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.

61247 lines
1.9MB

  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. #define JUCE_PUBLIC_INCLUDES 1
  36. // (this includes things that need defining outside of the JUCE namespace)
  37. /*** Start of inlined file: juce_StandardHeader.h ***/
  38. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  39. #define __JUCE_STANDARDHEADER_JUCEHEADER__
  40. /** Current Juce version number.
  41. See also SystemStats::getJUCEVersion() for a string version.
  42. */
  43. #define JUCE_MAJOR_VERSION 1
  44. #define JUCE_MINOR_VERSION 52
  45. #define JUCE_BUILDNUMBER 33
  46. /** Current Juce version number.
  47. Bits 16 to 32 = major version.
  48. Bits 8 to 16 = minor version.
  49. Bits 0 to 8 = point release (not currently used).
  50. See also SystemStats::getJUCEVersion() for a string version.
  51. */
  52. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8) + JUCE_BUILDNUMBER)
  53. /*** Start of inlined file: juce_TargetPlatform.h ***/
  54. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  55. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  56. /* This file figures out which platform is being built, and defines some macros
  57. that the rest of the code can use for OS-specific compilation.
  58. Macros that will be set here are:
  59. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  60. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  61. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  62. - Either JUCE_INTEL or JUCE_PPC
  63. - Either JUCE_GCC or JUCE_MSVC
  64. */
  65. #if (defined (_WIN32) || defined (_WIN64))
  66. #define JUCE_WIN32 1
  67. #define JUCE_WINDOWS 1
  68. #elif defined (LINUX) || defined (__linux__)
  69. #define JUCE_LINUX 1
  70. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  71. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  72. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  73. #define JUCE_IPHONE 1
  74. #else
  75. #define JUCE_MAC 1
  76. #endif
  77. #else
  78. #error "Unknown platform!"
  79. #endif
  80. #if JUCE_WINDOWS
  81. #ifdef _MSC_VER
  82. #ifdef _WIN64
  83. #define JUCE_64BIT 1
  84. #else
  85. #define JUCE_32BIT 1
  86. #endif
  87. #endif
  88. #ifdef _DEBUG
  89. #define JUCE_DEBUG 1
  90. #endif
  91. #ifdef __MINGW32__
  92. #define JUCE_MINGW 1
  93. #endif
  94. /** If defined, this indicates that the processor is little-endian. */
  95. #define JUCE_LITTLE_ENDIAN 1
  96. #define JUCE_INTEL 1
  97. #endif
  98. #if JUCE_MAC
  99. #ifndef NDEBUG
  100. #define JUCE_DEBUG 1
  101. #endif
  102. #ifdef __LITTLE_ENDIAN__
  103. #define JUCE_LITTLE_ENDIAN 1
  104. #else
  105. #define JUCE_BIG_ENDIAN 1
  106. #endif
  107. #if defined (__ppc__) || defined (__ppc64__)
  108. #define JUCE_PPC 1
  109. #else
  110. #define JUCE_INTEL 1
  111. #endif
  112. #ifdef __LP64__
  113. #define JUCE_64BIT 1
  114. #else
  115. #define JUCE_32BIT 1
  116. #endif
  117. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  118. #error "Building for OSX 10.3 is no longer supported!"
  119. #endif
  120. #ifndef MAC_OS_X_VERSION_10_5
  121. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  122. #endif
  123. #endif
  124. #if JUCE_IPHONE
  125. #ifndef NDEBUG
  126. #define JUCE_DEBUG 1
  127. #endif
  128. #ifdef __LITTLE_ENDIAN__
  129. #define JUCE_LITTLE_ENDIAN 1
  130. #else
  131. #define JUCE_BIG_ENDIAN 1
  132. #endif
  133. #endif
  134. #if JUCE_LINUX
  135. #ifdef _DEBUG
  136. #define JUCE_DEBUG 1
  137. #endif
  138. // Allow override for big-endian Linux platforms
  139. #ifndef JUCE_BIG_ENDIAN
  140. #define JUCE_LITTLE_ENDIAN 1
  141. #endif
  142. #if defined (__LP64__) || defined (_LP64)
  143. #define JUCE_64BIT 1
  144. #else
  145. #define JUCE_32BIT 1
  146. #endif
  147. #define JUCE_INTEL 1
  148. #endif
  149. // Compiler type macros.
  150. #ifdef __GNUC__
  151. #define JUCE_GCC 1
  152. #elif defined (_MSC_VER)
  153. #define JUCE_MSVC 1
  154. #if _MSC_VER >= 1400
  155. #define JUCE_USE_INTRINSICS 1
  156. #endif
  157. #else
  158. #error unknown compiler
  159. #endif
  160. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  161. /*** End of inlined file: juce_TargetPlatform.h ***/
  162. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  163. /*** Start of inlined file: juce_Config.h ***/
  164. #ifndef __JUCE_CONFIG_JUCEHEADER__
  165. #define __JUCE_CONFIG_JUCEHEADER__
  166. /*
  167. This file contains macros that enable/disable various JUCE features.
  168. */
  169. /** The name of the namespace that all Juce classes and functions will be
  170. put inside. If this is not defined, no namespace will be used.
  171. */
  172. #ifndef JUCE_NAMESPACE
  173. #define JUCE_NAMESPACE juce
  174. #endif
  175. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  176. project settings, but if you define this value, you can override this to force
  177. it to be true or false.
  178. */
  179. #ifndef JUCE_FORCE_DEBUG
  180. //#define JUCE_FORCE_DEBUG 0
  181. #endif
  182. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  183. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  184. Enabling it will also leave this turned on in release builds. When it's disabled,
  185. however, the jassert and jassertfalse macros will not be compiled in a
  186. release build.
  187. @see jassert, jassertfalse, Logger
  188. */
  189. #ifndef JUCE_LOG_ASSERTIONS
  190. #define JUCE_LOG_ASSERTIONS 0
  191. #endif
  192. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  193. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  194. on your Windows build machine.
  195. See the comments in the ASIOAudioIODevice class's header file for more
  196. info about this.
  197. */
  198. #ifndef JUCE_ASIO
  199. #define JUCE_ASIO 0
  200. #endif
  201. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  202. */
  203. #ifndef JUCE_WASAPI
  204. #define JUCE_WASAPI 0
  205. #endif
  206. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  207. */
  208. #ifndef JUCE_DIRECTSOUND
  209. #define JUCE_DIRECTSOUND 1
  210. #endif
  211. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  212. #ifndef JUCE_ALSA
  213. #define JUCE_ALSA 1
  214. #endif
  215. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  216. #ifndef JUCE_JACK
  217. #define JUCE_JACK 0
  218. #endif
  219. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  220. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  221. installed, and its header files will need to be on your include path.
  222. */
  223. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  224. #define JUCE_QUICKTIME 0
  225. #endif
  226. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  227. #undef JUCE_QUICKTIME
  228. #endif
  229. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  230. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  231. */
  232. #ifndef JUCE_OPENGL
  233. #define JUCE_OPENGL 1
  234. #endif
  235. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  236. If your app doesn't need to read FLAC files, you might want to disable this to
  237. reduce the size of your codebase and build time.
  238. */
  239. #ifndef JUCE_USE_FLAC
  240. #define JUCE_USE_FLAC 1
  241. #endif
  242. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  243. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  244. reduce the size of your codebase and build time.
  245. */
  246. #ifndef JUCE_USE_OGGVORBIS
  247. #define JUCE_USE_OGGVORBIS 1
  248. #endif
  249. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  250. Unless you're using CD-burning, you should probably turn this flag off to
  251. reduce code size.
  252. */
  253. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  254. #define JUCE_USE_CDBURNER 0
  255. #endif
  256. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  257. Unless you're using CD-reading, you should probably turn this flag off to
  258. reduce code size.
  259. */
  260. #ifndef JUCE_USE_CDREADER
  261. #define JUCE_USE_CDREADER 0
  262. #endif
  263. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  264. */
  265. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  266. #define JUCE_USE_CAMERA 0
  267. #endif
  268. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  269. gets repainted will flash in a random colour, so that you can check exactly how much and how
  270. often your components are being drawn.
  271. */
  272. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  273. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  274. #endif
  275. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  276. Unless you specifically want to disable this, it's best to leave this option turned on.
  277. */
  278. #ifndef JUCE_USE_XINERAMA
  279. #define JUCE_USE_XINERAMA 1
  280. #endif
  281. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  282. turned on unless you have a good reason to disable it.
  283. */
  284. #ifndef JUCE_USE_XSHM
  285. #define JUCE_USE_XSHM 1
  286. #endif
  287. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  288. */
  289. #ifndef JUCE_USE_XRENDER
  290. #define JUCE_USE_XRENDER 0
  291. #endif
  292. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  293. unless you have a good reason to disable it.
  294. */
  295. #ifndef JUCE_USE_XCURSOR
  296. #define JUCE_USE_XCURSOR 1
  297. #endif
  298. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  299. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  300. you're building a plugin hosting app.
  301. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  302. */
  303. #ifndef JUCE_PLUGINHOST_VST
  304. #define JUCE_PLUGINHOST_VST 0
  305. #endif
  306. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  307. of course, and should only be enabled if you're building a plugin hosting app.
  308. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  309. */
  310. #ifndef JUCE_PLUGINHOST_AU
  311. #define JUCE_PLUGINHOST_AU 0
  312. #endif
  313. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  314. This should be enabled if you're writing a console application.
  315. */
  316. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  317. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  318. #endif
  319. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  320. If you're not using any embedded web-pages, turning this off may reduce your code size.
  321. */
  322. #ifndef JUCE_WEB_BROWSER
  323. #define JUCE_WEB_BROWSER 1
  324. #endif
  325. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  326. Carbon isn't required for a normal app, but may be needed by specialised classes like
  327. plugin-hosts, which support older APIs.
  328. */
  329. #ifndef JUCE_SUPPORT_CARBON
  330. #define JUCE_SUPPORT_CARBON 1
  331. #endif
  332. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  333. You might need to tweak this if you're linking to an external zlib library in your app,
  334. but for normal apps, this option should be left alone.
  335. */
  336. #ifndef JUCE_INCLUDE_ZLIB_CODE
  337. #define JUCE_INCLUDE_ZLIB_CODE 1
  338. #endif
  339. #ifndef JUCE_INCLUDE_FLAC_CODE
  340. #define JUCE_INCLUDE_FLAC_CODE 1
  341. #endif
  342. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  343. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  344. #endif
  345. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  346. #define JUCE_INCLUDE_PNGLIB_CODE 1
  347. #endif
  348. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  349. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  350. #endif
  351. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  352. (Currently, this only affects Windows builds in debug mode).
  353. */
  354. #ifndef JUCE_CHECK_MEMORY_LEAKS
  355. #define JUCE_CHECK_MEMORY_LEAKS 1
  356. #endif
  357. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  358. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  359. are passed to the JUCEApplication::unhandledException() callback for logging.
  360. */
  361. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  362. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  363. #endif
  364. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  365. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  366. #undef JUCE_QUICKTIME
  367. #define JUCE_QUICKTIME 0
  368. #undef JUCE_OPENGL
  369. #define JUCE_OPENGL 0
  370. #undef JUCE_USE_CDBURNER
  371. #define JUCE_USE_CDBURNER 0
  372. #undef JUCE_USE_CDREADER
  373. #define JUCE_USE_CDREADER 0
  374. #undef JUCE_WEB_BROWSER
  375. #define JUCE_WEB_BROWSER 0
  376. #undef JUCE_PLUGINHOST_AU
  377. #define JUCE_PLUGINHOST_AU 0
  378. #undef JUCE_PLUGINHOST_VST
  379. #define JUCE_PLUGINHOST_VST 0
  380. #endif
  381. #endif
  382. /*** End of inlined file: juce_Config.h ***/
  383. #ifdef JUCE_NAMESPACE
  384. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  385. #define END_JUCE_NAMESPACE }
  386. #else
  387. #define BEGIN_JUCE_NAMESPACE
  388. #define END_JUCE_NAMESPACE
  389. #endif
  390. /*** Start of inlined file: juce_PlatformDefs.h ***/
  391. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  392. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  393. /* This file defines miscellaneous macros for debugging, assertions, etc.
  394. */
  395. #ifdef JUCE_FORCE_DEBUG
  396. #undef JUCE_DEBUG
  397. #if JUCE_FORCE_DEBUG
  398. #define JUCE_DEBUG 1
  399. #endif
  400. #endif
  401. /** This macro defines the C calling convention used as the standard for Juce calls. */
  402. #if JUCE_MSVC
  403. #define JUCE_CALLTYPE __stdcall
  404. #else
  405. #define JUCE_CALLTYPE
  406. #endif
  407. // Debugging and assertion macros
  408. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  409. #if JUCE_LOG_ASSERTIONS
  410. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  411. #elif JUCE_DEBUG
  412. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  413. #else
  414. #define juce_LogCurrentAssertion
  415. #endif
  416. #if JUCE_DEBUG
  417. // If debugging is enabled..
  418. /** Writes a string to the standard error stream.
  419. This is only compiled in a debug build.
  420. @see Logger::outputDebugString
  421. */
  422. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  423. // Assertions..
  424. #if JUCE_WINDOWS || DOXYGEN
  425. #if JUCE_USE_INTRINSICS
  426. #pragma intrinsic (__debugbreak)
  427. /** This will try to break the debugger if one is currently hosting this app.
  428. @see jassert()
  429. */
  430. #define juce_breakDebugger __debugbreak();
  431. #elif JUCE_GCC
  432. /** This will try to break the debugger if one is currently hosting this app.
  433. @see jassert()
  434. */
  435. #define juce_breakDebugger asm("int $3");
  436. #else
  437. /** This will try to break the debugger if one is currently hosting this app.
  438. @see jassert()
  439. */
  440. #define juce_breakDebugger { __asm int 3 }
  441. #endif
  442. #elif JUCE_MAC
  443. #define juce_breakDebugger Debugger();
  444. #elif JUCE_IPHONE
  445. #define juce_breakDebugger kill (0, SIGTRAP);
  446. #elif JUCE_LINUX
  447. #define juce_breakDebugger kill (0, SIGTRAP);
  448. #endif
  449. /** This will always cause an assertion failure.
  450. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  451. in juce_Config.h).
  452. @see jassert()
  453. */
  454. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  455. /** Platform-independent assertion macro.
  456. This gets optimised out when not being built with debugging turned on.
  457. Be careful not to call any functions within its arguments that are vital to
  458. the behaviour of the program, because these won't get called in the release
  459. build.
  460. @see jassertfalse
  461. */
  462. #define jassert(expression) { if (! (expression)) jassertfalse; }
  463. #else
  464. // If debugging is disabled, these dummy debug and assertion macros are used..
  465. #define DBG(dbgtext)
  466. #define jassertfalse { juce_LogCurrentAssertion }
  467. #if JUCE_LOG_ASSERTIONS
  468. #define jassert(expression) { if (! (expression)) jassertfalse; }
  469. #else
  470. #define jassert(a) { }
  471. #endif
  472. #endif
  473. #ifndef DOXYGEN
  474. template <bool b> struct JuceStaticAssert;
  475. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  476. #endif
  477. /** A compile-time assertion macro.
  478. If the expression parameter is false, the macro will cause a compile error.
  479. */
  480. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  481. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  482. #define JUCE_TRY try
  483. #define JUCE_CATCH_ALL catch (...) {}
  484. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  485. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  486. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  487. #else
  488. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  489. object so they can be logged by the application if it wants to.
  490. */
  491. #define JUCE_CATCH_EXCEPTION \
  492. catch (const std::exception& e) \
  493. { \
  494. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  495. } \
  496. catch (...) \
  497. { \
  498. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  499. }
  500. #endif
  501. #else
  502. #define JUCE_TRY
  503. #define JUCE_CATCH_EXCEPTION
  504. #define JUCE_CATCH_ALL
  505. #define JUCE_CATCH_ALL_ASSERT
  506. #endif
  507. // Macros for inlining.
  508. #if JUCE_MSVC
  509. /** A platform-independent way of forcing an inline function.
  510. Use the syntax: @code
  511. forcedinline void myfunction (int x)
  512. @endcode
  513. */
  514. #ifndef JUCE_DEBUG
  515. #define forcedinline __forceinline
  516. #else
  517. #define forcedinline inline
  518. #endif
  519. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  520. #else
  521. /** A platform-independent way of forcing an inline function.
  522. Use the syntax: @code
  523. forcedinline void myfunction (int x)
  524. @endcode
  525. */
  526. #ifndef JUCE_DEBUG
  527. #define forcedinline inline __attribute__((always_inline))
  528. #else
  529. #define forcedinline inline
  530. #endif
  531. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  532. #endif
  533. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  534. /*** End of inlined file: juce_PlatformDefs.h ***/
  535. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  536. #if JUCE_MSVC
  537. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  538. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  539. #endif
  540. #pragma warning (push)
  541. #pragma warning (disable: 4514 4245 4100)
  542. #endif
  543. #include <cstdlib>
  544. #include <cstdarg>
  545. #include <climits>
  546. #include <limits>
  547. #include <cmath>
  548. #include <cwchar>
  549. #include <stdexcept>
  550. #include <typeinfo>
  551. #include <cstring>
  552. #include <cstdio>
  553. #include <iostream>
  554. #if JUCE_USE_INTRINSICS
  555. #include <intrin.h>
  556. #endif
  557. #if JUCE_MAC || JUCE_IPHONE
  558. #include <libkern/OSAtomic.h>
  559. #endif
  560. #if JUCE_LINUX
  561. #include <signal.h>
  562. #if __INTEL_COMPILER
  563. #if __ia64__
  564. #include <ia64intrin.h>
  565. #else
  566. #include <ia32intrin.h>
  567. #endif
  568. #endif
  569. #endif
  570. #if JUCE_MSVC && JUCE_DEBUG
  571. #include <crtdbg.h>
  572. #endif
  573. #if JUCE_MSVC
  574. #include <malloc.h>
  575. #pragma warning (pop)
  576. #if ! JUCE_PUBLIC_INCLUDES
  577. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  578. #endif
  579. #endif
  580. // DLL building settings on Win32
  581. #if JUCE_MSVC
  582. #ifdef JUCE_DLL_BUILD
  583. #define JUCE_API __declspec (dllexport)
  584. #pragma warning (disable: 4251)
  585. #elif defined (JUCE_DLL)
  586. #define JUCE_API __declspec (dllimport)
  587. #pragma warning (disable: 4251)
  588. #endif
  589. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  590. #ifdef JUCE_DLL_BUILD
  591. #define JUCE_API __attribute__ ((visibility("default")))
  592. #endif
  593. #endif
  594. #ifndef JUCE_API
  595. /** This macro is added to all juce public class declarations. */
  596. #define JUCE_API
  597. #endif
  598. /** This macro is added to all juce public function declarations. */
  599. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  600. // Now include some basics that are needed by most of the Juce classes...
  601. BEGIN_JUCE_NAMESPACE
  602. extern bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger();
  603. #if JUCE_LOG_ASSERTIONS
  604. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  605. #endif
  606. /*** Start of inlined file: juce_Memory.h ***/
  607. #ifndef __JUCE_MEMORY_JUCEHEADER__
  608. #define __JUCE_MEMORY_JUCEHEADER__
  609. /*
  610. This file defines the various juce_malloc(), juce_free() macros that should be used in
  611. preference to the standard calls.
  612. */
  613. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  614. #ifndef JUCE_DLL
  615. // Win32 debug non-DLL versions..
  616. /** This should be used instead of calling malloc directly.
  617. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  618. */
  619. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  620. /** This should be used instead of calling calloc directly.
  621. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  622. */
  623. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  624. /** This should be used instead of calling realloc directly.
  625. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  626. */
  627. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  628. /** This should be used instead of calling free directly.
  629. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  630. */
  631. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  632. #else
  633. // Win32 debug DLL versions..
  634. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  635. // way all juce calls in the DLL and in the host API will all use the same allocator.
  636. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  637. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  638. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  639. extern JUCE_API void juce_DebugFree (void* const block);
  640. /** This should be used instead of calling malloc directly.
  641. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  642. */
  643. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  644. /** This should be used instead of calling calloc directly.
  645. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  646. */
  647. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  648. /** This should be used instead of calling realloc directly.
  649. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  650. */
  651. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  652. /** This should be used instead of calling free directly.
  653. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  654. */
  655. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  656. #endif
  657. #if ! defined (_AFXDLL)
  658. /** This macro can be added to classes to add extra debugging information to the memory
  659. allocated for them, so you can see the type of objects involved when there's a dump
  660. of leaked objects at program shutdown. (Only works on win32 at the moment).
  661. */
  662. #define juce_UseDebuggingNewOperator \
  663. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  664. static void* operator new (size_t, void* p) { return p; } \
  665. static void operator delete (void* p) { juce_free (p); } \
  666. static void operator delete (void*, void*) { }
  667. #endif
  668. #elif defined (JUCE_DLL)
  669. // Win32 DLL (release) versions..
  670. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  671. // way all juce calls in the DLL and in the host API will all use the same allocator.
  672. extern JUCE_API void* juce_Malloc (const int size);
  673. extern JUCE_API void* juce_Calloc (const int size);
  674. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  675. extern JUCE_API void juce_Free (void* const block);
  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) JUCE_NAMESPACE::juce_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) JUCE_NAMESPACE::juce_Calloc (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) JUCE_NAMESPACE::juce_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) JUCE_NAMESPACE::juce_Free (location)
  692. #define juce_UseDebuggingNewOperator \
  693. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  694. static void* operator new (size_t, void* p) { return p; } \
  695. static void operator delete (void* p) { juce_free (p); } \
  696. static void operator delete (void*, void*) { }
  697. #else
  698. // Mac, Linux and Win32 (release) versions..
  699. /** This should be used instead of calling malloc directly.
  700. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  701. */
  702. #define juce_malloc(numBytes) malloc (numBytes)
  703. /** This should be used instead of calling calloc directly.
  704. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  705. */
  706. #define juce_calloc(numBytes) calloc (1, numBytes)
  707. /** This should be used instead of calling realloc directly.
  708. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  709. */
  710. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  711. /** This should be used instead of calling free directly.
  712. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  713. */
  714. #define juce_free(location) free (location)
  715. #endif
  716. /** This macro can be added to classes to add extra debugging information to the memory
  717. allocated for them, so you can see the type of objects involved when there's a dump
  718. of leaked objects at program shutdown. (Only works on win32 at the moment).
  719. Note that if you create a class that inherits from a class that uses this macro,
  720. your class must also use the macro, otherwise you'll probably get compile errors
  721. because of ambiguous new operators.
  722. Most of the JUCE classes use it, so see these for examples of where it should go.
  723. */
  724. #ifndef juce_UseDebuggingNewOperator
  725. #define juce_UseDebuggingNewOperator
  726. #endif
  727. #if JUCE_MSVC
  728. /** This is a compiler-independent way of declaring a variable as being thread-local.
  729. E.g.
  730. @code
  731. juce_ThreadLocal int myVariable;
  732. @endcode
  733. */
  734. #define juce_ThreadLocal __declspec(thread)
  735. #else
  736. #define juce_ThreadLocal __thread
  737. #endif
  738. #if JUCE_MINGW
  739. /** This allocator is not defined in mingw gcc. */
  740. #define alloca __builtin_alloca
  741. #endif
  742. /** Clears a block of memory. */
  743. inline void zeromem (void* memory, size_t numBytes) { memset (memory, 0, numBytes); }
  744. /** Clears a reference to a local structure. */
  745. template <typename Type>
  746. inline void zerostruct (Type& structure) { memset (&structure, 0, sizeof (structure)); }
  747. /** A handy function that calls delete on a pointer if it's non-zero, and then sets
  748. the pointer to null.
  749. */
  750. template <typename Type>
  751. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  752. #endif // __JUCE_MEMORY_JUCEHEADER__
  753. /*** End of inlined file: juce_Memory.h ***/
  754. /*** Start of inlined file: juce_MathsFunctions.h ***/
  755. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  756. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  757. /*
  758. This file sets up some handy mathematical typdefs and functions.
  759. */
  760. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  761. /** A platform-independent 8-bit signed integer type. */
  762. typedef signed char int8;
  763. /** A platform-independent 8-bit unsigned integer type. */
  764. typedef unsigned char uint8;
  765. /** A platform-independent 16-bit signed integer type. */
  766. typedef signed short int16;
  767. /** A platform-independent 16-bit unsigned integer type. */
  768. typedef unsigned short uint16;
  769. /** A platform-independent 32-bit signed integer type. */
  770. typedef signed int int32;
  771. /** A platform-independent 32-bit unsigned integer type. */
  772. typedef unsigned int uint32;
  773. #if JUCE_MSVC
  774. /** A platform-independent 64-bit integer type. */
  775. typedef __int64 int64;
  776. /** A platform-independent 64-bit unsigned integer type. */
  777. typedef unsigned __int64 uint64;
  778. /** A platform-independent macro for writing 64-bit literals, needed because
  779. different compilers have different syntaxes for this.
  780. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  781. GCC, or 0x1000000000 for MSVC.
  782. */
  783. #define literal64bit(longLiteral) ((__int64) longLiteral)
  784. #else
  785. /** A platform-independent 64-bit integer type. */
  786. typedef long long int64;
  787. /** A platform-independent 64-bit unsigned integer type. */
  788. typedef unsigned long long uint64;
  789. /** A platform-independent macro for writing 64-bit literals, needed because
  790. different compilers have different syntaxes for this.
  791. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  792. GCC, or 0x1000000000 for MSVC.
  793. */
  794. #define literal64bit(longLiteral) (longLiteral##LL)
  795. #endif
  796. #if JUCE_64BIT
  797. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  798. typedef int64 pointer_sized_int;
  799. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  800. typedef uint64 pointer_sized_uint;
  801. #elif _MSC_VER >= 1300
  802. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  803. typedef _W64 int pointer_sized_int;
  804. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  805. typedef _W64 unsigned int pointer_sized_uint;
  806. #else
  807. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  808. typedef int pointer_sized_int;
  809. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  810. typedef unsigned int pointer_sized_uint;
  811. #endif
  812. /** A platform-independent unicode character type. */
  813. typedef wchar_t juce_wchar;
  814. // Some indispensible min/max functions
  815. /** Returns the larger of two values. */
  816. template <typename Type>
  817. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  818. /** Returns the larger of three values. */
  819. template <typename Type>
  820. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  821. /** Returns the larger of four values. */
  822. template <typename Type>
  823. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  824. /** Returns the smaller of two values. */
  825. template <typename Type>
  826. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  827. /** Returns the smaller of three values. */
  828. template <typename Type>
  829. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  830. /** Returns the smaller of four values. */
  831. template <typename Type>
  832. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  833. /** Constrains a value to keep it within a given range.
  834. This will check that the specified value lies between the lower and upper bounds
  835. specified, and if not, will return the nearest value that would be in-range. Effectively,
  836. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  837. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  838. the results will be unpredictable.
  839. @param lowerLimit the minimum value to return
  840. @param upperLimit the maximum value to return
  841. @param valueToConstrain the value to try to return
  842. @returns the closest value to valueToConstrain which lies between lowerLimit
  843. and upperLimit (inclusive)
  844. @see jlimit0To, jmin, jmax
  845. */
  846. template <typename Type>
  847. inline Type jlimit (const Type lowerLimit,
  848. const Type upperLimit,
  849. const Type valueToConstrain) throw()
  850. {
  851. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  852. return (valueToConstrain < lowerLimit) ? lowerLimit
  853. : ((upperLimit < valueToConstrain) ? upperLimit
  854. : valueToConstrain);
  855. }
  856. /** Handy function to swap two values over.
  857. */
  858. template <typename Type>
  859. inline void swapVariables (Type& variable1, Type& variable2)
  860. {
  861. const Type tempVal = variable1;
  862. variable1 = variable2;
  863. variable2 = tempVal;
  864. }
  865. /** Handy function for getting the number of elements in a simple const C array.
  866. E.g.
  867. @code
  868. static int myArray[] = { 1, 2, 3 };
  869. int numElements = numElementsInArray (myArray) // returns 3
  870. @endcode
  871. */
  872. template <typename Type>
  873. inline int numElementsInArray (Type& array)
  874. {
  875. (void) array; // (required to avoid a spurious warning in MS compilers)
  876. return static_cast<int> (sizeof (array) / sizeof (array[0]));
  877. }
  878. // Some useful maths functions that aren't always present with all compilers and build settings.
  879. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  880. versions of these functions of various platforms and compilers. */
  881. inline double juce_hypot (double a, double b)
  882. {
  883. #if JUCE_WINDOWS
  884. return _hypot (a, b);
  885. #else
  886. return hypot (a, b);
  887. #endif
  888. }
  889. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  890. versions of these functions of various platforms and compilers. */
  891. inline float juce_hypotf (float a, float b) throw()
  892. {
  893. #if JUCE_WINDOWS
  894. return (float) _hypot (a, b);
  895. #else
  896. return hypotf (a, b);
  897. #endif
  898. }
  899. /** 64-bit abs function. */
  900. inline int64 abs64 (const int64 n) throw()
  901. {
  902. return (n >= 0) ? n : -n;
  903. }
  904. /** This templated negate function will negate pointers as well as integers */
  905. template <typename Type>
  906. inline Type juce_negate (Type n) throw()
  907. {
  908. return sizeof (Type) == 1 ? (Type) -(char) n
  909. : (sizeof (Type) == 2 ? (Type) -(short) n
  910. : (sizeof (Type) == 4 ? (Type) -(int) n
  911. : ((Type) -(int64) n)));
  912. }
  913. /** This templated negate function will negate pointers as well as integers */
  914. template <typename Type>
  915. inline Type* juce_negate (Type* n) throw()
  916. {
  917. return (Type*) -(pointer_sized_int) n;
  918. }
  919. /** A predefined value for Pi, at double-precision.
  920. @see float_Pi
  921. */
  922. const double double_Pi = 3.1415926535897932384626433832795;
  923. /** A predefined value for Pi, at sngle-precision.
  924. @see double_Pi
  925. */
  926. const float float_Pi = 3.14159265358979323846f;
  927. /** The isfinite() method seems to vary between platforms, so this is a
  928. platform-independent function for it.
  929. */
  930. template <typename FloatingPointType>
  931. inline bool juce_isfinite (FloatingPointType value)
  932. {
  933. #if JUCE_WINDOWS
  934. return _finite (value);
  935. #else
  936. return std::isfinite (value);
  937. #endif
  938. }
  939. /** Fast floating-point-to-integer conversion.
  940. This is faster than using the normal c++ cast to convert a float to an int, and
  941. it will round the value to the nearest integer, rather than rounding it down
  942. like the normal cast does.
  943. Note that this routine gets its speed at the expense of some accuracy, and when
  944. rounding values whose floating point component is exactly 0.5, odd numbers and
  945. even numbers will be rounded up or down differently.
  946. */
  947. template <typename FloatType>
  948. inline int roundToInt (const FloatType value) throw()
  949. {
  950. union { int asInt[2]; double asDouble; } n;
  951. n.asDouble = ((double) value) + 6755399441055744.0;
  952. #if JUCE_BIG_ENDIAN
  953. return n.asInt [1];
  954. #else
  955. return n.asInt [0];
  956. #endif
  957. }
  958. /** Fast floating-point-to-integer conversion.
  959. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  960. fine for values above zero, but negative numbers are rounded the wrong way.
  961. */
  962. inline int roundToIntAccurate (const double value) throw()
  963. {
  964. return roundToInt (value + 1.5e-8);
  965. }
  966. /** Fast floating-point-to-integer conversion.
  967. This is faster than using the normal c++ cast to convert a double to an int, and
  968. it will round the value to the nearest integer, rather than rounding it down
  969. like the normal cast does.
  970. Note that this routine gets its speed at the expense of some accuracy, and when
  971. rounding values whose floating point component is exactly 0.5, odd numbers and
  972. even numbers will be rounded up or down differently. For a more accurate conversion,
  973. see roundDoubleToIntAccurate().
  974. */
  975. inline int roundDoubleToInt (const double value) throw()
  976. {
  977. return roundToInt (value);
  978. }
  979. /** Fast floating-point-to-integer conversion.
  980. This is faster than using the normal c++ cast to convert a float to an int, and
  981. it will round the value to the nearest integer, rather than rounding it down
  982. like the normal cast does.
  983. Note that this routine gets its speed at the expense of some accuracy, and when
  984. rounding values whose floating point component is exactly 0.5, odd numbers and
  985. even numbers will be rounded up or down differently.
  986. */
  987. inline int roundFloatToInt (const float value) throw()
  988. {
  989. return roundToInt (value);
  990. }
  991. /** This namespace contains a few template classes for helping work out class type variations.
  992. */
  993. namespace TypeHelpers
  994. {
  995. #if defined (_MSC_VER) && _MSC_VER <= 1400
  996. #define PARAMETER_TYPE(a) a
  997. #else
  998. /** The ParameterType struct is used to find the best type to use when passing some kind
  999. of object as a parameter.
  1000. Of course, this is only likely to be useful in certain esoteric template situations.
  1001. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1002. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1003. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1004. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1005. pass-by-value, but passing objects as a const reference, to avoid copying.
  1006. */
  1007. template <typename Type> struct ParameterType { typedef const Type& type; };
  1008. #if ! DOXYGEN
  1009. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1010. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1011. template <> struct ParameterType <char> { typedef char type; };
  1012. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1013. template <> struct ParameterType <short> { typedef short type; };
  1014. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1015. template <> struct ParameterType <int> { typedef int type; };
  1016. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1017. template <> struct ParameterType <long> { typedef long type; };
  1018. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1019. template <> struct ParameterType <int64> { typedef int64 type; };
  1020. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1021. template <> struct ParameterType <bool> { typedef bool type; };
  1022. template <> struct ParameterType <float> { typedef float type; };
  1023. template <> struct ParameterType <double> { typedef double type; };
  1024. #endif
  1025. /** A helpful macro to simplify the use of the ParameterType template.
  1026. @see ParameterType
  1027. */
  1028. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1029. #endif
  1030. }
  1031. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1032. /*** End of inlined file: juce_MathsFunctions.h ***/
  1033. /*** Start of inlined file: juce_ByteOrder.h ***/
  1034. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1035. #define __JUCE_BYTEORDER_JUCEHEADER__
  1036. /** Contains static methods for converting the byte order between different
  1037. endiannesses.
  1038. */
  1039. class JUCE_API ByteOrder
  1040. {
  1041. public:
  1042. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1043. static uint16 swap (uint16 value);
  1044. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1045. static uint32 swap (uint32 value);
  1046. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1047. static uint64 swap (uint64 value);
  1048. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1049. static uint16 swapIfBigEndian (uint16 value);
  1050. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1051. static uint32 swapIfBigEndian (uint32 value);
  1052. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1053. static uint64 swapIfBigEndian (uint64 value);
  1054. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1055. static uint16 swapIfLittleEndian (uint16 value);
  1056. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1057. static uint32 swapIfLittleEndian (uint32 value);
  1058. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1059. static uint64 swapIfLittleEndian (uint64 value);
  1060. /** Turns 4 bytes into a little-endian integer. */
  1061. static uint32 littleEndianInt (const void* bytes);
  1062. /** Turns 2 bytes into a little-endian integer. */
  1063. static uint16 littleEndianShort (const void* bytes);
  1064. /** Turns 4 bytes into a big-endian integer. */
  1065. static uint32 bigEndianInt (const void* bytes);
  1066. /** Turns 2 bytes into a big-endian integer. */
  1067. static uint16 bigEndianShort (const void* bytes);
  1068. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1069. static int littleEndian24Bit (const char* bytes);
  1070. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1071. static int bigEndian24Bit (const char* bytes);
  1072. /** Copies a 24-bit number to 3 little-endian bytes. */
  1073. static void littleEndian24BitToChars (int value, char* destBytes);
  1074. /** Copies a 24-bit number to 3 big-endian bytes. */
  1075. static void bigEndian24BitToChars (int value, char* destBytes);
  1076. /** Returns true if the current CPU is big-endian. */
  1077. static bool isBigEndian();
  1078. private:
  1079. ByteOrder();
  1080. ByteOrder (const ByteOrder&);
  1081. ByteOrder& operator= (const ByteOrder&);
  1082. };
  1083. #if JUCE_USE_INTRINSICS
  1084. #pragma intrinsic (_byteswap_ulong)
  1085. #endif
  1086. inline uint16 ByteOrder::swap (uint16 n)
  1087. {
  1088. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1089. return static_cast <uint16> (_byteswap_ushort (n));
  1090. #else
  1091. return static_cast <uint16> ((n << 8) | (n >> 8));
  1092. #endif
  1093. }
  1094. inline uint32 ByteOrder::swap (uint32 n)
  1095. {
  1096. #if JUCE_MAC || JUCE_IPHONE
  1097. return OSSwapInt32 (n);
  1098. #elif JUCE_GCC
  1099. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1100. return n;
  1101. #elif JUCE_USE_INTRINSICS
  1102. return _byteswap_ulong (n);
  1103. #else
  1104. __asm {
  1105. mov eax, n
  1106. bswap eax
  1107. mov n, eax
  1108. }
  1109. return n;
  1110. #endif
  1111. }
  1112. inline uint64 ByteOrder::swap (uint64 value)
  1113. {
  1114. #if JUCE_MAC || JUCE_IPHONE
  1115. return OSSwapInt64 (value);
  1116. #elif JUCE_USE_INTRINSICS
  1117. return _byteswap_uint64 (value);
  1118. #else
  1119. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1120. #endif
  1121. }
  1122. #if JUCE_LITTLE_ENDIAN
  1123. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1124. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1125. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1126. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1127. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1128. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1129. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1130. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1131. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1132. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1133. inline bool ByteOrder::isBigEndian() { return false; }
  1134. #else
  1135. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1136. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1137. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1138. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1139. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1140. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1141. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1142. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1143. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1144. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1145. inline bool ByteOrder::isBigEndian() { return true; }
  1146. #endif
  1147. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1148. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1149. 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); }
  1150. 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); }
  1151. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1152. /*** End of inlined file: juce_ByteOrder.h ***/
  1153. /*** Start of inlined file: juce_Logger.h ***/
  1154. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1155. #define __JUCE_LOGGER_JUCEHEADER__
  1156. /*** Start of inlined file: juce_String.h ***/
  1157. #ifndef __JUCE_STRING_JUCEHEADER__
  1158. #define __JUCE_STRING_JUCEHEADER__
  1159. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1160. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1161. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1162. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1163. typedef juce_wchar tchar;
  1164. #if ! JUCE_DONT_DEFINE_MACROS
  1165. /** The 'T' macro allows a literal string to be compiled as unicode.
  1166. If you write your string literals in the form T("xyz"), it will be compiled as L"xyz"
  1167. or "xyz", depending on which representation is best for the String class to work with.
  1168. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1169. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1170. the juce/src directory) to avoid defining this macro. See the comments in
  1171. juce_withoutMacros.h for more info.
  1172. */
  1173. #define T(stringLiteral) JUCE_T(stringLiteral)
  1174. #endif
  1175. /**
  1176. A set of methods for manipulating characters and character strings, with
  1177. duplicate methods to handle 8-bit and unicode characters.
  1178. These are defined as wrappers around the basic C string handlers, to provide
  1179. a clean, cross-platform layer, (because various platforms differ in the
  1180. range of C library calls that they provide).
  1181. @see String
  1182. */
  1183. class JUCE_API CharacterFunctions
  1184. {
  1185. public:
  1186. static int length (const char* const s) throw();
  1187. static int length (const juce_wchar* const s) throw();
  1188. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1189. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1190. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1191. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1192. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1193. static void append (char* dest, const char* src) throw();
  1194. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1195. static int compare (const char* const s1, const char* const s2) throw();
  1196. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1197. static int compare (const juce_wchar* s1, const char* s2) throw();
  1198. static int compare (const char* s1, const juce_wchar* s2) throw();
  1199. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1200. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1201. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1202. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1203. static int compareIgnoreCase (const juce_wchar* s1, const char* s2) throw();
  1204. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1205. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1206. static const char* find (const char* const haystack, const char* const needle) throw();
  1207. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1208. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1209. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1210. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1211. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1212. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1213. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1214. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1215. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1216. static int getIntValue (const char* const s) throw();
  1217. static int getIntValue (const juce_wchar* s) throw();
  1218. static int64 getInt64Value (const char* s) throw();
  1219. static int64 getInt64Value (const juce_wchar* s) throw();
  1220. static double getDoubleValue (const char* const s) throw();
  1221. static double getDoubleValue (const juce_wchar* const s) throw();
  1222. static char toUpperCase (const char character) throw();
  1223. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1224. static void toUpperCase (char* s) throw();
  1225. static void toUpperCase (juce_wchar* s) throw();
  1226. static bool isUpperCase (const char character) throw();
  1227. static bool isUpperCase (const juce_wchar character) throw();
  1228. static char toLowerCase (const char character) throw();
  1229. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1230. static void toLowerCase (char* s) throw();
  1231. static void toLowerCase (juce_wchar* s) throw();
  1232. static bool isLowerCase (const char character) throw();
  1233. static bool isLowerCase (const juce_wchar character) throw();
  1234. static bool isWhitespace (const char character) throw();
  1235. static bool isWhitespace (const juce_wchar character) throw();
  1236. static bool isDigit (const char character) throw();
  1237. static bool isDigit (const juce_wchar character) throw();
  1238. static bool isLetter (const char character) throw();
  1239. static bool isLetter (const juce_wchar character) throw();
  1240. static bool isLetterOrDigit (const char character) throw();
  1241. static bool isLetterOrDigit (const juce_wchar character) throw();
  1242. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1243. hex digit.
  1244. */
  1245. static int getHexDigitValue (const juce_wchar digit) throw();
  1246. };
  1247. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1248. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1249. class OutputStream;
  1250. /**
  1251. The JUCE String class!
  1252. Using a reference-counted internal representation, these strings are fast
  1253. and efficient, and there are methods to do just about any operation you'll ever
  1254. dream of.
  1255. @see StringArray, StringPairArray
  1256. */
  1257. class JUCE_API String
  1258. {
  1259. public:
  1260. /** Creates an empty string.
  1261. @see empty
  1262. */
  1263. String() throw();
  1264. /** Creates a copy of another string. */
  1265. String (const String& other) throw();
  1266. /** Creates a string from a zero-terminated text string.
  1267. The string is assumed to be stored in the default system encoding.
  1268. */
  1269. String (const char* text);
  1270. /** Creates a string from an string of characters.
  1271. This will use up the the first maxChars characters of the string (or
  1272. less if the string is actually shorter)
  1273. */
  1274. String (const char* text, size_t maxChars);
  1275. /** Creates a string from a zero-terminated unicode text string. */
  1276. String (const juce_wchar* unicodeText);
  1277. /** Creates a string from a unicode text string.
  1278. This will use up the the first maxChars characters of the string (or
  1279. less if the string is actually shorter)
  1280. */
  1281. String (const juce_wchar* unicodeText, size_t maxChars);
  1282. /** Creates a string from a single character. */
  1283. static const String charToString (juce_wchar character);
  1284. /** Destructor. */
  1285. ~String() throw();
  1286. /** This is an empty string that can be used whenever one is needed.
  1287. It's better to use this than String() because it explains what's going on
  1288. and is more efficient.
  1289. */
  1290. static const String empty;
  1291. /** Generates a probably-unique 32-bit hashcode from this string. */
  1292. int hashCode() const throw();
  1293. /** Generates a probably-unique 64-bit hashcode from this string. */
  1294. int64 hashCode64() const throw();
  1295. /** Returns the number of characters in the string. */
  1296. int length() const throw();
  1297. // Assignment and concatenation operators..
  1298. /** Replaces this string's contents with another string. */
  1299. String& operator= (const String& other) throw();
  1300. /** Appends another string at the end of this one. */
  1301. String& operator+= (const juce_wchar* textToAppend);
  1302. /** Appends another string at the end of this one. */
  1303. String& operator+= (const String& stringToAppend);
  1304. /** Appends a character at the end of this string. */
  1305. String& operator+= (char characterToAppend);
  1306. /** Appends a character at the end of this string. */
  1307. String& operator+= (juce_wchar characterToAppend);
  1308. /** Appends a decimal number at the end of this string. */
  1309. String& operator+= (int numberToAppend);
  1310. /** Appends a decimal number at the end of this string. */
  1311. String& operator+= (unsigned int numberToAppend);
  1312. /** Appends a string at the end of this one.
  1313. @param textToAppend the string to add
  1314. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1315. */
  1316. void append (const juce_wchar* textToAppend, int maxCharsToTake);
  1317. // Comparison methods..
  1318. /** Returns true if the string contains no characters.
  1319. Note that there's also an isNotEmpty() method to help write readable code.
  1320. @see containsNonWhitespaceChars()
  1321. */
  1322. inline bool isEmpty() const throw() { return text[0] == 0; }
  1323. /** Returns true if the string contains at least one character.
  1324. Note that there's also an isEmpty() method to help write readable code.
  1325. @see containsNonWhitespaceChars()
  1326. */
  1327. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  1328. /** Case-insensitive comparison with another string. */
  1329. bool equalsIgnoreCase (const String& other) const throw();
  1330. /** Case-insensitive comparison with another string. */
  1331. bool equalsIgnoreCase (const juce_wchar* other) const throw();
  1332. /** Case-insensitive comparison with another string. */
  1333. bool equalsIgnoreCase (const char* other) const throw();
  1334. /** Case-sensitive comparison with another string.
  1335. @returns 0 if the two strings are identical; negative if this string
  1336. comes before the other one alphabetically, or positive if it
  1337. comes after it.
  1338. */
  1339. int compare (const String& other) const throw();
  1340. /** Case-sensitive comparison with another string.
  1341. @returns 0 if the two strings are identical; negative if this string
  1342. comes before the other one alphabetically, or positive if it
  1343. comes after it.
  1344. */
  1345. int compare (const char* other) const throw();
  1346. /** Case-sensitive comparison with another string.
  1347. @returns 0 if the two strings are identical; negative if this string
  1348. comes before the other one alphabetically, or positive if it
  1349. comes after it.
  1350. */
  1351. int compare (const juce_wchar* other) const throw();
  1352. /** Case-insensitive comparison with another string.
  1353. @returns 0 if the two strings are identical; negative if this string
  1354. comes before the other one alphabetically, or positive if it
  1355. comes after it.
  1356. */
  1357. int compareIgnoreCase (const String& other) const throw();
  1358. /** Lexicographic comparison with another string.
  1359. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1360. characters, making it good for sorting human-readable strings.
  1361. @returns 0 if the two strings are identical; negative if this string
  1362. comes before the other one alphabetically, or positive if it
  1363. comes after it.
  1364. */
  1365. int compareLexicographically (const String& other) const throw();
  1366. /** Tests whether the string begins with another string.
  1367. Uses a case-sensitive comparison.
  1368. */
  1369. bool startsWith (const String& text) const throw();
  1370. /** Tests whether the string begins with a particular character.
  1371. Uses a case-sensitive comparison.
  1372. */
  1373. bool startsWithChar (juce_wchar character) const throw();
  1374. /** Tests whether the string begins with another string.
  1375. Uses a case-insensitive comparison.
  1376. */
  1377. bool startsWithIgnoreCase (const String& text) const throw();
  1378. /** Tests whether the string ends with another string.
  1379. Uses a case-sensitive comparison.
  1380. */
  1381. bool endsWith (const String& text) const throw();
  1382. /** Tests whether the string ends with a particular character.
  1383. Uses a case-sensitive comparison.
  1384. */
  1385. bool endsWithChar (juce_wchar character) const throw();
  1386. /** Tests whether the string ends with another string.
  1387. Uses a case-insensitive comparison.
  1388. */
  1389. bool endsWithIgnoreCase (const String& text) const throw();
  1390. /** Tests whether the string contains another substring.
  1391. Uses a case-sensitive comparison.
  1392. */
  1393. bool contains (const String& text) const throw();
  1394. /** Tests whether the string contains a particular character.
  1395. Uses a case-sensitive comparison.
  1396. */
  1397. bool containsChar (juce_wchar character) const throw();
  1398. /** Tests whether the string contains another substring.
  1399. Uses a case-insensitive comparison.
  1400. */
  1401. bool containsIgnoreCase (const String& text) const throw();
  1402. /** Tests whether the string contains another substring as a distict word.
  1403. @returns true if the string contains this word, surrounded by
  1404. non-alphanumeric characters
  1405. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1406. */
  1407. bool containsWholeWord (const String& wordToLookFor) const throw();
  1408. /** Tests whether the string contains another substring as a distict word.
  1409. @returns true if the string contains this word, surrounded by
  1410. non-alphanumeric characters
  1411. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1412. */
  1413. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1414. /** Finds an instance of another substring if it exists as a distict word.
  1415. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1416. then this will return the index of the start of the substring. If it isn't
  1417. found, then it will return -1
  1418. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1419. */
  1420. int indexOfWholeWord (const String& wordToLookFor) const throw();
  1421. /** Finds an instance of another substring if it exists as a distict word.
  1422. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1423. then this will return the index of the start of the substring. If it isn't
  1424. found, then it will return -1
  1425. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1426. */
  1427. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1428. /** Looks for any of a set of characters in the string.
  1429. Uses a case-sensitive comparison.
  1430. @returns true if the string contains any of the characters from
  1431. the string that is passed in.
  1432. */
  1433. bool containsAnyOf (const String& charactersItMightContain) const throw();
  1434. /** Looks for a set of characters in the string.
  1435. Uses a case-sensitive comparison.
  1436. @returns true if the all the characters in the string are also found in the
  1437. string that is passed in.
  1438. */
  1439. bool containsOnly (const String& charactersItMightContain) const throw();
  1440. /** Returns true if this string contains any non-whitespace characters.
  1441. This will return false if the string contains only whitespace characters, or
  1442. if it's empty.
  1443. It is equivalent to calling "myString.trim().isNotEmpty()".
  1444. */
  1445. bool containsNonWhitespaceChars() const throw();
  1446. /** Returns true if the string matches this simple wildcard expression.
  1447. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1448. This isn't a full-blown regex though! The only wildcard characters supported
  1449. are "*" and "?". It's mainly intended for filename pattern matching.
  1450. */
  1451. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  1452. // Substring location methods..
  1453. /** Searches for a character inside this string.
  1454. Uses a case-sensitive comparison.
  1455. @returns the index of the first occurrence of the character in this
  1456. string, or -1 if it's not found.
  1457. */
  1458. int indexOfChar (juce_wchar characterToLookFor) const throw();
  1459. /** Searches for a character inside this string.
  1460. Uses a case-sensitive comparison.
  1461. @param startIndex the index from which the search should proceed
  1462. @param characterToLookFor the character to look for
  1463. @returns the index of the first occurrence of the character in this
  1464. string, or -1 if it's not found.
  1465. */
  1466. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  1467. /** Returns the index of the first character that matches one of the characters
  1468. passed-in to this method.
  1469. This scans the string, beginning from the startIndex supplied, and if it finds
  1470. a character that appears in the string charactersToLookFor, it returns its index.
  1471. If none of these characters are found, it returns -1.
  1472. If ignoreCase is true, the comparison will be case-insensitive.
  1473. @see indexOfChar, lastIndexOfAnyOf
  1474. */
  1475. int indexOfAnyOf (const String& charactersToLookFor,
  1476. int startIndex = 0,
  1477. bool ignoreCase = false) const throw();
  1478. /** Searches for a substring within this string.
  1479. Uses a case-sensitive comparison.
  1480. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1481. */
  1482. int indexOf (const String& text) const throw();
  1483. /** Searches for a substring within this string.
  1484. Uses a case-sensitive comparison.
  1485. @param startIndex the index from which the search should proceed
  1486. @param textToLookFor the string to search for
  1487. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1488. */
  1489. int indexOf (int startIndex,
  1490. const String& textToLookFor) const throw();
  1491. /** Searches for a substring within this string.
  1492. Uses a case-insensitive comparison.
  1493. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1494. */
  1495. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  1496. /** Searches for a substring within this string.
  1497. Uses a case-insensitive comparison.
  1498. @param startIndex the index from which the search should proceed
  1499. @param textToLookFor the string to search for
  1500. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1501. */
  1502. int indexOfIgnoreCase (int startIndex,
  1503. const String& textToLookFor) const throw();
  1504. /** Searches for a character inside this string (working backwards from the end of the string).
  1505. Uses a case-sensitive comparison.
  1506. @returns the index of the last occurrence of the character in this
  1507. string, or -1 if it's not found.
  1508. */
  1509. int lastIndexOfChar (juce_wchar character) const throw();
  1510. /** Searches for a substring inside this string (working backwards from the end of the string).
  1511. Uses a case-sensitive comparison.
  1512. @returns the index of the start of the last occurrence of the
  1513. substring within this string, or -1 if it's not found.
  1514. */
  1515. int lastIndexOf (const String& textToLookFor) const throw();
  1516. /** Searches for a substring inside this string (working backwards from the end of the string).
  1517. Uses a case-insensitive comparison.
  1518. @returns the index of the start of the last occurrence of the
  1519. substring within this string, or -1 if it's not found.
  1520. */
  1521. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  1522. /** Returns the index of the last character in this string that matches one of the
  1523. characters passed-in to this method.
  1524. This scans the string backwards, starting from its end, and if it finds
  1525. a character that appears in the string charactersToLookFor, it returns its index.
  1526. If none of these characters are found, it returns -1.
  1527. If ignoreCase is true, the comparison will be case-insensitive.
  1528. @see lastIndexOf, indexOfAnyOf
  1529. */
  1530. int lastIndexOfAnyOf (const String& charactersToLookFor,
  1531. bool ignoreCase = false) const throw();
  1532. // Substring extraction and manipulation methods..
  1533. /** Returns the character at this index in the string.
  1534. No checks are made to see if the index is within a valid range, so be careful!
  1535. */
  1536. inline const juce_wchar& operator[] (int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text [index]; }
  1537. /** Returns a character from the string such that it can also be altered.
  1538. This can be used as a way of easily changing characters in the string.
  1539. Note that the index passed-in is not checked to see whether it's in-range, so
  1540. be careful when using this.
  1541. */
  1542. juce_wchar& operator[] (int index);
  1543. /** Returns the final character of the string.
  1544. If the string is empty this will return 0.
  1545. */
  1546. juce_wchar getLastCharacter() const throw();
  1547. /** Returns a subsection of the string.
  1548. If the range specified is beyond the limits of the string, as much as
  1549. possible is returned.
  1550. @param startIndex the index of the start of the substring needed
  1551. @param endIndex all characters from startIndex up to (but not including)
  1552. this index are returned
  1553. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1554. */
  1555. const String substring (int startIndex, int endIndex) const;
  1556. /** Returns a section of the string, starting from a given position.
  1557. @param startIndex the first character to include. If this is beyond the end
  1558. of the string, an empty string is returned. If it is zero or
  1559. less, the whole string is returned.
  1560. @returns the substring from startIndex up to the end of the string
  1561. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1562. */
  1563. const String substring (int startIndex) const;
  1564. /** Returns a version of this string with a number of characters removed
  1565. from the end.
  1566. @param numberToDrop the number of characters to drop from the end of the
  1567. string. If this is greater than the length of the string,
  1568. an empty string will be returned. If zero or less, the
  1569. original string will be returned.
  1570. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1571. */
  1572. const String dropLastCharacters (int numberToDrop) const;
  1573. /** Returns a number of characters from the end of the string.
  1574. This returns the last numCharacters characters from the end of the string. If the
  1575. string is shorter than numCharacters, the whole string is returned.
  1576. @see substring, dropLastCharacters, getLastCharacter
  1577. */
  1578. const String getLastCharacters (int numCharacters) const;
  1579. /** Returns a section of the string starting from a given substring.
  1580. This will search for the first occurrence of the given substring, and
  1581. return the section of the string starting from the point where this is
  1582. found (optionally not including the substring itself).
  1583. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1584. fromFirstOccurrenceOf ("34", false) would return "56".
  1585. If the substring isn't found, the method will return an empty string.
  1586. If ignoreCase is true, the comparison will be case-insensitive.
  1587. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1588. */
  1589. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  1590. bool includeSubStringInResult,
  1591. bool ignoreCase) const;
  1592. /** Returns a section of the string starting from the last occurrence of a given substring.
  1593. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1594. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1595. return the whole of the original string.
  1596. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1597. */
  1598. const String fromLastOccurrenceOf (const String& substringToFind,
  1599. bool includeSubStringInResult,
  1600. bool ignoreCase) const;
  1601. /** Returns the start of this string, up to the first occurrence of a substring.
  1602. This will search for the first occurrence of a given substring, and then
  1603. return a copy of the string, up to the position of this substring,
  1604. optionally including or excluding the substring itself in the result.
  1605. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1606. upTo ("34", true) would return "1234".
  1607. If the substring isn't found, this will return the whole of the original string.
  1608. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1609. */
  1610. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  1611. bool includeSubStringInResult,
  1612. bool ignoreCase) const;
  1613. /** Returns the start of this string, up to the last occurrence of a substring.
  1614. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1615. If the substring isn't found, this will return an empty string.
  1616. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1617. */
  1618. const String upToLastOccurrenceOf (const String& substringToFind,
  1619. bool includeSubStringInResult,
  1620. bool ignoreCase) const;
  1621. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1622. const String trim() const;
  1623. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1624. const String trimStart() const;
  1625. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1626. const String trimEnd() const;
  1627. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1628. Characters are removed from the start of the string until it finds one that is not in the
  1629. specified set, and then it stops.
  1630. @param charactersToTrim the set of characters to remove.
  1631. @see trim, trimStart, trimCharactersAtEnd
  1632. */
  1633. const String trimCharactersAtStart (const String& charactersToTrim) const;
  1634. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1635. Characters are removed from the end of the string until it finds one that is not in the
  1636. specified set, and then it stops.
  1637. @param charactersToTrim the set of characters to remove.
  1638. @see trim, trimEnd, trimCharactersAtStart
  1639. */
  1640. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  1641. /** Returns an upper-case version of this string. */
  1642. const String toUpperCase() const;
  1643. /** Returns an lower-case version of this string. */
  1644. const String toLowerCase() const;
  1645. /** Replaces a sub-section of the string with another string.
  1646. This will return a copy of this string, with a set of characters
  1647. from startIndex to startIndex + numCharsToReplace removed, and with
  1648. a new string inserted in their place.
  1649. Note that this is a const method, and won't alter the string itself.
  1650. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1651. it will be constrained to a valid range.
  1652. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1653. characters will be taken out.
  1654. @param stringToInsert the new string to insert at startIndex after the characters have been
  1655. removed.
  1656. */
  1657. const String replaceSection (int startIndex,
  1658. int numCharactersToReplace,
  1659. const String& stringToInsert) const;
  1660. /** Replaces all occurrences of a substring with another string.
  1661. Returns a copy of this string, with any occurrences of stringToReplace
  1662. swapped for stringToInsertInstead.
  1663. Note that this is a const method, and won't alter the string itself.
  1664. */
  1665. const String replace (const String& stringToReplace,
  1666. const String& stringToInsertInstead,
  1667. bool ignoreCase = false) const;
  1668. /** Returns a string with all occurrences of a character replaced with a different one. */
  1669. const String replaceCharacter (juce_wchar characterToReplace,
  1670. juce_wchar characterToInsertInstead) const;
  1671. /** Replaces a set of characters with another set.
  1672. Returns a string in which each character from charactersToReplace has been replaced
  1673. by the character at the equivalent position in newCharacters (so the two strings
  1674. passed in must be the same length).
  1675. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1676. Note that this is a const method, and won't affect the string itself.
  1677. */
  1678. const String replaceCharacters (const String& charactersToReplace,
  1679. const String& charactersToInsertInstead) const;
  1680. /** Returns a version of this string that only retains a fixed set of characters.
  1681. This will return a copy of this string, omitting any characters which are not
  1682. found in the string passed-in.
  1683. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1684. Note that this is a const method, and won't alter the string itself.
  1685. */
  1686. const String retainCharacters (const String& charactersToRetain) const;
  1687. /** Returns a version of this string with a set of characters removed.
  1688. This will return a copy of this string, omitting any characters which are
  1689. found in the string passed-in.
  1690. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1691. Note that this is a const method, and won't alter the string itself.
  1692. */
  1693. const String removeCharacters (const String& charactersToRemove) const;
  1694. /** Returns a section from the start of the string that only contains a certain set of characters.
  1695. This returns the leftmost section of the string, up to (and not including) the
  1696. first character that doesn't appear in the string passed in.
  1697. */
  1698. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  1699. /** Returns a section from the start of the string that only contains a certain set of characters.
  1700. This returns the leftmost section of the string, up to (and not including) the
  1701. first character that occurs in the string passed in.
  1702. */
  1703. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  1704. /** Checks whether the string might be in quotation marks.
  1705. @returns true if the string begins with a quote character (either a double or single quote).
  1706. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1707. @see unquoted, quoted
  1708. */
  1709. bool isQuotedString() const;
  1710. /** Removes quotation marks from around the string, (if there are any).
  1711. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1712. at the ends of the string are not affected. If there aren't any quotes, the original string
  1713. is returned.
  1714. Note that this is a const method, and won't alter the string itself.
  1715. @see isQuotedString, quoted
  1716. */
  1717. const String unquoted() const;
  1718. /** Adds quotation marks around a string.
  1719. This will return a copy of the string with a quote at the start and end, (but won't
  1720. add the quote if there's already one there, so it's safe to call this on strings that
  1721. may already have quotes around them).
  1722. Note that this is a const method, and won't alter the string itself.
  1723. @param quoteCharacter the character to add at the start and end
  1724. @see isQuotedString, unquoted
  1725. */
  1726. const String quoted (juce_wchar quoteCharacter = '"') const;
  1727. /** Creates a string which is a version of a string repeated and joined together.
  1728. @param stringToRepeat the string to repeat
  1729. @param numberOfTimesToRepeat how many times to repeat it
  1730. */
  1731. static const String repeatedString (const String& stringToRepeat,
  1732. int numberOfTimesToRepeat);
  1733. /** Returns a copy of this string with the specified character repeatedly added to its
  1734. beginning until the total length is at least the minimum length specified.
  1735. */
  1736. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  1737. /** Returns a copy of this string with the specified character repeatedly added to its
  1738. end until the total length is at least the minimum length specified.
  1739. */
  1740. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  1741. /** Creates a string from data in an unknown format.
  1742. This looks at some binary data and tries to guess whether it's Unicode
  1743. or 8-bit characters, then returns a string that represents it correctly.
  1744. Should be able to handle Unicode endianness correctly, by looking at
  1745. the first two bytes.
  1746. */
  1747. static const String createStringFromData (const void* data, int size);
  1748. /** Creates a String from a printf-style parameter list.
  1749. I don't like this method. I don't use it myself, and I recommend avoiding it and
  1750. using the operator<< methods or pretty much anything else instead. It's only provided
  1751. here because of the popular unrest that was stirred-up when I tried to remove it...
  1752. If you're really determined to use it, at least make sure that you never, ever,
  1753. pass any String objects to it as parameters.
  1754. */
  1755. static const String formatted (const juce_wchar* formatString, ... );
  1756. // Numeric conversions..
  1757. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1758. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1759. */
  1760. explicit String (int decimalInteger);
  1761. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1762. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1763. */
  1764. explicit String (unsigned int decimalInteger);
  1765. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1766. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1767. */
  1768. explicit String (short decimalInteger);
  1769. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1770. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1771. */
  1772. explicit String (unsigned short decimalInteger);
  1773. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1774. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1775. */
  1776. explicit String (int64 largeIntegerValue);
  1777. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1778. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1779. */
  1780. explicit String (uint64 largeIntegerValue);
  1781. /** Creates a string representing this floating-point number.
  1782. @param floatValue the value to convert to a string
  1783. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1784. decimal places, and will not use exponent notation. If 0 or
  1785. less, it will use exponent notation if necessary.
  1786. @see getDoubleValue, getIntValue
  1787. */
  1788. explicit String (float floatValue,
  1789. int numberOfDecimalPlaces = 0);
  1790. /** Creates a string representing this floating-point number.
  1791. @param doubleValue the value to convert to a string
  1792. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1793. decimal places, and will not use exponent notation. If 0 or
  1794. less, it will use exponent notation if necessary.
  1795. @see getFloatValue, getIntValue
  1796. */
  1797. explicit String (double doubleValue,
  1798. int numberOfDecimalPlaces = 0);
  1799. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1800. @returns the value of the string as a 32 bit signed base-10 integer.
  1801. @see getTrailingIntValue, getHexValue32, getHexValue64
  1802. */
  1803. int getIntValue() const throw();
  1804. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1805. @returns the value of the string as a 64 bit signed base-10 integer.
  1806. */
  1807. int64 getLargeIntValue() const throw();
  1808. /** Parses a decimal number from the end of the string.
  1809. This will look for a value at the end of the string.
  1810. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1811. Negative numbers are not handled, so "xyz-5" returns 5.
  1812. @see getIntValue
  1813. */
  1814. int getTrailingIntValue() const throw();
  1815. /** Parses this string as a floating point number.
  1816. @returns the value of the string as a 32-bit floating point value.
  1817. @see getDoubleValue
  1818. */
  1819. float getFloatValue() const throw();
  1820. /** Parses this string as a floating point number.
  1821. @returns the value of the string as a 64-bit floating point value.
  1822. @see getFloatValue
  1823. */
  1824. double getDoubleValue() const throw();
  1825. /** Parses the string as a hexadecimal number.
  1826. Non-hexadecimal characters in the string are ignored.
  1827. If the string contains too many characters, then the lowest significant
  1828. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1829. @returns a 32-bit number which is the value of the string in hex.
  1830. */
  1831. int getHexValue32() const throw();
  1832. /** Parses the string as a hexadecimal number.
  1833. Non-hexadecimal characters in the string are ignored.
  1834. If the string contains too many characters, then the lowest significant
  1835. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1836. @returns a 64-bit number which is the value of the string in hex.
  1837. */
  1838. int64 getHexValue64() const throw();
  1839. /** Creates a string representing this 32-bit value in hexadecimal. */
  1840. static const String toHexString (int number);
  1841. /** Creates a string representing this 64-bit value in hexadecimal. */
  1842. static const String toHexString (int64 number);
  1843. /** Creates a string representing this 16-bit value in hexadecimal. */
  1844. static const String toHexString (short number);
  1845. /** Creates a string containing a hex dump of a block of binary data.
  1846. @param data the binary data to use as input
  1847. @param size how many bytes of data to use
  1848. @param groupSize how many bytes are grouped together before inserting a
  1849. space into the output. e.g. group size 0 has no spaces,
  1850. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1851. like "bea1 c2ff".
  1852. */
  1853. static const String toHexString (const unsigned char* data,
  1854. int size,
  1855. int groupSize = 1);
  1856. /** Returns a unicode version of this string.
  1857. Because it returns a reference to the string's internal data, the pointer
  1858. that is returned must not be stored anywhere, as it can become invalid whenever
  1859. any string methods (even some const ones!) are called.
  1860. */
  1861. inline operator const juce_wchar*() const throw() { return text; }
  1862. /** Returns a unicode version of this string.
  1863. Because it returns a reference to the string's internal data, the pointer
  1864. that is returned must not be stored anywhere, as it can become invalid whenever
  1865. any string methods (even some const ones!) are called.
  1866. */
  1867. inline operator juce_wchar*() throw() { return text; }
  1868. /** Returns a pointer to a UTF-8 version of this string.
  1869. Because it returns a reference to the string's internal data, the pointer
  1870. that is returned must not be stored anywhere, as it can be deleted whenever the
  1871. string changes.
  1872. @see getNumBytesAsUTF8, fromUTF8, copyToUTF8, toCString
  1873. */
  1874. const char* toUTF8() const;
  1875. /** Creates a String from a UTF-8 encoded buffer.
  1876. If the size is < 0, it'll keep reading until it hits a zero.
  1877. */
  1878. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  1879. /** Returns the number of bytes required to represent this string as UTF8.
  1880. The number returned does NOT include the trailing zero.
  1881. @see toUTF8, copyToUTF8
  1882. */
  1883. int getNumBytesAsUTF8() const throw();
  1884. /** Copies the string to a buffer as UTF-8 characters.
  1885. Returns the number of bytes copied to the buffer, including the terminating null
  1886. character.
  1887. @param destBuffer the place to copy it to; if this is a null pointer,
  1888. the method just returns the number of bytes required
  1889. (including the terminating null character).
  1890. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1891. string won't fit, it'll put in as many as it can while
  1892. still allowing for a terminating null char at the end, and
  1893. will return the number of bytes that were actually used.
  1894. */
  1895. int copyToUTF8 (char* destBuffer, int maxBufferSizeBytes) const throw();
  1896. /** Returns a version of this string using the default 8-bit multi-byte system encoding.
  1897. Because it returns a reference to the string's internal data, the pointer
  1898. that is returned must not be stored anywhere, as it can be deleted whenever the
  1899. string changes.
  1900. @see getNumBytesAsCString, copyToCString, toUTF8
  1901. */
  1902. const char* toCString() const;
  1903. /** Returns the number of bytes
  1904. */
  1905. int getNumBytesAsCString() const throw();
  1906. /** Copies the string to a buffer.
  1907. @param destBuffer the place to copy it to; if this is a null pointer,
  1908. the method just returns the number of bytes required
  1909. (including the terminating null character).
  1910. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1911. string won't fit, it'll put in as many as it can while
  1912. still allowing for a terminating null char at the end, and
  1913. will return the number of bytes that were actually used.
  1914. */
  1915. int copyToCString (char* destBuffer, int maxBufferSizeBytes) const throw();
  1916. /** Copies the string to a unicode buffer.
  1917. @param destBuffer the place to copy it to
  1918. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1919. not including the tailing zero, so this shouldn't be
  1920. larger than the size of your destination buffer - 1
  1921. */
  1922. void copyToUnicode (juce_wchar* destBuffer, int maxCharsToCopy) const throw();
  1923. /** Increases the string's internally allocated storage.
  1924. Although the string's contents won't be affected by this call, it will
  1925. increase the amount of memory allocated internally for the string to grow into.
  1926. If you're about to make a large number of calls to methods such
  1927. as += or <<, it's more efficient to preallocate enough extra space
  1928. beforehand, so that these methods won't have to keep resizing the string
  1929. to append the extra characters.
  1930. @param numCharsNeeded the number of characters to allocate storage for. If this
  1931. value is less than the currently allocated size, it will
  1932. have no effect.
  1933. */
  1934. void preallocateStorage (size_t numCharsNeeded);
  1935. /** Swaps the contents of this string with another one.
  1936. This is a very fast operation, as no allocation or copying needs to be done.
  1937. */
  1938. void swapWith (String& other) throw();
  1939. /** A helper class to improve performance when concatenating many large strings
  1940. together.
  1941. Because appending one string to another involves measuring the length of
  1942. both strings, repeatedly doing this for many long strings will become
  1943. an exponentially slow operation. This class uses some internal state to
  1944. avoid that, so that each append operation only needs to measure the length
  1945. of the appended string.
  1946. */
  1947. class JUCE_API Concatenator
  1948. {
  1949. public:
  1950. Concatenator (String& stringToAppendTo);
  1951. ~Concatenator();
  1952. void append (const String& s);
  1953. private:
  1954. String& result;
  1955. int nextIndex;
  1956. Concatenator (const Concatenator&);
  1957. Concatenator& operator= (const Concatenator&);
  1958. };
  1959. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1960. private:
  1961. juce_wchar* text;
  1962. // internal constructor that preallocates a certain amount of memory
  1963. String (size_t numChars, int dummyVariable);
  1964. String (const String& stringToCopy, size_t charsToAllocate);
  1965. void createInternal (const juce_wchar* text, size_t numChars);
  1966. void appendInternal (const juce_wchar* text, int numExtraChars);
  1967. };
  1968. /** Concatenates two strings. */
  1969. const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  1970. /** Concatenates two strings. */
  1971. const String JUCE_CALLTYPE operator+ (const juce_wchar* string1, const String& string2);
  1972. /** Concatenates two strings. */
  1973. const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  1974. /** Concatenates two strings. */
  1975. const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  1976. /** Concatenates two strings. */
  1977. const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  1978. /** Concatenates two strings. */
  1979. const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  1980. /** Concatenates two strings. */
  1981. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* string2);
  1982. /** Concatenates two strings. */
  1983. const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  1984. /** Concatenates two strings. */
  1985. const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  1986. /** Appends a character at the end of a string. */
  1987. String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  1988. /** Appends a character at the end of a string. */
  1989. String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  1990. /** Appends a string to the end of the first one. */
  1991. String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  1992. /** Appends a string to the end of the first one. */
  1993. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* string2);
  1994. /** Appends a string to the end of the first one. */
  1995. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  1996. /** Appends a decimal number at the end of a string. */
  1997. String& JUCE_CALLTYPE operator<< (String& string1, short number);
  1998. /** Appends a decimal number at the end of a string. */
  1999. String& JUCE_CALLTYPE operator<< (String& string1, int number);
  2000. /** Appends a decimal number at the end of a string. */
  2001. String& JUCE_CALLTYPE operator<< (String& string1, unsigned int number);
  2002. /** Appends a decimal number at the end of a string. */
  2003. String& JUCE_CALLTYPE operator<< (String& string1, long number);
  2004. /** Appends a decimal number at the end of a string. */
  2005. String& JUCE_CALLTYPE operator<< (String& string1, unsigned long number);
  2006. /** Appends a decimal number at the end of a string. */
  2007. String& JUCE_CALLTYPE operator<< (String& string1, float number);
  2008. /** Appends a decimal number at the end of a string. */
  2009. String& JUCE_CALLTYPE operator<< (String& string1, double number);
  2010. /** Case-sensitive comparison of two strings. */
  2011. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  2012. /** Case-sensitive comparison of two strings. */
  2013. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  2014. /** Case-sensitive comparison of two strings. */
  2015. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw();
  2016. /** Case-sensitive comparison of two strings. */
  2017. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  2018. /** Case-sensitive comparison of two strings. */
  2019. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  2020. /** Case-sensitive comparison of two strings. */
  2021. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw();
  2022. /** Case-sensitive comparison of two strings. */
  2023. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  2024. /** Case-sensitive comparison of two strings. */
  2025. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  2026. /** Case-sensitive comparison of two strings. */
  2027. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  2028. /** Case-sensitive comparison of two strings. */
  2029. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  2030. /** This streaming override allows you to pass a juce String directly into std output streams.
  2031. This is very handy for writing strings to std::cout, std::cerr, etc.
  2032. */
  2033. template <class charT, class traits>
  2034. std::basic_ostream <charT, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  2035. {
  2036. return stream << stringToWrite.toUTF8();
  2037. }
  2038. /** Writes a string to an OutputStream as UTF8. */
  2039. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text);
  2040. #endif // __JUCE_STRING_JUCEHEADER__
  2041. /*** End of inlined file: juce_String.h ***/
  2042. /**
  2043. Acts as an application-wide logging class.
  2044. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  2045. method and this will then be used by all calls to writeToLog.
  2046. The logger class also contains methods for writing messages to the debugger's
  2047. output stream.
  2048. @see FileLogger
  2049. */
  2050. class JUCE_API Logger
  2051. {
  2052. public:
  2053. /** Destructor. */
  2054. virtual ~Logger();
  2055. /** Sets the current logging class to use.
  2056. Note that the object passed in won't be deleted when no longer needed.
  2057. A null pointer can be passed-in to disable any logging.
  2058. If deleteOldLogger is set to true, the existing logger will be
  2059. deleted (if there is one).
  2060. */
  2061. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  2062. const bool deleteOldLogger = false);
  2063. /** Writes a string to the current logger.
  2064. This will pass the string to the logger's logMessage() method if a logger
  2065. has been set.
  2066. @see logMessage
  2067. */
  2068. static void JUCE_CALLTYPE writeToLog (const String& message);
  2069. /** Writes a message to the standard error stream.
  2070. This can be called directly, or by using the DBG() macro in
  2071. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2072. */
  2073. static void JUCE_CALLTYPE outputDebugString (const String& text);
  2074. protected:
  2075. Logger();
  2076. /** This is overloaded by subclasses to implement custom logging behaviour.
  2077. @see setCurrentLogger
  2078. */
  2079. virtual void logMessage (const String& message) = 0;
  2080. private:
  2081. static Logger* currentLogger;
  2082. };
  2083. #endif // __JUCE_LOGGER_JUCEHEADER__
  2084. /*** End of inlined file: juce_Logger.h ***/
  2085. END_JUCE_NAMESPACE
  2086. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2087. /*** End of inlined file: juce_StandardHeader.h ***/
  2088. BEGIN_JUCE_NAMESPACE
  2089. #if JUCE_MSVC
  2090. // this is set explicitly in case the app is using a different packing size.
  2091. #pragma pack (push, 8)
  2092. #pragma warning (push)
  2093. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2094. #endif
  2095. // this is where all the class header files get brought in..
  2096. /*** Start of inlined file: juce_core_includes.h ***/
  2097. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2098. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2099. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2100. /*** Start of inlined file: juce_Array.h ***/
  2101. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2102. #define __JUCE_ARRAY_JUCEHEADER__
  2103. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  2104. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2105. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2106. /*** Start of inlined file: juce_HeapBlock.h ***/
  2107. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  2108. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  2109. /**
  2110. Very simple container class to hold a pointer to some data on the heap.
  2111. When you need to allocate some heap storage for something, always try to use
  2112. this class instead of allocating the memory directly using malloc/free.
  2113. A HeapBlock<char> object can be treated in pretty much exactly the same way
  2114. as an char*, but as long as you allocate it on the stack or as a class member,
  2115. it's almost impossible for it to leak memory.
  2116. It also makes your code much more concise and readable than doing the same thing
  2117. using direct allocations,
  2118. E.g. instead of this:
  2119. @code
  2120. int* temp = (int*) juce_malloc (1024 * sizeof (int));
  2121. memcpy (temp, xyz, 1024 * sizeof (int));
  2122. juce_free (temp);
  2123. temp = (int*) juce_calloc (2048 * sizeof (int));
  2124. temp[0] = 1234;
  2125. memcpy (foobar, temp, 2048 * sizeof (int));
  2126. juce_free (temp);
  2127. @endcode
  2128. ..you could just write this:
  2129. @code
  2130. HeapBlock <int> temp (1024);
  2131. memcpy (temp, xyz, 1024 * sizeof (int));
  2132. temp.calloc (2048);
  2133. temp[0] = 1234;
  2134. memcpy (foobar, temp, 2048 * sizeof (int));
  2135. @endcode
  2136. The class is extremely lightweight, containing only a pointer to the
  2137. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  2138. as their less object-oriented counterparts. Despite adding safety, you probably
  2139. won't sacrifice any performance by using this in place of normal pointers.
  2140. @see Array, OwnedArray, MemoryBlock
  2141. */
  2142. template <class ElementType>
  2143. class HeapBlock
  2144. {
  2145. public:
  2146. /** Creates a HeapBlock which is initially just a null pointer.
  2147. After creation, you can resize the array using the malloc(), calloc(),
  2148. or realloc() methods.
  2149. */
  2150. HeapBlock() throw() : data (0)
  2151. {
  2152. }
  2153. /** Creates a HeapBlock containing a number of elements.
  2154. The contents of the block are undefined, as it will have been created by a
  2155. malloc call.
  2156. If you want an array of zero values, you can use the calloc() method instead.
  2157. */
  2158. explicit HeapBlock (const size_t numElements)
  2159. : data (static_cast <ElementType*> (::juce_malloc (numElements * sizeof (ElementType))))
  2160. {
  2161. }
  2162. /** Destructor.
  2163. This will free the data, if any has been allocated.
  2164. */
  2165. ~HeapBlock()
  2166. {
  2167. ::juce_free (data);
  2168. }
  2169. /** Returns a raw pointer to the allocated data.
  2170. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2171. freed by calling the free() method.
  2172. */
  2173. inline operator ElementType*() const throw() { return data; }
  2174. /** Returns a raw pointer to the allocated data.
  2175. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2176. freed by calling the free() method.
  2177. */
  2178. inline ElementType* getData() const throw() { return data; }
  2179. /** Returns a void pointer to the allocated data.
  2180. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2181. freed by calling the free() method.
  2182. */
  2183. inline operator void*() const throw() { return static_cast <void*> (data); }
  2184. /** Lets you use indirect calls to the first element in the array.
  2185. Obviously this will cause problems if the array hasn't been initialised, because it'll
  2186. be referencing a null pointer.
  2187. */
  2188. inline ElementType* operator->() const throw() { return data; }
  2189. /** Returns a reference to one of the data elements.
  2190. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  2191. has no idea of the size it currently has allocated.
  2192. */
  2193. template <typename IndexType>
  2194. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  2195. /** Returns a pointer to a data element at an offset from the start of the array.
  2196. This is the same as doing pointer arithmetic on the raw pointer itself.
  2197. */
  2198. template <typename IndexType>
  2199. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  2200. /** Returns a reference to the raw data pointer.
  2201. Beware that the pointer returned here will become invalid as soon as you call
  2202. any of the allocator methods on this object!
  2203. */
  2204. inline ElementType* const* operator&() const throw() { return static_cast <ElementType* const*> (&data); }
  2205. /** Returns a reference to the raw data pointer.
  2206. Beware that the pointer returned here will become invalid as soon as you call
  2207. any of the allocator methods on this object!
  2208. */
  2209. inline ElementType** operator&() throw() { return static_cast <ElementType**> (&data); }
  2210. /** Compares the pointer with another pointer.
  2211. This can be handy for checking whether this is a null pointer.
  2212. */
  2213. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  2214. /** Compares the pointer with another pointer.
  2215. This can be handy for checking whether this is a null pointer.
  2216. */
  2217. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  2218. /** Allocates a specified amount of memory.
  2219. This uses the normal malloc to allocate an amount of memory for this object.
  2220. Any previously allocated memory will be freed by this method.
  2221. The number of bytes allocated will be (newNumElements * elementSize). Normally
  2222. you wouldn't need to specify the second parameter, but it can be handy if you need
  2223. to allocate a size in bytes rather than in terms of the number of elements.
  2224. The data that is allocated will be freed when this object is deleted, or when you
  2225. call free() or any of the allocation methods.
  2226. */
  2227. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2228. {
  2229. ::juce_free (data);
  2230. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2231. }
  2232. /** Allocates a specified amount of memory and clears it.
  2233. This does the same job as the malloc() method, but clears the memory that it allocates.
  2234. */
  2235. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2236. {
  2237. ::juce_free (data);
  2238. data = static_cast <ElementType*> (::juce_calloc (newNumElements * elementSize));
  2239. }
  2240. /** Allocates a specified amount of memory and optionally clears it.
  2241. This does the same job as either malloc() or calloc(), depending on the
  2242. initialiseToZero parameter.
  2243. */
  2244. void allocate (const size_t newNumElements, const bool initialiseToZero)
  2245. {
  2246. ::juce_free (data);
  2247. if (initialiseToZero)
  2248. data = static_cast <ElementType*> (::juce_calloc (newNumElements * sizeof (ElementType)));
  2249. else
  2250. data = static_cast <ElementType*> (::juce_malloc (newNumElements * sizeof (ElementType)));
  2251. }
  2252. /** Re-allocates a specified amount of memory.
  2253. The semantics of this method are the same as malloc() and calloc(), but it
  2254. uses realloc() to keep as much of the existing data as possible.
  2255. */
  2256. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2257. {
  2258. if (data == 0)
  2259. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2260. else
  2261. data = static_cast <ElementType*> (::juce_realloc (data, newNumElements * elementSize));
  2262. }
  2263. /** Frees any currently-allocated data.
  2264. This will free the data and reset this object to be a null pointer.
  2265. */
  2266. void free()
  2267. {
  2268. ::juce_free (data);
  2269. data = 0;
  2270. }
  2271. /** Swaps this object's data with the data of another HeapBlock.
  2272. The two objects simply exchange their data pointers.
  2273. */
  2274. void swapWith (HeapBlock <ElementType>& other) throw()
  2275. {
  2276. swapVariables (data, other.data);
  2277. }
  2278. private:
  2279. ElementType* data;
  2280. HeapBlock (const HeapBlock&);
  2281. HeapBlock& operator= (const HeapBlock&);
  2282. };
  2283. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  2284. /*** End of inlined file: juce_HeapBlock.h ***/
  2285. /**
  2286. Implements some basic array storage allocation functions.
  2287. This class isn't really for public use - it's used by the other
  2288. array classes, but might come in handy for some purposes.
  2289. It inherits from a critical section class to allow the arrays to use
  2290. the "empty base class optimisation" pattern to reduce their footprint.
  2291. @see Array, OwnedArray, ReferenceCountedArray
  2292. */
  2293. template <class ElementType, class TypeOfCriticalSectionToUse>
  2294. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  2295. {
  2296. public:
  2297. /** Creates an empty array. */
  2298. ArrayAllocationBase() throw()
  2299. : numAllocated (0)
  2300. {
  2301. }
  2302. /** Destructor. */
  2303. ~ArrayAllocationBase()
  2304. {
  2305. }
  2306. /** Changes the amount of storage allocated.
  2307. This will retain any data currently held in the array, and either add or
  2308. remove extra space at the end.
  2309. @param numElements the number of elements that are needed
  2310. */
  2311. void setAllocatedSize (const int numElements)
  2312. {
  2313. if (numAllocated != numElements)
  2314. {
  2315. if (numElements > 0)
  2316. elements.realloc (numElements);
  2317. else
  2318. elements.free();
  2319. numAllocated = numElements;
  2320. }
  2321. }
  2322. /** Increases the amount of storage allocated if it is less than a given amount.
  2323. This will retain any data currently held in the array, but will add
  2324. extra space at the end to make sure there it's at least as big as the size
  2325. passed in. If it's already bigger, no action is taken.
  2326. @param minNumElements the minimum number of elements that are needed
  2327. */
  2328. void ensureAllocatedSize (const int minNumElements)
  2329. {
  2330. if (minNumElements > numAllocated)
  2331. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  2332. }
  2333. /** Minimises the amount of storage allocated so that it's no more than
  2334. the given number of elements.
  2335. */
  2336. void shrinkToNoMoreThan (const int maxNumElements)
  2337. {
  2338. if (maxNumElements < numAllocated)
  2339. setAllocatedSize (maxNumElements);
  2340. }
  2341. /** Swap the contents of two objects. */
  2342. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2343. {
  2344. elements.swapWith (other.elements);
  2345. swapVariables (numAllocated, other.numAllocated);
  2346. }
  2347. HeapBlock <ElementType> elements;
  2348. int numAllocated;
  2349. private:
  2350. ArrayAllocationBase (const ArrayAllocationBase&);
  2351. ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2352. };
  2353. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2354. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  2355. /*** Start of inlined file: juce_ElementComparator.h ***/
  2356. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2357. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2358. /**
  2359. Sorts a range of elements in an array.
  2360. The comparator object that is passed-in must define a public method with the following
  2361. signature:
  2362. @code
  2363. int compareElements (ElementType first, ElementType second);
  2364. @endcode
  2365. ..and this method must return:
  2366. - a value of < 0 if the first comes before the second
  2367. - a value of 0 if the two objects are equivalent
  2368. - a value of > 0 if the second comes before the first
  2369. To improve performance, the compareElements() method can be declared as static or const.
  2370. @param comparator an object which defines a compareElements() method
  2371. @param array the array to sort
  2372. @param firstElement the index of the first element of the range to be sorted
  2373. @param lastElement the index of the last element in the range that needs
  2374. sorting (this is inclusive)
  2375. @param retainOrderOfEquivalentItems if true, the order of items that the
  2376. comparator deems the same will be maintained - this will be
  2377. a slower algorithm than if they are allowed to be moved around.
  2378. @see sortArrayRetainingOrder
  2379. */
  2380. template <class ElementType, class ElementComparator>
  2381. static void sortArray (ElementComparator& comparator,
  2382. ElementType* const array,
  2383. int firstElement,
  2384. int lastElement,
  2385. const bool retainOrderOfEquivalentItems)
  2386. {
  2387. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2388. // avoids getting warning messages about the parameter being unused
  2389. if (lastElement > firstElement)
  2390. {
  2391. if (retainOrderOfEquivalentItems)
  2392. {
  2393. for (int i = firstElement; i < lastElement; ++i)
  2394. {
  2395. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2396. {
  2397. const ElementType temp = array [i];
  2398. array [i] = array[i + 1];
  2399. array [i + 1] = temp;
  2400. if (i > firstElement)
  2401. i -= 2;
  2402. }
  2403. }
  2404. }
  2405. else
  2406. {
  2407. int fromStack[30], toStack[30];
  2408. int stackIndex = 0;
  2409. for (;;)
  2410. {
  2411. const int size = (lastElement - firstElement) + 1;
  2412. if (size <= 8)
  2413. {
  2414. int j = lastElement;
  2415. int maxIndex;
  2416. while (j > firstElement)
  2417. {
  2418. maxIndex = firstElement;
  2419. for (int k = firstElement + 1; k <= j; ++k)
  2420. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2421. maxIndex = k;
  2422. const ElementType temp = array [maxIndex];
  2423. array [maxIndex] = array[j];
  2424. array [j] = temp;
  2425. --j;
  2426. }
  2427. }
  2428. else
  2429. {
  2430. const int mid = firstElement + (size >> 1);
  2431. ElementType temp = array [mid];
  2432. array [mid] = array [firstElement];
  2433. array [firstElement] = temp;
  2434. int i = firstElement;
  2435. int j = lastElement + 1;
  2436. for (;;)
  2437. {
  2438. while (++i <= lastElement
  2439. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2440. {}
  2441. while (--j > firstElement
  2442. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2443. {}
  2444. if (j < i)
  2445. break;
  2446. temp = array[i];
  2447. array[i] = array[j];
  2448. array[j] = temp;
  2449. }
  2450. temp = array [firstElement];
  2451. array [firstElement] = array[j];
  2452. array [j] = temp;
  2453. if (j - 1 - firstElement >= lastElement - i)
  2454. {
  2455. if (firstElement + 1 < j)
  2456. {
  2457. fromStack [stackIndex] = firstElement;
  2458. toStack [stackIndex] = j - 1;
  2459. ++stackIndex;
  2460. }
  2461. if (i < lastElement)
  2462. {
  2463. firstElement = i;
  2464. continue;
  2465. }
  2466. }
  2467. else
  2468. {
  2469. if (i < lastElement)
  2470. {
  2471. fromStack [stackIndex] = i;
  2472. toStack [stackIndex] = lastElement;
  2473. ++stackIndex;
  2474. }
  2475. if (firstElement + 1 < j)
  2476. {
  2477. lastElement = j - 1;
  2478. continue;
  2479. }
  2480. }
  2481. }
  2482. if (--stackIndex < 0)
  2483. break;
  2484. jassert (stackIndex < numElementsInArray (fromStack));
  2485. firstElement = fromStack [stackIndex];
  2486. lastElement = toStack [stackIndex];
  2487. }
  2488. }
  2489. }
  2490. }
  2491. /**
  2492. Searches a sorted array of elements, looking for the index at which a specified value
  2493. should be inserted for it to be in the correct order.
  2494. The comparator object that is passed-in must define a public method with the following
  2495. signature:
  2496. @code
  2497. int compareElements (ElementType first, ElementType second);
  2498. @endcode
  2499. ..and this method must return:
  2500. - a value of < 0 if the first comes before the second
  2501. - a value of 0 if the two objects are equivalent
  2502. - a value of > 0 if the second comes before the first
  2503. To improve performance, the compareElements() method can be declared as static or const.
  2504. @param comparator an object which defines a compareElements() method
  2505. @param array the array to search
  2506. @param newElement the value that is going to be inserted
  2507. @param firstElement the index of the first element to search
  2508. @param lastElement the index of the last element in the range (this is non-inclusive)
  2509. */
  2510. template <class ElementType, class ElementComparator>
  2511. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2512. ElementType* const array,
  2513. const ElementType newElement,
  2514. int firstElement,
  2515. int lastElement)
  2516. {
  2517. jassert (firstElement <= lastElement);
  2518. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2519. // avoids getting warning messages about the parameter being unused
  2520. while (firstElement < lastElement)
  2521. {
  2522. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2523. {
  2524. ++firstElement;
  2525. break;
  2526. }
  2527. else
  2528. {
  2529. const int halfway = (firstElement + lastElement) >> 1;
  2530. if (halfway == firstElement)
  2531. {
  2532. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2533. ++firstElement;
  2534. break;
  2535. }
  2536. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2537. {
  2538. firstElement = halfway;
  2539. }
  2540. else
  2541. {
  2542. lastElement = halfway;
  2543. }
  2544. }
  2545. }
  2546. return firstElement;
  2547. }
  2548. /**
  2549. A simple ElementComparator class that can be used to sort an array of
  2550. objects that support the '<' operator.
  2551. This will work for primitive types and objects that implement operator<().
  2552. Example: @code
  2553. Array <int> myArray;
  2554. DefaultElementComparator<int> sorter;
  2555. myArray.sort (sorter);
  2556. @endcode
  2557. @see ElementComparator
  2558. */
  2559. template <class ElementType>
  2560. class DefaultElementComparator
  2561. {
  2562. private:
  2563. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2564. public:
  2565. static int compareElements (ParameterType first, ParameterType second)
  2566. {
  2567. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  2568. }
  2569. };
  2570. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2571. /*** End of inlined file: juce_ElementComparator.h ***/
  2572. /*** Start of inlined file: juce_CriticalSection.h ***/
  2573. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2574. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2575. class JUCE_API ScopedLock;
  2576. class JUCE_API ScopedUnlock;
  2577. /**
  2578. Prevents multiple threads from accessing shared objects at the same time.
  2579. @see ScopedLock, Thread, InterProcessLock
  2580. */
  2581. class JUCE_API CriticalSection
  2582. {
  2583. public:
  2584. /**
  2585. Creates a CriticalSection object
  2586. */
  2587. CriticalSection() throw();
  2588. /** Destroys a CriticalSection object.
  2589. If the critical section is deleted whilst locked, its subsequent behaviour
  2590. is unpredictable.
  2591. */
  2592. ~CriticalSection() throw();
  2593. /** Locks this critical section.
  2594. If the lock is currently held by another thread, this will wait until it
  2595. becomes free.
  2596. If the lock is already held by the caller thread, the method returns immediately.
  2597. @see exit, ScopedLock
  2598. */
  2599. void enter() const throw();
  2600. /** Attempts to lock this critical section without blocking.
  2601. This method behaves identically to CriticalSection::enter, except that the caller thread
  2602. does not wait if the lock is currently held by another thread but returns false immediately.
  2603. @returns false if the lock is currently held by another thread, true otherwise.
  2604. @see enter
  2605. */
  2606. bool tryEnter() const throw();
  2607. /** Releases the lock.
  2608. If the caller thread hasn't got the lock, this can have unpredictable results.
  2609. If the enter() method has been called multiple times by the thread, each
  2610. call must be matched by a call to exit() before other threads will be allowed
  2611. to take over the lock.
  2612. @see enter, ScopedLock
  2613. */
  2614. void exit() const throw();
  2615. /** Provides the type of scoped lock to use with this type of critical section object. */
  2616. typedef ScopedLock ScopedLockType;
  2617. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  2618. typedef ScopedUnlock ScopedUnlockType;
  2619. juce_UseDebuggingNewOperator
  2620. private:
  2621. #if JUCE_WINDOWS
  2622. #if JUCE_64BIT
  2623. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2624. // block of memory here that's big enough to be used internally as a windows critical
  2625. // section object.
  2626. uint8 internal [44];
  2627. #else
  2628. uint8 internal [24];
  2629. #endif
  2630. #else
  2631. mutable pthread_mutex_t internal;
  2632. #endif
  2633. CriticalSection (const CriticalSection&);
  2634. CriticalSection& operator= (const CriticalSection&);
  2635. };
  2636. /**
  2637. A class that can be used in place of a real CriticalSection object.
  2638. This is currently used by some templated classes, and should get
  2639. optimised out by the compiler.
  2640. @see Array, OwnedArray, ReferenceCountedArray
  2641. */
  2642. class JUCE_API DummyCriticalSection
  2643. {
  2644. public:
  2645. inline DummyCriticalSection() throw() {}
  2646. inline ~DummyCriticalSection() throw() {}
  2647. inline void enter() const throw() {}
  2648. inline void exit() const throw() {}
  2649. /** A dummy scoped-lock type to use with a dummy critical section. */
  2650. struct ScopedLockType
  2651. {
  2652. ScopedLockType (const DummyCriticalSection&) throw() {}
  2653. };
  2654. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  2655. typedef ScopedLockType ScopedUnlockType;
  2656. private:
  2657. DummyCriticalSection (const DummyCriticalSection&);
  2658. DummyCriticalSection& operator= (const DummyCriticalSection&);
  2659. };
  2660. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2661. /*** End of inlined file: juce_CriticalSection.h ***/
  2662. /**
  2663. Holds a list of simple objects, such as ints, doubles, or pointers.
  2664. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  2665. The array can be used to hold simple, non-polymorphic objects as well as primitive types - to
  2666. do so, the class must fulfil these requirements:
  2667. - it must have a copy constructor and operator=
  2668. - it must be able to be relocated in memory by a memcpy without this causing a problem - so no
  2669. objects whose functionality relies on pointers or references to themselves can be used.
  2670. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  2671. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  2672. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  2673. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  2674. specialised class StringArray, which provides more useful functions.
  2675. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2676. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2677. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2678. */
  2679. template <typename ElementType,
  2680. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  2681. class Array
  2682. {
  2683. private:
  2684. #if defined (_MSC_VER) && _MSC_VER <= 1400
  2685. typedef const ElementType& ParameterType;
  2686. #else
  2687. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2688. #endif
  2689. public:
  2690. /** Creates an empty array. */
  2691. Array() throw()
  2692. : numUsed (0)
  2693. {
  2694. }
  2695. /** Creates a copy of another array.
  2696. @param other the array to copy
  2697. */
  2698. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  2699. {
  2700. const ScopedLockType lock (other.getLock());
  2701. numUsed = other.numUsed;
  2702. data.setAllocatedSize (other.numUsed);
  2703. for (int i = 0; i < numUsed; ++i)
  2704. new (data.elements + i) ElementType (other.data.elements[i]);
  2705. }
  2706. /** Initalises from a null-terminated C array of values.
  2707. @param values the array to copy from
  2708. */
  2709. template <typename TypeToCreateFrom>
  2710. explicit Array (const TypeToCreateFrom* values)
  2711. : numUsed (0)
  2712. {
  2713. while (*values != TypeToCreateFrom())
  2714. add (*values++);
  2715. }
  2716. /** Initalises from a C array of values.
  2717. @param values the array to copy from
  2718. @param numValues the number of values in the array
  2719. */
  2720. template <typename TypeToCreateFrom>
  2721. Array (const TypeToCreateFrom* values, int numValues)
  2722. : numUsed (numValues)
  2723. {
  2724. data.setAllocatedSize (numValues);
  2725. for (int i = 0; i < numValues; ++i)
  2726. new (data.elements + i) ElementType (values[i]);
  2727. }
  2728. /** Destructor. */
  2729. ~Array()
  2730. {
  2731. for (int i = 0; i < numUsed; ++i)
  2732. data.elements[i].~ElementType();
  2733. }
  2734. /** Copies another array.
  2735. @param other the array to copy
  2736. */
  2737. Array& operator= (const Array& other)
  2738. {
  2739. if (this != &other)
  2740. {
  2741. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  2742. swapWithArray (otherCopy);
  2743. }
  2744. return *this;
  2745. }
  2746. /** Compares this array to another one.
  2747. Two arrays are considered equal if they both contain the same set of
  2748. elements, in the same order.
  2749. @param other the other array to compare with
  2750. */
  2751. template <class OtherArrayType>
  2752. bool operator== (const OtherArrayType& other) const
  2753. {
  2754. const ScopedLockType lock (getLock());
  2755. if (numUsed != other.numUsed)
  2756. return false;
  2757. for (int i = numUsed; --i >= 0;)
  2758. if (! (data.elements [i] == other.data.elements [i]))
  2759. return false;
  2760. return true;
  2761. }
  2762. /** Compares this array to another one.
  2763. Two arrays are considered equal if they both contain the same set of
  2764. elements, in the same order.
  2765. @param other the other array to compare with
  2766. */
  2767. template <class OtherArrayType>
  2768. bool operator!= (const OtherArrayType& other) const
  2769. {
  2770. return ! operator== (other);
  2771. }
  2772. /** Removes all elements from the array.
  2773. This will remove all the elements, and free any storage that the array is
  2774. using. To clear the array without freeing the storage, use the clearQuick()
  2775. method instead.
  2776. @see clearQuick
  2777. */
  2778. void clear()
  2779. {
  2780. const ScopedLockType lock (getLock());
  2781. for (int i = 0; i < numUsed; ++i)
  2782. data.elements[i].~ElementType();
  2783. data.setAllocatedSize (0);
  2784. numUsed = 0;
  2785. }
  2786. /** Removes all elements from the array without freeing the array's allocated storage.
  2787. @see clear
  2788. */
  2789. void clearQuick()
  2790. {
  2791. const ScopedLockType lock (getLock());
  2792. for (int i = 0; i < numUsed; ++i)
  2793. data.elements[i].~ElementType();
  2794. numUsed = 0;
  2795. }
  2796. /** Returns the current number of elements in the array.
  2797. */
  2798. inline int size() const throw()
  2799. {
  2800. return numUsed;
  2801. }
  2802. /** Returns one of the elements in the array.
  2803. If the index passed in is beyond the range of valid elements, this
  2804. will return zero.
  2805. If you're certain that the index will always be a valid element, you
  2806. can call getUnchecked() instead, which is faster.
  2807. @param index the index of the element being requested (0 is the first element in the array)
  2808. @see getUnchecked, getFirst, getLast
  2809. */
  2810. inline ElementType operator[] (const int index) const
  2811. {
  2812. const ScopedLockType lock (getLock());
  2813. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  2814. : ElementType();
  2815. }
  2816. /** Returns one of the elements in the array, without checking the index passed in.
  2817. Unlike the operator[] method, this will try to return an element without
  2818. checking that the index is within the bounds of the array, so should only
  2819. be used when you're confident that it will always be a valid index.
  2820. @param index the index of the element being requested (0 is the first element in the array)
  2821. @see operator[], getFirst, getLast
  2822. */
  2823. inline const ElementType getUnchecked (const int index) const
  2824. {
  2825. const ScopedLockType lock (getLock());
  2826. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2827. return data.elements [index];
  2828. }
  2829. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2830. This is like getUnchecked, but returns a direct reference to the element, so that
  2831. you can alter it directly. Obviously this can be dangerous, so only use it when
  2832. absolutely necessary.
  2833. @param index the index of the element being requested (0 is the first element in the array)
  2834. @see operator[], getFirst, getLast
  2835. */
  2836. inline ElementType& getReference (const int index) const throw()
  2837. {
  2838. const ScopedLockType lock (getLock());
  2839. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2840. return data.elements [index];
  2841. }
  2842. /** Returns the first element in the array, or 0 if the array is empty.
  2843. @see operator[], getUnchecked, getLast
  2844. */
  2845. inline ElementType getFirst() const
  2846. {
  2847. const ScopedLockType lock (getLock());
  2848. return (numUsed > 0) ? data.elements [0]
  2849. : ElementType();
  2850. }
  2851. /** Returns the last element in the array, or 0 if the array is empty.
  2852. @see operator[], getUnchecked, getFirst
  2853. */
  2854. inline ElementType getLast() const
  2855. {
  2856. const ScopedLockType lock (getLock());
  2857. return (numUsed > 0) ? data.elements [numUsed - 1]
  2858. : ElementType();
  2859. }
  2860. /** Returns a pointer to the actual array data.
  2861. This pointer will only be valid until the next time a non-const method
  2862. is called on the array.
  2863. */
  2864. inline ElementType* getRawDataPointer() throw()
  2865. {
  2866. return data.elements;
  2867. }
  2868. /** Finds the index of the first element which matches the value passed in.
  2869. This will search the array for the given object, and return the index
  2870. of its first occurrence. If the object isn't found, the method will return -1.
  2871. @param elementToLookFor the value or object to look for
  2872. @returns the index of the object, or -1 if it's not found
  2873. */
  2874. int indexOf (ParameterType elementToLookFor) const
  2875. {
  2876. const ScopedLockType lock (getLock());
  2877. const ElementType* e = data.elements.getData();
  2878. const ElementType* const end = e + numUsed;
  2879. while (e != end)
  2880. {
  2881. if (elementToLookFor == *e)
  2882. return static_cast <int> (e - data.elements.getData());
  2883. ++e;
  2884. }
  2885. return -1;
  2886. }
  2887. /** Returns true if the array contains at least one occurrence of an object.
  2888. @param elementToLookFor the value or object to look for
  2889. @returns true if the item is found
  2890. */
  2891. bool contains (ParameterType elementToLookFor) const
  2892. {
  2893. const ScopedLockType lock (getLock());
  2894. const ElementType* e = data.elements.getData();
  2895. const ElementType* const end = e + numUsed;
  2896. while (e != end)
  2897. {
  2898. if (elementToLookFor == *e)
  2899. return true;
  2900. ++e;
  2901. }
  2902. return false;
  2903. }
  2904. /** Appends a new element at the end of the array.
  2905. @param newElement the new object to add to the array
  2906. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  2907. */
  2908. void add (ParameterType newElement)
  2909. {
  2910. const ScopedLockType lock (getLock());
  2911. data.ensureAllocatedSize (numUsed + 1);
  2912. new (data.elements + numUsed++) ElementType (newElement);
  2913. }
  2914. /** Inserts a new element into the array at a given position.
  2915. If the index is less than 0 or greater than the size of the array, the
  2916. element will be added to the end of the array.
  2917. Otherwise, it will be inserted into the array, moving all the later elements
  2918. along to make room.
  2919. @param indexToInsertAt the index at which the new element should be
  2920. inserted (pass in -1 to add it to the end)
  2921. @param newElement the new object to add to the array
  2922. @see add, addSorted, addUsingDefaultSort, set
  2923. */
  2924. void insert (int indexToInsertAt, ParameterType newElement)
  2925. {
  2926. const ScopedLockType lock (getLock());
  2927. data.ensureAllocatedSize (numUsed + 1);
  2928. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2929. {
  2930. ElementType* const insertPos = data.elements + indexToInsertAt;
  2931. const int numberToMove = numUsed - indexToInsertAt;
  2932. if (numberToMove > 0)
  2933. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2934. new (insertPos) ElementType (newElement);
  2935. ++numUsed;
  2936. }
  2937. else
  2938. {
  2939. new (data.elements + numUsed++) ElementType (newElement);
  2940. }
  2941. }
  2942. /** Inserts multiple copies of an element into the array at a given position.
  2943. If the index is less than 0 or greater than the size of the array, the
  2944. element will be added to the end of the array.
  2945. Otherwise, it will be inserted into the array, moving all the later elements
  2946. along to make room.
  2947. @param indexToInsertAt the index at which the new element should be inserted
  2948. @param newElement the new object to add to the array
  2949. @param numberOfTimesToInsertIt how many copies of the value to insert
  2950. @see insert, add, addSorted, set
  2951. */
  2952. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  2953. int numberOfTimesToInsertIt)
  2954. {
  2955. if (numberOfTimesToInsertIt > 0)
  2956. {
  2957. const ScopedLockType lock (getLock());
  2958. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2959. ElementType* insertPos;
  2960. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2961. {
  2962. insertPos = data.elements + indexToInsertAt;
  2963. const int numberToMove = numUsed - indexToInsertAt;
  2964. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2965. }
  2966. else
  2967. {
  2968. insertPos = data.elements + numUsed;
  2969. }
  2970. numUsed += numberOfTimesToInsertIt;
  2971. while (--numberOfTimesToInsertIt >= 0)
  2972. new (insertPos++) ElementType (newElement);
  2973. }
  2974. }
  2975. /** Inserts an array of values into this array at a given position.
  2976. If the index is less than 0 or greater than the size of the array, the
  2977. new elements will be added to the end of the array.
  2978. Otherwise, they will be inserted into the array, moving all the later elements
  2979. along to make room.
  2980. @param indexToInsertAt the index at which the first new element should be inserted
  2981. @param newElements the new values to add to the array
  2982. @param numberOfElements how many items are in the array
  2983. @see insert, add, addSorted, set
  2984. */
  2985. void insertArray (int indexToInsertAt,
  2986. const ElementType* newElements,
  2987. int numberOfElements)
  2988. {
  2989. if (numberOfElements > 0)
  2990. {
  2991. const ScopedLockType lock (getLock());
  2992. data.ensureAllocatedSize (numUsed + numberOfElements);
  2993. ElementType* insertPos;
  2994. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2995. {
  2996. insertPos = data.elements + indexToInsertAt;
  2997. const int numberToMove = numUsed - indexToInsertAt;
  2998. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  2999. }
  3000. else
  3001. {
  3002. insertPos = data.elements + numUsed;
  3003. }
  3004. numUsed += numberOfElements;
  3005. while (--numberOfElements >= 0)
  3006. new (insertPos++) ElementType (*newElements++);
  3007. }
  3008. }
  3009. /** Appends a new element at the end of the array as long as the array doesn't
  3010. already contain it.
  3011. If the array already contains an element that matches the one passed in, nothing
  3012. will be done.
  3013. @param newElement the new object to add to the array
  3014. */
  3015. void addIfNotAlreadyThere (ParameterType newElement)
  3016. {
  3017. const ScopedLockType lock (getLock());
  3018. if (! contains (newElement))
  3019. add (newElement);
  3020. }
  3021. /** Replaces an element with a new value.
  3022. If the index is less than zero, this method does nothing.
  3023. If the index is beyond the end of the array, the item is added to the end of the array.
  3024. @param indexToChange the index whose value you want to change
  3025. @param newValue the new value to set for this index.
  3026. @see add, insert
  3027. */
  3028. void set (const int indexToChange, ParameterType newValue)
  3029. {
  3030. jassert (indexToChange >= 0);
  3031. const ScopedLockType lock (getLock());
  3032. if (((unsigned int) indexToChange) < (unsigned int) numUsed)
  3033. {
  3034. data.elements [indexToChange] = newValue;
  3035. }
  3036. else if (indexToChange >= 0)
  3037. {
  3038. data.ensureAllocatedSize (numUsed + 1);
  3039. new (data.elements + numUsed++) ElementType (newValue);
  3040. }
  3041. }
  3042. /** Replaces an element with a new value without doing any bounds-checking.
  3043. This just sets a value directly in the array's internal storage, so you'd
  3044. better make sure it's in range!
  3045. @param indexToChange the index whose value you want to change
  3046. @param newValue the new value to set for this index.
  3047. @see set, getUnchecked
  3048. */
  3049. void setUnchecked (const int indexToChange, ParameterType newValue)
  3050. {
  3051. const ScopedLockType lock (getLock());
  3052. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3053. data.elements [indexToChange] = newValue;
  3054. }
  3055. /** Adds elements from an array to the end of this array.
  3056. @param elementsToAdd the array of elements to add
  3057. @param numElementsToAdd how many elements are in this other array
  3058. @see add
  3059. */
  3060. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  3061. {
  3062. const ScopedLockType lock (getLock());
  3063. if (numElementsToAdd > 0)
  3064. {
  3065. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  3066. while (--numElementsToAdd >= 0)
  3067. {
  3068. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  3069. ++numUsed;
  3070. }
  3071. }
  3072. }
  3073. /** This swaps the contents of this array with those of another array.
  3074. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3075. because it just swaps their internal pointers.
  3076. */
  3077. void swapWithArray (Array& otherArray) throw()
  3078. {
  3079. const ScopedLockType lock1 (getLock());
  3080. const ScopedLockType lock2 (otherArray.getLock());
  3081. data.swapWith (otherArray.data);
  3082. swapVariables (numUsed, otherArray.numUsed);
  3083. }
  3084. /** Adds elements from another array to the end of this array.
  3085. @param arrayToAddFrom the array from which to copy the elements
  3086. @param startIndex the first element of the other array to start copying from
  3087. @param numElementsToAdd how many elements to add from the other array. If this
  3088. value is negative or greater than the number of available elements,
  3089. all available elements will be copied.
  3090. @see add
  3091. */
  3092. template <class OtherArrayType>
  3093. void addArray (const OtherArrayType& arrayToAddFrom,
  3094. int startIndex = 0,
  3095. int numElementsToAdd = -1)
  3096. {
  3097. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  3098. const ScopedLockType lock2 (getLock());
  3099. if (startIndex < 0)
  3100. {
  3101. jassertfalse;
  3102. startIndex = 0;
  3103. }
  3104. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3105. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3106. while (--numElementsToAdd >= 0)
  3107. add (arrayToAddFrom.getUnchecked (startIndex++));
  3108. }
  3109. /** Inserts a new element into the array, assuming that the array is sorted.
  3110. This will use a comparator to find the position at which the new element
  3111. should go. If the array isn't sorted, the behaviour of this
  3112. method will be unpredictable.
  3113. @param comparator the comparator to use to compare the elements - see the sort()
  3114. method for details about the form this object should take
  3115. @param newElement the new element to insert to the array
  3116. @see addUsingDefaultSort, add, sort
  3117. */
  3118. template <class ElementComparator>
  3119. void addSorted (ElementComparator& comparator, ParameterType newElement)
  3120. {
  3121. const ScopedLockType lock (getLock());
  3122. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  3123. }
  3124. /** Inserts a new element into the array, assuming that the array is sorted.
  3125. This will use the DefaultElementComparator class for sorting, so your ElementType
  3126. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  3127. method will be unpredictable.
  3128. @param newElement the new element to insert to the array
  3129. @see addSorted, sort
  3130. */
  3131. void addUsingDefaultSort (ParameterType newElement)
  3132. {
  3133. DefaultElementComparator <ElementType> comparator;
  3134. addSorted (comparator, newElement);
  3135. }
  3136. /** Finds the index of an element in the array, assuming that the array is sorted.
  3137. This will use a comparator to do a binary-chop to find the index of the given
  3138. element, if it exists. If the array isn't sorted, the behaviour of this
  3139. method will be unpredictable.
  3140. @param comparator the comparator to use to compare the elements - see the sort()
  3141. method for details about the form this object should take
  3142. @param elementToLookFor the element to search for
  3143. @returns the index of the element, or -1 if it's not found
  3144. @see addSorted, sort
  3145. */
  3146. template <class ElementComparator>
  3147. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  3148. {
  3149. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3150. // avoids getting warning messages about the parameter being unused
  3151. const ScopedLockType lock (getLock());
  3152. int start = 0;
  3153. int end = numUsed;
  3154. for (;;)
  3155. {
  3156. if (start >= end)
  3157. {
  3158. return -1;
  3159. }
  3160. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  3161. {
  3162. return start;
  3163. }
  3164. else
  3165. {
  3166. const int halfway = (start + end) >> 1;
  3167. if (halfway == start)
  3168. return -1;
  3169. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  3170. start = halfway;
  3171. else
  3172. end = halfway;
  3173. }
  3174. }
  3175. }
  3176. /** Removes an element from the array.
  3177. This will remove the element at a given index, and move back
  3178. all the subsequent elements to close the gap.
  3179. If the index passed in is out-of-range, nothing will happen.
  3180. @param indexToRemove the index of the element to remove
  3181. @returns the element that has been removed
  3182. @see removeValue, removeRange
  3183. */
  3184. ElementType remove (const int indexToRemove)
  3185. {
  3186. const ScopedLockType lock (getLock());
  3187. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  3188. {
  3189. --numUsed;
  3190. ElementType* const e = data.elements + indexToRemove;
  3191. ElementType removed (*e);
  3192. e->~ElementType();
  3193. const int numberToShift = numUsed - indexToRemove;
  3194. if (numberToShift > 0)
  3195. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  3196. if ((numUsed << 1) < data.numAllocated)
  3197. minimiseStorageOverheads();
  3198. return removed;
  3199. }
  3200. else
  3201. {
  3202. return ElementType();
  3203. }
  3204. }
  3205. /** Removes an item from the array.
  3206. This will remove the first occurrence of the given element from the array.
  3207. If the item isn't found, no action is taken.
  3208. @param valueToRemove the object to try to remove
  3209. @see remove, removeRange
  3210. */
  3211. void removeValue (ParameterType valueToRemove)
  3212. {
  3213. const ScopedLockType lock (getLock());
  3214. ElementType* e = data.elements;
  3215. for (int i = numUsed; --i >= 0;)
  3216. {
  3217. if (valueToRemove == *e)
  3218. {
  3219. remove (static_cast <int> (e - data.elements.getData()));
  3220. break;
  3221. }
  3222. ++e;
  3223. }
  3224. }
  3225. /** Removes a range of elements from the array.
  3226. This will remove a set of elements, starting from the given index,
  3227. and move subsequent elements down to close the gap.
  3228. If the range extends beyond the bounds of the array, it will
  3229. be safely clipped to the size of the array.
  3230. @param startIndex the index of the first element to remove
  3231. @param numberToRemove how many elements should be removed
  3232. @see remove, removeValue
  3233. */
  3234. void removeRange (int startIndex, int numberToRemove)
  3235. {
  3236. const ScopedLockType lock (getLock());
  3237. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3238. startIndex = jlimit (0, numUsed, startIndex);
  3239. if (endIndex > startIndex)
  3240. {
  3241. ElementType* const e = data.elements + startIndex;
  3242. numberToRemove = endIndex - startIndex;
  3243. for (int i = 0; i < numberToRemove; ++i)
  3244. e[i].~ElementType();
  3245. const int numToShift = numUsed - endIndex;
  3246. if (numToShift > 0)
  3247. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  3248. numUsed -= numberToRemove;
  3249. if ((numUsed << 1) < data.numAllocated)
  3250. minimiseStorageOverheads();
  3251. }
  3252. }
  3253. /** Removes the last n elements from the array.
  3254. @param howManyToRemove how many elements to remove from the end of the array
  3255. @see remove, removeValue, removeRange
  3256. */
  3257. void removeLast (int howManyToRemove = 1)
  3258. {
  3259. const ScopedLockType lock (getLock());
  3260. if (howManyToRemove > numUsed)
  3261. howManyToRemove = numUsed;
  3262. for (int i = 0; i < howManyToRemove; ++i)
  3263. data.elements [numUsed - i].~ElementType();
  3264. numUsed -= howManyToRemove;
  3265. if ((numUsed << 1) < data.numAllocated)
  3266. minimiseStorageOverheads();
  3267. }
  3268. /** Removes any elements which are also in another array.
  3269. @param otherArray the other array in which to look for elements to remove
  3270. @see removeValuesNotIn, remove, removeValue, removeRange
  3271. */
  3272. template <class OtherArrayType>
  3273. void removeValuesIn (const OtherArrayType& otherArray)
  3274. {
  3275. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3276. const ScopedLockType lock2 (getLock());
  3277. if (this == &otherArray)
  3278. {
  3279. clear();
  3280. }
  3281. else
  3282. {
  3283. if (otherArray.size() > 0)
  3284. {
  3285. for (int i = numUsed; --i >= 0;)
  3286. if (otherArray.contains (data.elements [i]))
  3287. remove (i);
  3288. }
  3289. }
  3290. }
  3291. /** Removes any elements which are not found in another array.
  3292. Only elements which occur in this other array will be retained.
  3293. @param otherArray the array in which to look for elements NOT to remove
  3294. @see removeValuesIn, remove, removeValue, removeRange
  3295. */
  3296. template <class OtherArrayType>
  3297. void removeValuesNotIn (const OtherArrayType& otherArray)
  3298. {
  3299. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3300. const ScopedLockType lock2 (getLock());
  3301. if (this != &otherArray)
  3302. {
  3303. if (otherArray.size() <= 0)
  3304. {
  3305. clear();
  3306. }
  3307. else
  3308. {
  3309. for (int i = numUsed; --i >= 0;)
  3310. if (! otherArray.contains (data.elements [i]))
  3311. remove (i);
  3312. }
  3313. }
  3314. }
  3315. /** Swaps over two elements in the array.
  3316. This swaps over the elements found at the two indexes passed in.
  3317. If either index is out-of-range, this method will do nothing.
  3318. @param index1 index of one of the elements to swap
  3319. @param index2 index of the other element to swap
  3320. */
  3321. void swap (const int index1,
  3322. const int index2)
  3323. {
  3324. const ScopedLockType lock (getLock());
  3325. if (((unsigned int) index1) < (unsigned int) numUsed
  3326. && ((unsigned int) index2) < (unsigned int) numUsed)
  3327. {
  3328. swapVariables (data.elements [index1],
  3329. data.elements [index2]);
  3330. }
  3331. }
  3332. /** Moves one of the values to a different position.
  3333. This will move the value to a specified index, shuffling along
  3334. any intervening elements as required.
  3335. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3336. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3337. @param currentIndex the index of the value to be moved. If this isn't a
  3338. valid index, then nothing will be done
  3339. @param newIndex the index at which you'd like this value to end up. If this
  3340. is less than zero, the value will be moved to the end
  3341. of the array
  3342. */
  3343. void move (const int currentIndex, int newIndex) throw()
  3344. {
  3345. if (currentIndex != newIndex)
  3346. {
  3347. const ScopedLockType lock (getLock());
  3348. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3349. {
  3350. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3351. newIndex = numUsed - 1;
  3352. char tempCopy [sizeof (ElementType)];
  3353. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  3354. if (newIndex > currentIndex)
  3355. {
  3356. memmove (data.elements + currentIndex,
  3357. data.elements + currentIndex + 1,
  3358. (newIndex - currentIndex) * sizeof (ElementType));
  3359. }
  3360. else
  3361. {
  3362. memmove (data.elements + newIndex + 1,
  3363. data.elements + newIndex,
  3364. (currentIndex - newIndex) * sizeof (ElementType));
  3365. }
  3366. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  3367. }
  3368. }
  3369. }
  3370. /** Reduces the amount of storage being used by the array.
  3371. Arrays typically allocate slightly more storage than they need, and after
  3372. removing elements, they may have quite a lot of unused space allocated.
  3373. This method will reduce the amount of allocated storage to a minimum.
  3374. */
  3375. void minimiseStorageOverheads()
  3376. {
  3377. const ScopedLockType lock (getLock());
  3378. data.shrinkToNoMoreThan (numUsed);
  3379. }
  3380. /** Increases the array's internal storage to hold a minimum number of elements.
  3381. Calling this before adding a large known number of elements means that
  3382. the array won't have to keep dynamically resizing itself as the elements
  3383. are added, and it'll therefore be more efficient.
  3384. */
  3385. void ensureStorageAllocated (const int minNumElements)
  3386. {
  3387. const ScopedLockType lock (getLock());
  3388. data.ensureAllocatedSize (minNumElements);
  3389. }
  3390. /** Sorts the elements in the array.
  3391. This will use a comparator object to sort the elements into order. The object
  3392. passed must have a method of the form:
  3393. @code
  3394. int compareElements (ElementType first, ElementType second);
  3395. @endcode
  3396. ..and this method must return:
  3397. - a value of < 0 if the first comes before the second
  3398. - a value of 0 if the two objects are equivalent
  3399. - a value of > 0 if the second comes before the first
  3400. To improve performance, the compareElements() method can be declared as static or const.
  3401. @param comparator the comparator to use for comparing elements.
  3402. @param retainOrderOfEquivalentItems if this is true, then items
  3403. which the comparator says are equivalent will be
  3404. kept in the order in which they currently appear
  3405. in the array. This is slower to perform, but may
  3406. be important in some cases. If it's false, a faster
  3407. algorithm is used, but equivalent elements may be
  3408. rearranged.
  3409. @see addSorted, indexOfSorted, sortArray
  3410. */
  3411. template <class ElementComparator>
  3412. void sort (ElementComparator& comparator,
  3413. const bool retainOrderOfEquivalentItems = false) const
  3414. {
  3415. const ScopedLockType lock (getLock());
  3416. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3417. // avoids getting warning messages about the parameter being unused
  3418. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  3419. }
  3420. /** Returns the CriticalSection that locks this array.
  3421. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  3422. an object of ScopedLockType as an RAII lock for it.
  3423. */
  3424. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  3425. /** Returns the type of scoped lock to use for locking this array */
  3426. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  3427. juce_UseDebuggingNewOperator
  3428. private:
  3429. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  3430. int numUsed;
  3431. };
  3432. #endif // __JUCE_ARRAY_JUCEHEADER__
  3433. /*** End of inlined file: juce_Array.h ***/
  3434. #endif
  3435. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3436. #endif
  3437. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3438. /*** Start of inlined file: juce_BigInteger.h ***/
  3439. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3440. #define __JUCE_BIGINTEGER_JUCEHEADER__
  3441. class MemoryBlock;
  3442. /**
  3443. An arbitrarily large integer class.
  3444. A BigInteger can be used in a similar way to a normal integer, but has no size
  3445. limit (except for memory and performance constraints).
  3446. Negative values are possible, but the value isn't stored as 2s-complement, so
  3447. be careful if you use negative values and look at the values of individual bits.
  3448. */
  3449. class JUCE_API BigInteger
  3450. {
  3451. public:
  3452. /** Creates an empty BigInteger */
  3453. BigInteger();
  3454. /** Creates a BigInteger containing an integer value in its low bits.
  3455. The low 32 bits of the number are initialised with this value.
  3456. */
  3457. BigInteger (unsigned int value);
  3458. /** Creates a BigInteger containing an integer value in its low bits.
  3459. The low 32 bits of the number are initialised with the absolute value
  3460. passed in, and its sign is set to reflect the sign of the number.
  3461. */
  3462. BigInteger (int value);
  3463. /** Creates a BigInteger containing an integer value in its low bits.
  3464. The low 64 bits of the number are initialised with the absolute value
  3465. passed in, and its sign is set to reflect the sign of the number.
  3466. */
  3467. BigInteger (int64 value);
  3468. /** Creates a copy of another BigInteger. */
  3469. BigInteger (const BigInteger& other);
  3470. /** Destructor. */
  3471. ~BigInteger();
  3472. /** Copies another BigInteger onto this one. */
  3473. BigInteger& operator= (const BigInteger& other);
  3474. /** Swaps the internal contents of this with another object. */
  3475. void swapWith (BigInteger& other) throw();
  3476. /** Returns the value of a specified bit in the number.
  3477. If the index is out-of-range, the result will be false.
  3478. */
  3479. bool operator[] (int bit) const throw();
  3480. /** Returns true if no bits are set. */
  3481. bool isZero() const throw();
  3482. /** Returns true if the value is 1. */
  3483. bool isOne() const throw();
  3484. /** Attempts to get the lowest bits of the value as an integer.
  3485. If the value is bigger than the integer limits, this will return only the lower bits.
  3486. */
  3487. int toInteger() const throw();
  3488. /** Resets the value to 0. */
  3489. void clear();
  3490. /** Clears a particular bit in the number. */
  3491. void clearBit (int bitNumber) throw();
  3492. /** Sets a specified bit to 1. */
  3493. void setBit (int bitNumber);
  3494. /** Sets or clears a specified bit. */
  3495. void setBit (int bitNumber, bool shouldBeSet);
  3496. /** Sets a range of bits to be either on or off.
  3497. @param startBit the first bit to change
  3498. @param numBits the number of bits to change
  3499. @param shouldBeSet whether to turn these bits on or off
  3500. */
  3501. void setRange (int startBit, int numBits, bool shouldBeSet);
  3502. /** Inserts a bit an a given position, shifting up any bits above it. */
  3503. void insertBit (int bitNumber, bool shouldBeSet);
  3504. /** Returns a range of bits as a new BigInteger.
  3505. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3506. @see getBitRangeAsInt
  3507. */
  3508. const BigInteger getBitRange (int startBit, int numBits) const;
  3509. /** Returns a range of bits as an integer value.
  3510. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3511. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3512. getBitRange().
  3513. */
  3514. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3515. /** Sets a range of bits to an integer value.
  3516. Copies the given integer onto a range of bits, starting at startBit,
  3517. and using up to numBits of the available bits.
  3518. */
  3519. void setBitRangeAsInt (int startBit, int numBits, unsigned int valueToSet);
  3520. /** Shifts a section of bits left or right.
  3521. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3522. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3523. */
  3524. void shiftBits (int howManyBitsLeft, int startBit);
  3525. /** Returns the total number of set bits in the value. */
  3526. int countNumberOfSetBits() const throw();
  3527. /** Looks for the index of the next set bit after a given starting point.
  3528. This searches from startIndex (inclusive) upwards for the first set bit,
  3529. and returns its index. If no set bits are found, it returns -1.
  3530. */
  3531. int findNextSetBit (int startIndex = 0) const throw();
  3532. /** Looks for the index of the next clear bit after a given starting point.
  3533. This searches from startIndex (inclusive) upwards for the first clear bit,
  3534. and returns its index.
  3535. */
  3536. int findNextClearBit (int startIndex = 0) const throw();
  3537. /** Returns the index of the highest set bit in the number.
  3538. If the value is zero, this will return -1.
  3539. */
  3540. int getHighestBit() const throw();
  3541. // All the standard arithmetic ops...
  3542. BigInteger& operator+= (const BigInteger& other);
  3543. BigInteger& operator-= (const BigInteger& other);
  3544. BigInteger& operator*= (const BigInteger& other);
  3545. BigInteger& operator/= (const BigInteger& other);
  3546. BigInteger& operator|= (const BigInteger& other);
  3547. BigInteger& operator&= (const BigInteger& other);
  3548. BigInteger& operator^= (const BigInteger& other);
  3549. BigInteger& operator%= (const BigInteger& other);
  3550. BigInteger& operator<<= (int numBitsToShift);
  3551. BigInteger& operator>>= (int numBitsToShift);
  3552. BigInteger& operator++();
  3553. BigInteger& operator--();
  3554. const BigInteger operator++ (int);
  3555. const BigInteger operator-- (int);
  3556. const BigInteger operator-() const;
  3557. const BigInteger operator+ (const BigInteger& other) const;
  3558. const BigInteger operator- (const BigInteger& other) const;
  3559. const BigInteger operator* (const BigInteger& other) const;
  3560. const BigInteger operator/ (const BigInteger& other) const;
  3561. const BigInteger operator| (const BigInteger& other) const;
  3562. const BigInteger operator& (const BigInteger& other) const;
  3563. const BigInteger operator^ (const BigInteger& other) const;
  3564. const BigInteger operator% (const BigInteger& other) const;
  3565. const BigInteger operator<< (int numBitsToShift) const;
  3566. const BigInteger operator>> (int numBitsToShift) const;
  3567. bool operator== (const BigInteger& other) const throw();
  3568. bool operator!= (const BigInteger& other) const throw();
  3569. bool operator< (const BigInteger& other) const throw();
  3570. bool operator<= (const BigInteger& other) const throw();
  3571. bool operator> (const BigInteger& other) const throw();
  3572. bool operator>= (const BigInteger& other) const throw();
  3573. /** Does a signed comparison of two BigIntegers.
  3574. Return values are:
  3575. - 0 if the numbers are the same
  3576. - < 0 if this number is smaller than the other
  3577. - > 0 if this number is bigger than the other
  3578. */
  3579. int compare (const BigInteger& other) const throw();
  3580. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  3581. Return values are:
  3582. - 0 if the numbers are the same
  3583. - < 0 if this number is smaller than the other
  3584. - > 0 if this number is bigger than the other
  3585. */
  3586. int compareAbsolute (const BigInteger& other) const throw();
  3587. /** Divides this value by another one and returns the remainder.
  3588. This number is divided by other, leaving the quotient in this number,
  3589. with the remainder being copied to the other BigInteger passed in.
  3590. */
  3591. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  3592. /** Returns the largest value that will divide both this value and the one passed-in.
  3593. */
  3594. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  3595. /** Performs a combined exponent and modulo operation.
  3596. This BigInteger's value becomes (this ^ exponent) % modulus.
  3597. */
  3598. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  3599. /** Performs an inverse modulo on the value.
  3600. i.e. the result is (this ^ -1) mod (modulus).
  3601. */
  3602. void inverseModulo (const BigInteger& modulus);
  3603. /** Returns true if the value is less than zero.
  3604. @see setNegative, negate
  3605. */
  3606. bool isNegative() const throw();
  3607. /** Changes the sign of the number to be positive or negative.
  3608. @see isNegative, negate
  3609. */
  3610. void setNegative (const bool shouldBeNegative) throw();
  3611. /** Inverts the sign of the number.
  3612. @see isNegative, setNegative
  3613. */
  3614. void negate() throw();
  3615. /** Converts the number to a string.
  3616. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3617. If minimumNumCharacters is greater than 0, the returned string will be
  3618. padded with leading zeros to reach at least that length.
  3619. */
  3620. const String toString (int base, int minimumNumCharacters = 1) const;
  3621. /** Reads the numeric value from a string.
  3622. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3623. Any invalid characters will be ignored.
  3624. */
  3625. void parseString (const String& text, int base);
  3626. /** Turns the number into a block of binary data.
  3627. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3628. of the number, and so on.
  3629. @see loadFromMemoryBlock
  3630. */
  3631. const MemoryBlock toMemoryBlock() const;
  3632. /** Converts a block of raw data into a number.
  3633. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3634. of the number, and so on.
  3635. @see toMemoryBlock
  3636. */
  3637. void loadFromMemoryBlock (const MemoryBlock& data);
  3638. juce_UseDebuggingNewOperator
  3639. private:
  3640. HeapBlock <unsigned int> values;
  3641. int numValues, highestBit;
  3642. bool negative;
  3643. void ensureSize (int numVals);
  3644. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  3645. };
  3646. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  3647. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  3648. /** For backwards compatibility, BitArray is defined to be an alias for BigInteger.
  3649. */
  3650. typedef BigInteger BitArray;
  3651. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  3652. /*** End of inlined file: juce_BigInteger.h ***/
  3653. #endif
  3654. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3655. /*** Start of inlined file: juce_DynamicObject.h ***/
  3656. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3657. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3658. /*** Start of inlined file: juce_NamedValueSet.h ***/
  3659. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  3660. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  3661. /*** Start of inlined file: juce_Variant.h ***/
  3662. #ifndef __JUCE_VARIANT_JUCEHEADER__
  3663. #define __JUCE_VARIANT_JUCEHEADER__
  3664. /*** Start of inlined file: juce_Identifier.h ***/
  3665. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  3666. #define __JUCE_IDENTIFIER_JUCEHEADER__
  3667. /*** Start of inlined file: juce_StringPool.h ***/
  3668. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  3669. #define __JUCE_STRINGPOOL_JUCEHEADER__
  3670. /**
  3671. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  3672. comparison speed when dealing with many duplicate strings.
  3673. When you add a string to a pool using getPooledString, it'll return a character
  3674. array containing the same string. This array is owned by the pool, and the same array
  3675. is returned every time a matching string is asked for. This means that it's trivial to
  3676. compare two pooled strings for equality, as you can simply compare their pointers. It
  3677. also cuts down on storage if you're using many copies of the same string.
  3678. */
  3679. class JUCE_API StringPool
  3680. {
  3681. public:
  3682. /** Creates an empty pool. */
  3683. StringPool() throw();
  3684. /** Destructor */
  3685. ~StringPool();
  3686. /** Returns a pointer to a copy of the string that is passed in.
  3687. The pool will always return the same pointer when asked for a string that matches it.
  3688. The pool will own all the pointers that it returns, deleting them when the pool itself
  3689. is deleted.
  3690. */
  3691. const juce_wchar* getPooledString (const String& original);
  3692. /** Returns a pointer to a copy of the string that is passed in.
  3693. The pool will always return the same pointer when asked for a string that matches it.
  3694. The pool will own all the pointers that it returns, deleting them when the pool itself
  3695. is deleted.
  3696. */
  3697. const juce_wchar* getPooledString (const char* original);
  3698. /** Returns a pointer to a copy of the string that is passed in.
  3699. The pool will always return the same pointer when asked for a string that matches it.
  3700. The pool will own all the pointers that it returns, deleting them when the pool itself
  3701. is deleted.
  3702. */
  3703. const juce_wchar* getPooledString (const juce_wchar* original);
  3704. /** Returns the number of strings in the pool. */
  3705. int size() const throw();
  3706. /** Returns one of the strings in the pool, by index. */
  3707. const juce_wchar* operator[] (int index) const throw();
  3708. private:
  3709. Array <String> strings;
  3710. };
  3711. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  3712. /*** End of inlined file: juce_StringPool.h ***/
  3713. /**
  3714. Represents a string identifier, designed for accessing properties by name.
  3715. Identifier objects are very light and fast to copy, but slower to initialise
  3716. from a string, so it's much faster to keep a static identifier object to refer
  3717. to frequently-used names, rather than constructing them each time you need it.
  3718. @see NamedPropertySet, ValueTree
  3719. */
  3720. class JUCE_API Identifier
  3721. {
  3722. public:
  3723. /** Creates a null identifier. */
  3724. Identifier() throw();
  3725. /** Creates an identifier with a specified name.
  3726. Because this name may need to be used in contexts such as script variables or XML
  3727. tags, it must only contain ascii letters and digits, or the underscore character.
  3728. */
  3729. Identifier (const char* name);
  3730. /** Creates an identifier with a specified name.
  3731. Because this name may need to be used in contexts such as script variables or XML
  3732. tags, it must only contain ascii letters and digits, or the underscore character.
  3733. */
  3734. Identifier (const String& name);
  3735. /** Creates a copy of another identifier. */
  3736. Identifier (const Identifier& other) throw();
  3737. /** Creates a copy of another identifier. */
  3738. Identifier& operator= (const Identifier& other) throw();
  3739. /** Destructor */
  3740. ~Identifier();
  3741. /** Compares two identifiers. This is a very fast operation. */
  3742. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  3743. /** Compares two identifiers. This is a very fast operation. */
  3744. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  3745. /** Returns this identifier as a string. */
  3746. const String toString() const { return name; }
  3747. /** Returns this identifier's raw string pointer. */
  3748. operator const juce_wchar*() const throw() { return name; }
  3749. private:
  3750. const juce_wchar* name;
  3751. static StringPool& getPool();
  3752. };
  3753. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  3754. /*** End of inlined file: juce_Identifier.h ***/
  3755. /*** Start of inlined file: juce_OutputStream.h ***/
  3756. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3757. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3758. /*** Start of inlined file: juce_InputStream.h ***/
  3759. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  3760. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  3761. /*** Start of inlined file: juce_MemoryBlock.h ***/
  3762. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3763. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  3764. /**
  3765. A class to hold a resizable block of raw data.
  3766. */
  3767. class JUCE_API MemoryBlock
  3768. {
  3769. public:
  3770. /** Create an uninitialised block with 0 size. */
  3771. MemoryBlock() throw();
  3772. /** Creates a memory block with a given initial size.
  3773. @param initialSize the size of block to create
  3774. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  3775. */
  3776. MemoryBlock (const size_t initialSize,
  3777. const bool initialiseToZero = false) throw();
  3778. /** Creates a copy of another memory block. */
  3779. MemoryBlock (const MemoryBlock& other) throw();
  3780. /** Creates a memory block using a copy of a block of data.
  3781. @param dataToInitialiseFrom some data to copy into this block
  3782. @param sizeInBytes how much space to use
  3783. */
  3784. MemoryBlock (const void* const dataToInitialiseFrom,
  3785. const size_t sizeInBytes) throw();
  3786. /** Destructor. */
  3787. ~MemoryBlock() throw();
  3788. /** Copies another memory block onto this one.
  3789. This block will be resized and copied to exactly match the other one.
  3790. */
  3791. MemoryBlock& operator= (const MemoryBlock& other) throw();
  3792. /** Compares two memory blocks.
  3793. @returns true only if the two blocks are the same size and have identical contents.
  3794. */
  3795. bool operator== (const MemoryBlock& other) const throw();
  3796. /** Compares two memory blocks.
  3797. @returns true if the two blocks are different sizes or have different contents.
  3798. */
  3799. bool operator!= (const MemoryBlock& other) const throw();
  3800. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  3801. */
  3802. bool matches (const void* data, size_t dataSize) const throw();
  3803. /** Returns a void pointer to the data.
  3804. Note that the pointer returned will probably become invalid when the
  3805. block is resized.
  3806. */
  3807. void* getData() const throw() { return data; }
  3808. /** Returns a byte from the memory block.
  3809. This returns a reference, so you can also use it to set a byte.
  3810. */
  3811. template <typename Type>
  3812. char& operator[] (const Type offset) const throw() { return data [offset]; }
  3813. /** Returns the block's current allocated size, in bytes. */
  3814. size_t getSize() const throw() { return size; }
  3815. /** Resizes the memory block.
  3816. This will try to keep as much of the block's current content as it can,
  3817. and can optionally be made to clear any new space that gets allocated at
  3818. the end of the block.
  3819. @param newSize the new desired size for the block
  3820. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3821. whether to clear the new section or just leave it
  3822. uninitialised
  3823. @see ensureSize
  3824. */
  3825. void setSize (const size_t newSize,
  3826. const bool initialiseNewSpaceToZero = false) throw();
  3827. /** Increases the block's size only if it's smaller than a given size.
  3828. @param minimumSize if the block is already bigger than this size, no action
  3829. will be taken; otherwise it will be increased to this size
  3830. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3831. whether to clear the new section or just leave it
  3832. uninitialised
  3833. @see setSize
  3834. */
  3835. void ensureSize (const size_t minimumSize,
  3836. const bool initialiseNewSpaceToZero = false) throw();
  3837. /** Fills the entire memory block with a repeated byte value.
  3838. This is handy for clearing a block of memory to zero.
  3839. */
  3840. void fillWith (const uint8 valueToUse) throw();
  3841. /** Adds another block of data to the end of this one.
  3842. This block's size will be increased accordingly.
  3843. */
  3844. void append (const void* const data,
  3845. const size_t numBytes) throw();
  3846. /** Exchanges the contents of this and another memory block.
  3847. No actual copying is required for this, so it's very fast.
  3848. */
  3849. void swapWith (MemoryBlock& other) throw();
  3850. /** Copies data into this MemoryBlock from a memory address.
  3851. @param srcData the memory location of the data to copy into this block
  3852. @param destinationOffset the offset in this block at which the data being copied should begin
  3853. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  3854. it will be clipped so not to do anything nasty)
  3855. */
  3856. void copyFrom (const void* srcData,
  3857. int destinationOffset,
  3858. size_t numBytes) throw();
  3859. /** Copies data from this MemoryBlock to a memory address.
  3860. @param destData the memory location to write to
  3861. @param sourceOffset the offset within this block from which the copied data will be read
  3862. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  3863. zeros will be used for that portion of the data)
  3864. */
  3865. void copyTo (void* destData,
  3866. int sourceOffset,
  3867. size_t numBytes) const throw();
  3868. /** Chops out a section of the block.
  3869. This will remove a section of the memory block and close the gap around it,
  3870. shifting any subsequent data downwards and reducing the size of the block.
  3871. If the range specified goes beyond the size of the block, it will be clipped.
  3872. */
  3873. void removeSection (size_t startByte, size_t numBytesToRemove) throw();
  3874. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  3875. characters in the system's default encoding. */
  3876. const String toString() const throw();
  3877. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  3878. The block will be resized to the number of valid bytes read from the string.
  3879. Non-hex characters in the string will be ignored.
  3880. @see String::toHexString()
  3881. */
  3882. void loadFromHexString (const String& sourceHexString) throw();
  3883. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  3884. void setBitRange (size_t bitRangeStart,
  3885. size_t numBits,
  3886. int binaryNumberToApply) throw();
  3887. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  3888. int getBitRange (size_t bitRangeStart,
  3889. size_t numBitsToRead) const throw();
  3890. /** Returns a string of characters that represent the binary contents of this block.
  3891. Uses a 64-bit encoding system to allow binary data to be turned into a string
  3892. of simple non-extended characters, e.g. for storage in XML.
  3893. @see fromBase64Encoding
  3894. */
  3895. const String toBase64Encoding() const throw();
  3896. /** Takes a string of encoded characters and turns it into binary data.
  3897. The string passed in must have been created by to64BitEncoding(), and this
  3898. block will be resized to recreate the original data block.
  3899. @see toBase64Encoding
  3900. */
  3901. bool fromBase64Encoding (const String& encodedString) throw();
  3902. juce_UseDebuggingNewOperator
  3903. private:
  3904. HeapBlock <char> data;
  3905. size_t size;
  3906. static const char* const encodingTable;
  3907. };
  3908. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  3909. /*** End of inlined file: juce_MemoryBlock.h ***/
  3910. /** The base class for streams that read data.
  3911. Input and output streams are used throughout the library - subclasses can override
  3912. some or all of the virtual functions to implement their behaviour.
  3913. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  3914. */
  3915. class JUCE_API InputStream
  3916. {
  3917. public:
  3918. /** Destructor. */
  3919. virtual ~InputStream() {}
  3920. /** Returns the total number of bytes available for reading in this stream.
  3921. Note that this is the number of bytes available from the start of the
  3922. stream, not from the current position.
  3923. If the size of the stream isn't actually known, this may return -1.
  3924. */
  3925. virtual int64 getTotalLength() = 0;
  3926. /** Returns true if the stream has no more data to read. */
  3927. virtual bool isExhausted() = 0;
  3928. /** Reads a set of bytes from the stream into a memory buffer.
  3929. This is the only read method that subclasses actually need to implement, as the
  3930. InputStream base class implements the other read methods in terms of this one (although
  3931. it's often more efficient for subclasses to implement them directly).
  3932. @param destBuffer the destination buffer for the data
  3933. @param maxBytesToRead the maximum number of bytes to read - make sure the
  3934. memory block passed in is big enough to contain this
  3935. many bytes.
  3936. @returns the actual number of bytes that were read, which may be less than
  3937. maxBytesToRead if the stream is exhausted before it gets that far
  3938. */
  3939. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  3940. /** Reads a byte from the stream.
  3941. If the stream is exhausted, this will return zero.
  3942. @see OutputStream::writeByte
  3943. */
  3944. virtual char readByte();
  3945. /** Reads a boolean from the stream.
  3946. The bool is encoded as a single byte - 1 for true, 0 for false.
  3947. If the stream is exhausted, this will return false.
  3948. @see OutputStream::writeBool
  3949. */
  3950. virtual bool readBool();
  3951. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3952. If the next two bytes read are byte1 and byte2, this returns
  3953. (byte1 | (byte2 << 8)).
  3954. If the stream is exhausted partway through reading the bytes, this will return zero.
  3955. @see OutputStream::writeShort, readShortBigEndian
  3956. */
  3957. virtual short readShort();
  3958. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3959. If the next two bytes read are byte1 and byte2, this returns
  3960. (byte2 | (byte1 << 8)).
  3961. If the stream is exhausted partway through reading the bytes, this will return zero.
  3962. @see OutputStream::writeShortBigEndian, readShort
  3963. */
  3964. virtual short readShortBigEndian();
  3965. /** Reads four bytes from the stream as a little-endian 32-bit value.
  3966. If the next four bytes are byte1 to byte4, this returns
  3967. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  3968. If the stream is exhausted partway through reading the bytes, this will return zero.
  3969. @see OutputStream::writeInt, readIntBigEndian
  3970. */
  3971. virtual int readInt();
  3972. /** Reads four bytes from the stream as a big-endian 32-bit value.
  3973. If the next four bytes are byte1 to byte4, this returns
  3974. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  3975. If the stream is exhausted partway through reading the bytes, this will return zero.
  3976. @see OutputStream::writeIntBigEndian, readInt
  3977. */
  3978. virtual int readIntBigEndian();
  3979. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  3980. If the next eight bytes are byte1 to byte8, this returns
  3981. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  3982. If the stream is exhausted partway through reading the bytes, this will return zero.
  3983. @see OutputStream::writeInt64, readInt64BigEndian
  3984. */
  3985. virtual int64 readInt64();
  3986. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  3987. If the next eight bytes are byte1 to byte8, this returns
  3988. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  3989. If the stream is exhausted partway through reading the bytes, this will return zero.
  3990. @see OutputStream::writeInt64BigEndian, readInt64
  3991. */
  3992. virtual int64 readInt64BigEndian();
  3993. /** Reads four bytes as a 32-bit floating point value.
  3994. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  3995. If the stream is exhausted partway through reading the bytes, this will return zero.
  3996. @see OutputStream::writeFloat, readDouble
  3997. */
  3998. virtual float readFloat();
  3999. /** Reads four bytes as a 32-bit floating point value.
  4000. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  4001. If the stream is exhausted partway through reading the bytes, this will return zero.
  4002. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  4003. */
  4004. virtual float readFloatBigEndian();
  4005. /** Reads eight bytes as a 64-bit floating point value.
  4006. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  4007. If the stream is exhausted partway through reading the bytes, this will return zero.
  4008. @see OutputStream::writeDouble, readFloat
  4009. */
  4010. virtual double readDouble();
  4011. /** Reads eight bytes as a 64-bit floating point value.
  4012. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  4013. If the stream is exhausted partway through reading the bytes, this will return zero.
  4014. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  4015. */
  4016. virtual double readDoubleBigEndian();
  4017. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  4018. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  4019. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4020. @see OutputStream::writeCompressedInt()
  4021. */
  4022. virtual int readCompressedInt();
  4023. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  4024. This will read up to the next "\n" or "\r\n" or end-of-stream.
  4025. After this call, the stream's position will be left pointing to the next character
  4026. following the line-feed, but the linefeeds aren't included in the string that
  4027. is returned.
  4028. */
  4029. virtual const String readNextLine();
  4030. /** Reads a zero-terminated UTF8 string from the stream.
  4031. This will read characters from the stream until it hits a zero character or
  4032. end-of-stream.
  4033. @see OutputStream::writeString, readEntireStreamAsString
  4034. */
  4035. virtual const String readString();
  4036. /** Tries to read the whole stream and turn it into a string.
  4037. This will read from the stream's current position until the end-of-stream, and
  4038. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  4039. */
  4040. virtual const String readEntireStreamAsString();
  4041. /** Reads from the stream and appends the data to a MemoryBlock.
  4042. @param destBlock the block to append the data onto
  4043. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  4044. of bytes that will be read - if it's negative, data
  4045. will be read until the stream is exhausted.
  4046. @returns the number of bytes that were added to the memory block
  4047. */
  4048. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  4049. int maxNumBytesToRead = -1);
  4050. /** Returns the offset of the next byte that will be read from the stream.
  4051. @see setPosition
  4052. */
  4053. virtual int64 getPosition() = 0;
  4054. /** Tries to move the current read position of the stream.
  4055. The position is an absolute number of bytes from the stream's start.
  4056. Some streams might not be able to do this, in which case they should do
  4057. nothing and return false. Others might be able to manage it by resetting
  4058. themselves and skipping to the correct position, although this is
  4059. obviously a bit slow.
  4060. @returns true if the stream manages to reposition itself correctly
  4061. @see getPosition
  4062. */
  4063. virtual bool setPosition (int64 newPosition) = 0;
  4064. /** Reads and discards a number of bytes from the stream.
  4065. Some input streams might implement this efficiently, but the base
  4066. class will just keep reading data until the requisite number of bytes
  4067. have been done.
  4068. */
  4069. virtual void skipNextBytes (int64 numBytesToSkip);
  4070. juce_UseDebuggingNewOperator
  4071. protected:
  4072. InputStream() throw() {}
  4073. };
  4074. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  4075. /*** End of inlined file: juce_InputStream.h ***/
  4076. class File;
  4077. /**
  4078. The base class for streams that write data to some kind of destination.
  4079. Input and output streams are used throughout the library - subclasses can override
  4080. some or all of the virtual functions to implement their behaviour.
  4081. @see InputStream, MemoryOutputStream, FileOutputStream
  4082. */
  4083. class JUCE_API OutputStream
  4084. {
  4085. protected:
  4086. OutputStream();
  4087. public:
  4088. /** Destructor.
  4089. Some subclasses might want to do things like call flush() during their
  4090. destructors.
  4091. */
  4092. virtual ~OutputStream();
  4093. /** If the stream is using a buffer, this will ensure it gets written
  4094. out to the destination. */
  4095. virtual void flush() = 0;
  4096. /** Tries to move the stream's output position.
  4097. Not all streams will be able to seek to a new position - this will return
  4098. false if it fails to work.
  4099. @see getPosition
  4100. */
  4101. virtual bool setPosition (int64 newPosition) = 0;
  4102. /** Returns the stream's current position.
  4103. @see setPosition
  4104. */
  4105. virtual int64 getPosition() = 0;
  4106. /** Writes a block of data to the stream.
  4107. When creating a subclass of OutputStream, this is the only write method
  4108. that needs to be overloaded - the base class has methods for writing other
  4109. types of data which use this to do the work.
  4110. @returns false if the write operation fails for some reason
  4111. */
  4112. virtual bool write (const void* dataToWrite,
  4113. int howManyBytes) = 0;
  4114. /** Writes a single byte to the stream.
  4115. @see InputStream::readByte
  4116. */
  4117. virtual void writeByte (char byte);
  4118. /** Writes a boolean to the stream as a single byte.
  4119. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  4120. @see InputStream::readBool
  4121. */
  4122. virtual void writeBool (bool boolValue);
  4123. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  4124. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  4125. @see InputStream::readShort
  4126. */
  4127. virtual void writeShort (short value);
  4128. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  4129. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  4130. @see InputStream::readShortBigEndian
  4131. */
  4132. virtual void writeShortBigEndian (short value);
  4133. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  4134. @see InputStream::readInt
  4135. */
  4136. virtual void writeInt (int value);
  4137. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  4138. @see InputStream::readIntBigEndian
  4139. */
  4140. virtual void writeIntBigEndian (int value);
  4141. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  4142. @see InputStream::readInt64
  4143. */
  4144. virtual void writeInt64 (int64 value);
  4145. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  4146. @see InputStream::readInt64BigEndian
  4147. */
  4148. virtual void writeInt64BigEndian (int64 value);
  4149. /** Writes a 32-bit floating point value to the stream in a binary format.
  4150. The binary 32-bit encoding of the float is written as a little-endian int.
  4151. @see InputStream::readFloat
  4152. */
  4153. virtual void writeFloat (float value);
  4154. /** Writes a 32-bit floating point value to the stream in a binary format.
  4155. The binary 32-bit encoding of the float is written as a big-endian int.
  4156. @see InputStream::readFloatBigEndian
  4157. */
  4158. virtual void writeFloatBigEndian (float value);
  4159. /** Writes a 64-bit floating point value to the stream in a binary format.
  4160. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  4161. @see InputStream::readDouble
  4162. */
  4163. virtual void writeDouble (double value);
  4164. /** Writes a 64-bit floating point value to the stream in a binary format.
  4165. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  4166. @see InputStream::readDoubleBigEndian
  4167. */
  4168. virtual void writeDoubleBigEndian (double value);
  4169. /** Writes a condensed binary encoding of a 32-bit integer.
  4170. If you're storing a lot of integers which are unlikely to have very large values,
  4171. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  4172. under 0xffff only 3 bytes, etc.
  4173. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4174. @see InputStream::readCompressedInt
  4175. */
  4176. virtual void writeCompressedInt (int value);
  4177. /** Stores a string in the stream in a binary format.
  4178. This isn't the method to use if you're trying to append text to the end of a
  4179. text-file! It's intended for storing a string so that it can be retrieved later
  4180. by InputStream::readString().
  4181. It writes the string to the stream as UTF8, including the null termination character.
  4182. For appending text to a file, instead use writeText, or operator<<
  4183. @see InputStream::readString, writeText, operator<<
  4184. */
  4185. virtual void writeString (const String& text);
  4186. /** Writes a string of text to the stream.
  4187. It can either write it as UTF8 characters or as unicode, and
  4188. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  4189. should only be done at the start of a file).
  4190. The method also replaces '\\n' characters in the text with '\\r\\n'.
  4191. */
  4192. virtual void writeText (const String& text,
  4193. bool asUnicode,
  4194. bool writeUnicodeHeaderBytes);
  4195. /** Reads data from an input stream and writes it to this stream.
  4196. @param source the stream to read from
  4197. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  4198. less than zero, it will keep reading until the input
  4199. is exhausted)
  4200. */
  4201. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  4202. juce_UseDebuggingNewOperator
  4203. };
  4204. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4205. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  4206. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4207. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  4208. /** Writes a character to a stream. */
  4209. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  4210. /** Writes a null-terminated text string to a stream. */
  4211. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  4212. /** Writes a block of data from a MemoryBlock to a stream. */
  4213. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  4214. /** Writes the contents of a file to a stream. */
  4215. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  4216. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4217. /*** End of inlined file: juce_OutputStream.h ***/
  4218. class JUCE_API DynamicObject;
  4219. /**
  4220. A variant class, that can be used to hold a range of primitive values.
  4221. A var object can hold a range of simple primitive values, strings, or
  4222. a reference-counted pointer to a DynamicObject. The var class is intended
  4223. to act like the values used in dynamic scripting languages.
  4224. @see DynamicObject
  4225. */
  4226. class JUCE_API var
  4227. {
  4228. public:
  4229. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  4230. typedef Identifier identifier;
  4231. /** Creates a void variant. */
  4232. var() throw();
  4233. /** Destructor. */
  4234. ~var() throw();
  4235. /** A static var object that can be used where you need an empty variant object. */
  4236. static const var null;
  4237. var (const var& valueToCopy);
  4238. var (int value) throw();
  4239. var (bool value) throw();
  4240. var (double value) throw();
  4241. var (const char* value);
  4242. var (const juce_wchar* value);
  4243. var (const String& value);
  4244. var (DynamicObject* object);
  4245. var (MethodFunction method) throw();
  4246. var& operator= (const var& valueToCopy);
  4247. var& operator= (int value);
  4248. var& operator= (bool value);
  4249. var& operator= (double value);
  4250. var& operator= (const char* value);
  4251. var& operator= (const juce_wchar* value);
  4252. var& operator= (const String& value);
  4253. var& operator= (DynamicObject* object);
  4254. var& operator= (MethodFunction method);
  4255. void swapWith (var& other) throw();
  4256. operator int() const;
  4257. operator bool() const;
  4258. operator float() const;
  4259. operator double() const;
  4260. operator const String() const;
  4261. const String toString() const;
  4262. DynamicObject* getObject() const;
  4263. bool isVoid() const throw();
  4264. bool isInt() const throw();
  4265. bool isBool() const throw();
  4266. bool isDouble() const throw();
  4267. bool isString() const throw();
  4268. bool isObject() const throw();
  4269. bool isMethod() const throw();
  4270. /** Writes a binary representation of this value to a stream.
  4271. The data can be read back later using readFromStream().
  4272. */
  4273. void writeToStream (OutputStream& output) const;
  4274. /** Reads back a stored binary representation of a value.
  4275. The data in the stream must have been written using writeToStream(), or this
  4276. will have unpredictable results.
  4277. */
  4278. static const var readFromStream (InputStream& input);
  4279. /** If this variant is an object, this returns one of its properties. */
  4280. const var operator[] (const Identifier& propertyName) const;
  4281. /** If this variant is an object, this invokes one of its methods with no arguments. */
  4282. const var call (const Identifier& method) const;
  4283. /** If this variant is an object, this invokes one of its methods with one argument. */
  4284. const var call (const Identifier& method, const var& arg1) const;
  4285. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  4286. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  4287. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  4288. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  4289. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  4290. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  4291. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  4292. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  4293. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  4294. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  4295. /** If this variant is a method pointer, this invokes it on a target object. */
  4296. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  4297. juce_UseDebuggingNewOperator
  4298. /** Returns true if this var has the same value as the one supplied. */
  4299. bool equals (const var& other) const throw();
  4300. private:
  4301. class VariantType;
  4302. friend class VariantType;
  4303. class VariantType_Void;
  4304. friend class VariantType_Void;
  4305. class VariantType_Int;
  4306. friend class VariantType_Int;
  4307. class VariantType_Double;
  4308. friend class VariantType_Double;
  4309. class VariantType_Float;
  4310. friend class VariantType_Float;
  4311. class VariantType_Bool;
  4312. friend class VariantType_Bool;
  4313. class VariantType_String;
  4314. friend class VariantType_String;
  4315. class VariantType_Object;
  4316. friend class VariantType_Object;
  4317. class VariantType_Method;
  4318. friend class VariantType_Method;
  4319. union ValueUnion
  4320. {
  4321. int intValue;
  4322. bool boolValue;
  4323. double doubleValue;
  4324. String* stringValue;
  4325. DynamicObject* objectValue;
  4326. MethodFunction methodValue;
  4327. };
  4328. const VariantType* type;
  4329. ValueUnion value;
  4330. };
  4331. bool operator== (const var& v1, const var& v2) throw();
  4332. bool operator!= (const var& v1, const var& v2) throw();
  4333. bool operator== (const var& v1, const String& v2) throw();
  4334. bool operator!= (const var& v1, const String& v2) throw();
  4335. #endif // __JUCE_VARIANT_JUCEHEADER__
  4336. /*** End of inlined file: juce_Variant.h ***/
  4337. /** Holds a set of named var objects.
  4338. This can be used as a basic structure to hold a set of var object, which can
  4339. be retrieved by using their identifier.
  4340. */
  4341. class JUCE_API NamedValueSet
  4342. {
  4343. public:
  4344. /** Creates an empty set. */
  4345. NamedValueSet() throw();
  4346. /** Creates a copy of another set. */
  4347. NamedValueSet (const NamedValueSet& other);
  4348. /** Replaces this set with a copy of another set. */
  4349. NamedValueSet& operator= (const NamedValueSet& other);
  4350. /** Destructor. */
  4351. ~NamedValueSet();
  4352. bool operator== (const NamedValueSet& other) const;
  4353. bool operator!= (const NamedValueSet& other) const;
  4354. /** Returns the total number of values that the set contains. */
  4355. int size() const throw();
  4356. /** Returns the value of a named item.
  4357. If the name isn't found, this will return a void variant.
  4358. @see getProperty
  4359. */
  4360. const var& operator[] (const Identifier& name) const;
  4361. /** Tries to return the named value, but if no such value is found, this will
  4362. instead return the supplied default value.
  4363. */
  4364. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  4365. /** Returns a pointer to the object holding a named value, or
  4366. null if there is no value with this name. */
  4367. var* getItem (const Identifier& name) const;
  4368. /** Changes or adds a named value.
  4369. @returns true if a value was changed or added; false if the
  4370. value was already set the the value passed-in.
  4371. */
  4372. bool set (const Identifier& name, const var& newValue);
  4373. /** Returns true if the set contains an item with the specified name. */
  4374. bool contains (const Identifier& name) const;
  4375. /** Removes a value from the set.
  4376. @returns true if a value was removed; false if there was no value
  4377. with the name that was given.
  4378. */
  4379. bool remove (const Identifier& name);
  4380. /** Returns the name of the value at a given index.
  4381. The index must be between 0 and size() - 1. Out-of-range indexes will
  4382. return an empty identifier.
  4383. */
  4384. const Identifier getName (int index) const;
  4385. /** Returns the value of the item at a given index.
  4386. The index must be between 0 and size() - 1. Out-of-range indexes will
  4387. return an empty identifier.
  4388. */
  4389. const var getValueAt (int index) const;
  4390. /** Removes all values. */
  4391. void clear();
  4392. juce_UseDebuggingNewOperator
  4393. private:
  4394. struct NamedValue
  4395. {
  4396. NamedValue() throw();
  4397. NamedValue (const Identifier& name, const var& value);
  4398. bool operator== (const NamedValue& other) const throw();
  4399. Identifier name;
  4400. var value;
  4401. };
  4402. Array <NamedValue> values;
  4403. };
  4404. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  4405. /*** End of inlined file: juce_NamedValueSet.h ***/
  4406. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  4407. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4408. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4409. /*** Start of inlined file: juce_Atomic.h ***/
  4410. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  4411. #define __JUCE_ATOMIC_JUCEHEADER__
  4412. /**
  4413. Simple class to hold a primitive value and perform atomic operations on it.
  4414. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  4415. There are methods to perform most of the basic atomic operations.
  4416. */
  4417. template <typename Type>
  4418. class Atomic
  4419. {
  4420. public:
  4421. /** Creates a new value, initialised to zero. */
  4422. inline Atomic() throw()
  4423. : value (0)
  4424. {
  4425. }
  4426. /** Creates a new value, with a given initial value. */
  4427. inline Atomic (const Type initialValue) throw()
  4428. : value (initialValue)
  4429. {
  4430. }
  4431. /** Copies another value (atomically). */
  4432. inline Atomic (const Atomic& other) throw()
  4433. : value (other.get())
  4434. {
  4435. }
  4436. /** Copies another value onto this one (atomically). */
  4437. inline Atomic& operator= (const Atomic& other) throw()
  4438. {
  4439. set (other.get());
  4440. return *this;
  4441. }
  4442. /** Destructor. */
  4443. inline ~Atomic() throw()
  4444. {
  4445. // This class can only be used for types which are 32 or 64 bits in size.
  4446. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  4447. }
  4448. /** Atomically reads and returns the current value. */
  4449. Type get() const throw();
  4450. /** Atomically sets the current value. */
  4451. void set (Type newValue) throw();
  4452. /** Atomically sets the current value, returning the value that was replaced. */
  4453. Type exchange (Type value) throw();
  4454. /** Atomically adds a number to this value, returning the new value. */
  4455. Type operator+= (Type amountToAdd) throw();
  4456. /** Atomically subtracts a number from this value, returning the new value. */
  4457. Type operator-= (Type amountToSubtract) throw();
  4458. /** Atomically increments this value, returning the new value. */
  4459. Type operator++() throw();
  4460. /** Atomically decrements this value, returning the new value. */
  4461. Type operator--() throw();
  4462. /** Atomically compares this value with a target value, and if it is equal, sets
  4463. this to be equal to a new value.
  4464. This operation is the atomic equivalent of doing this:
  4465. @code
  4466. bool compareAndSetBool (Type newValue, Type valueToCompare)
  4467. {
  4468. if (get() == valueToCompare)
  4469. {
  4470. set (newValue);
  4471. return true;
  4472. }
  4473. return false;
  4474. }
  4475. @endcode
  4476. @returns true if the comparison was true and the value was replaced; false if
  4477. the comparison failed and the value was left unchanged.
  4478. @see compareAndSetValue
  4479. */
  4480. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  4481. /** Atomically compares this value with a target value, and if it is equal, sets
  4482. this to be equal to a new value.
  4483. This operation is the atomic equivalent of doing this:
  4484. @code
  4485. Type compareAndSetValue (Type newValue, Type valueToCompare)
  4486. {
  4487. Type oldValue = get();
  4488. if (oldValue == valueToCompare)
  4489. set (newValue);
  4490. return oldValue;
  4491. }
  4492. @endcode
  4493. @returns the old value before it was changed.
  4494. @see compareAndSetBool
  4495. */
  4496. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  4497. /** Implements a memory read/write barrier. */
  4498. static void memoryBarrier() throw();
  4499. JUCE_ALIGN(8)
  4500. /** The raw value that this class operates on.
  4501. This is exposed publically in case you need to manipulate it directly
  4502. for performance reasons.
  4503. */
  4504. Type value;
  4505. };
  4506. /*
  4507. The following code is in the header so that the atomics can be inlined where possible...
  4508. */
  4509. #if (JUCE_IPHONE && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  4510. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  4511. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  4512. #if JUCE_PPC || JUCE_IPHONE
  4513. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  4514. template <typename Type> static Type OSAtomicAdd64 (Type b, volatile Type* a) throw() { jassertfalse; return *a += b; }
  4515. template <typename Type> static Type OSAtomicIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4516. template <typename Type> static Type OSAtomicDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4517. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, volatile Type* value) throw()
  4518. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  4519. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4520. #endif
  4521. #elif JUCE_GCC
  4522. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  4523. #else
  4524. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  4525. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  4526. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  4527. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  4528. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  4529. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  4530. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  4531. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  4532. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  4533. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  4534. #define juce_MemoryBarrier _ReadWriteBarrier
  4535. #else
  4536. // (these are defined in juce_win32_Threads.cpp)
  4537. long juce_InterlockedExchange (volatile long* a, long b) throw();
  4538. long juce_InterlockedIncrement (volatile long* a) throw();
  4539. long juce_InterlockedDecrement (volatile long* a) throw();
  4540. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  4541. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  4542. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  4543. static void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  4544. #endif
  4545. #if JUCE_64BIT
  4546. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  4547. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  4548. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  4549. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  4550. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  4551. #else
  4552. // None of these atomics are available in a 32-bit Windows build!!
  4553. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  4554. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  4555. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4556. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4557. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4558. #endif
  4559. #endif
  4560. #if JUCE_MSVC
  4561. #pragma warning (push)
  4562. #pragma warning (disable: 4311) // (truncation warning)
  4563. #endif
  4564. template <typename Type>
  4565. inline Type Atomic<Type>::get() const throw()
  4566. {
  4567. return const_cast <Atomic<Type>*> (this)->operator+= (0);
  4568. }
  4569. template <typename Type>
  4570. inline void Atomic<Type>::set (const Type newValue) throw()
  4571. {
  4572. exchange (newValue);
  4573. }
  4574. template <typename Type>
  4575. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  4576. {
  4577. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  4578. Type currentVal = value;
  4579. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  4580. return currentVal;
  4581. #elif JUCE_ATOMICS_WINDOWS
  4582. return sizeof (Type) == 4 ? (Type) juce_InterlockedExchange ((volatile long*) &value, (long) newValue)
  4583. : (Type) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) newValue);
  4584. #endif
  4585. }
  4586. template <typename Type>
  4587. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  4588. {
  4589. #if JUCE_ATOMICS_MAC
  4590. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32 ((int32_t) amountToAdd, (int32_t*) &value)
  4591. : (Type) OSAtomicAdd64 ((int64_t) amountToAdd, (int64_t*) &value);
  4592. #elif JUCE_ATOMICS_WINDOWS
  4593. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  4594. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  4595. #elif JUCE_ATOMICS_GCC
  4596. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  4597. #endif
  4598. }
  4599. template <typename Type>
  4600. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  4601. {
  4602. return operator+= (juce_negate (amountToSubtract));
  4603. }
  4604. template <typename Type>
  4605. inline Type Atomic<Type>::operator++() throw()
  4606. {
  4607. #if JUCE_ATOMICS_MAC
  4608. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32 ((int32_t*) &value)
  4609. : (Type) OSAtomicIncrement64 ((int64_t*) &value);
  4610. #elif JUCE_ATOMICS_WINDOWS
  4611. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  4612. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  4613. #elif JUCE_ATOMICS_GCC
  4614. return (Type) __sync_add_and_fetch (&value, 1);
  4615. #endif
  4616. }
  4617. template <typename Type>
  4618. inline Type Atomic<Type>::operator--() throw()
  4619. {
  4620. #if JUCE_ATOMICS_MAC
  4621. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32 ((int32_t*) &value)
  4622. : (Type) OSAtomicDecrement64 ((int64_t*) &value);
  4623. #elif JUCE_ATOMICS_WINDOWS
  4624. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  4625. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  4626. #elif JUCE_ATOMICS_GCC
  4627. return (Type) __sync_add_and_fetch (&value, -1);
  4628. #endif
  4629. }
  4630. template <typename Type>
  4631. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  4632. {
  4633. #if JUCE_ATOMICS_MAC
  4634. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) valueToCompare, (int32_t) newValue, (int32_t*) &value)
  4635. : OSAtomicCompareAndSwap64Barrier ((int64_t) valueToCompare, (int64_t) newValue, (int64_t*) &value);
  4636. #elif JUCE_ATOMICS_WINDOWS
  4637. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  4638. #elif JUCE_ATOMICS_GCC
  4639. return __sync_bool_compare_and_swap (&value, valueToCompare, newValue);
  4640. #endif
  4641. }
  4642. template <typename Type>
  4643. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  4644. {
  4645. #if JUCE_ATOMICS_MAC
  4646. for (;;) // Annoying workaround for OSX only having a bool CAS operation..
  4647. {
  4648. if (compareAndSetBool (newValue, valueToCompare))
  4649. return valueToCompare;
  4650. const Type result = value;
  4651. if (result != valueToCompare)
  4652. return result;
  4653. }
  4654. #elif JUCE_ATOMICS_WINDOWS
  4655. return sizeof (Type) == 4 ? (Type) juce_InterlockedCompareExchange ((volatile long*) &value, (long) newValue, (long) valueToCompare)
  4656. : (Type) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) newValue, (__int64) valueToCompare);
  4657. #elif JUCE_ATOMICS_GCC
  4658. return __sync_val_compare_and_swap (&value, valueToCompare, newValue);
  4659. #endif
  4660. }
  4661. template <typename Type>
  4662. inline void Atomic<Type>::memoryBarrier() throw()
  4663. {
  4664. #if JUCE_ATOMICS_MAC
  4665. OSMemoryBarrier();
  4666. #elif JUCE_ATOMICS_GCC
  4667. __sync_synchronize();
  4668. #elif JUCE_ATOMICS_WINDOWS
  4669. juce_MemoryBarrier();
  4670. #endif
  4671. }
  4672. #if JUCE_MSVC
  4673. #pragma warning (pop)
  4674. #endif
  4675. #endif // __JUCE_ATOMIC_JUCEHEADER__
  4676. /*** End of inlined file: juce_Atomic.h ***/
  4677. /**
  4678. Adds reference-counting to an object.
  4679. To add reference-counting to a class, derive it from this class, and
  4680. use the ReferenceCountedObjectPtr class to point to it.
  4681. e.g. @code
  4682. class MyClass : public ReferenceCountedObject
  4683. {
  4684. void foo();
  4685. // This is a neat way of declaring a typedef for a pointer class,
  4686. // rather than typing out the full templated name each time..
  4687. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  4688. };
  4689. MyClass::Ptr p = new MyClass();
  4690. MyClass::Ptr p2 = p;
  4691. p = 0;
  4692. p2->foo();
  4693. @endcode
  4694. Once a new ReferenceCountedObject has been assigned to a pointer, be
  4695. careful not to delete the object manually.
  4696. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  4697. */
  4698. class JUCE_API ReferenceCountedObject
  4699. {
  4700. public:
  4701. /** Increments the object's reference count.
  4702. This is done automatically by the smart pointer, but is public just
  4703. in case it's needed for nefarious purposes.
  4704. */
  4705. inline void incReferenceCount() throw()
  4706. {
  4707. ++refCount;
  4708. }
  4709. /** Decreases the object's reference count.
  4710. If the count gets to zero, the object will be deleted.
  4711. */
  4712. inline void decReferenceCount() throw()
  4713. {
  4714. jassert (getReferenceCount() > 0);
  4715. if (--refCount == 0)
  4716. delete this;
  4717. }
  4718. /** Returns the object's current reference count. */
  4719. inline int getReferenceCount() const throw()
  4720. {
  4721. return refCount.get();
  4722. }
  4723. protected:
  4724. /** Creates the reference-counted object (with an initial ref count of zero). */
  4725. ReferenceCountedObject()
  4726. {
  4727. }
  4728. /** Destructor. */
  4729. virtual ~ReferenceCountedObject()
  4730. {
  4731. // it's dangerous to delete an object that's still referenced by something else!
  4732. jassert (getReferenceCount() == 0);
  4733. }
  4734. private:
  4735. Atomic <int> refCount;
  4736. };
  4737. /**
  4738. Used to point to an object of type ReferenceCountedObject.
  4739. It's wise to use a typedef instead of typing out the templated name
  4740. each time - e.g.
  4741. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  4742. @see ReferenceCountedObject, ReferenceCountedObjectArray
  4743. */
  4744. template <class ReferenceCountedObjectClass>
  4745. class ReferenceCountedObjectPtr
  4746. {
  4747. public:
  4748. /** Creates a pointer to a null object. */
  4749. inline ReferenceCountedObjectPtr() throw()
  4750. : referencedObject (0)
  4751. {
  4752. }
  4753. /** Creates a pointer to an object.
  4754. This will increment the object's reference-count if it is non-null.
  4755. */
  4756. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  4757. : referencedObject (refCountedObject)
  4758. {
  4759. if (refCountedObject != 0)
  4760. refCountedObject->incReferenceCount();
  4761. }
  4762. /** Copies another pointer.
  4763. This will increment the object's reference-count (if it is non-null).
  4764. */
  4765. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  4766. : referencedObject (other.referencedObject)
  4767. {
  4768. if (referencedObject != 0)
  4769. referencedObject->incReferenceCount();
  4770. }
  4771. /** Changes this pointer to point at a different object.
  4772. The reference count of the old object is decremented, and it might be
  4773. deleted if it hits zero. The new object's count is incremented.
  4774. */
  4775. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  4776. {
  4777. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  4778. if (newObject != referencedObject)
  4779. {
  4780. if (newObject != 0)
  4781. newObject->incReferenceCount();
  4782. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4783. referencedObject = newObject;
  4784. if (oldObject != 0)
  4785. oldObject->decReferenceCount();
  4786. }
  4787. return *this;
  4788. }
  4789. /** Changes this pointer to point at a different object.
  4790. The reference count of the old object is decremented, and it might be
  4791. deleted if it hits zero. The new object's count is incremented.
  4792. */
  4793. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  4794. {
  4795. if (referencedObject != newObject)
  4796. {
  4797. if (newObject != 0)
  4798. newObject->incReferenceCount();
  4799. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4800. referencedObject = newObject;
  4801. if (oldObject != 0)
  4802. oldObject->decReferenceCount();
  4803. }
  4804. return *this;
  4805. }
  4806. /** Destructor.
  4807. This will decrement the object's reference-count, and may delete it if it
  4808. gets to zero.
  4809. */
  4810. inline ~ReferenceCountedObjectPtr()
  4811. {
  4812. if (referencedObject != 0)
  4813. referencedObject->decReferenceCount();
  4814. }
  4815. /** Returns the object that this pointer references.
  4816. The pointer returned may be zero, of course.
  4817. */
  4818. inline operator ReferenceCountedObjectClass*() const throw()
  4819. {
  4820. return referencedObject;
  4821. }
  4822. /** Returns true if this pointer refers to the given object. */
  4823. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  4824. {
  4825. return referencedObject == object;
  4826. }
  4827. /** Returns true if this pointer doesn't refer to the given object. */
  4828. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  4829. {
  4830. return referencedObject != object;
  4831. }
  4832. // the -> operator is called on the referenced object
  4833. inline ReferenceCountedObjectClass* operator->() const throw()
  4834. {
  4835. return referencedObject;
  4836. }
  4837. /** Returns the object that this pointer references.
  4838. The pointer returned may be zero, of course.
  4839. */
  4840. inline ReferenceCountedObjectClass* getObject() const throw()
  4841. {
  4842. return referencedObject;
  4843. }
  4844. private:
  4845. ReferenceCountedObjectClass* referencedObject;
  4846. };
  4847. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4848. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  4849. /**
  4850. Represents a dynamically implemented object.
  4851. This class is primarily intended for wrapping scripting language objects,
  4852. but could be used for other purposes.
  4853. An instance of a DynamicObject can be used to store named properties, and
  4854. by subclassing hasMethod() and invokeMethod(), you can give your object
  4855. methods.
  4856. */
  4857. class JUCE_API DynamicObject : public ReferenceCountedObject
  4858. {
  4859. public:
  4860. DynamicObject();
  4861. /** Destructor. */
  4862. virtual ~DynamicObject();
  4863. /** Returns true if the object has a property with this name.
  4864. Note that if the property is actually a method, this will return false.
  4865. */
  4866. virtual bool hasProperty (const Identifier& propertyName) const;
  4867. /** Returns a named property.
  4868. This returns a void if no such property exists.
  4869. */
  4870. virtual const var getProperty (const Identifier& propertyName) const;
  4871. /** Sets a named property. */
  4872. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  4873. /** Removes a named property. */
  4874. virtual void removeProperty (const Identifier& propertyName);
  4875. /** Checks whether this object has the specified method.
  4876. The default implementation of this just checks whether there's a property
  4877. with this name that's actually a method, but this can be overridden for
  4878. building objects with dynamic invocation.
  4879. */
  4880. virtual bool hasMethod (const Identifier& methodName) const;
  4881. /** Invokes a named method on this object.
  4882. The default implementation looks up the named property, and if it's a method
  4883. call, then it invokes it.
  4884. This method is virtual to allow more dynamic invocation to used for objects
  4885. where the methods may not already be set as properies.
  4886. */
  4887. virtual const var invokeMethod (const Identifier& methodName,
  4888. const var* parameters,
  4889. int numParameters);
  4890. /** Sets up a method.
  4891. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  4892. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  4893. the code easier to read,
  4894. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  4895. @code
  4896. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  4897. @endcode
  4898. */
  4899. void setMethod (const Identifier& methodName,
  4900. var::MethodFunction methodFunction);
  4901. /** Removes all properties and methods from the object. */
  4902. void clear();
  4903. juce_UseDebuggingNewOperator
  4904. private:
  4905. NamedValueSet properties;
  4906. };
  4907. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4908. /*** End of inlined file: juce_DynamicObject.h ***/
  4909. #endif
  4910. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4911. #endif
  4912. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4913. #endif
  4914. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  4915. #endif
  4916. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4917. #endif
  4918. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  4919. #endif
  4920. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4921. /*** Start of inlined file: juce_OwnedArray.h ***/
  4922. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4923. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  4924. /*** Start of inlined file: juce_ScopedPointer.h ***/
  4925. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4926. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4927. /**
  4928. This class holds a pointer which is automatically deleted when this object goes
  4929. out of scope.
  4930. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  4931. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  4932. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  4933. created objects.
  4934. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  4935. to an object. If you use the assignment operator to assign a different object to a
  4936. ScopedPointer, the old one will be automatically deleted.
  4937. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  4938. object to which it points during its lifetime. This means that making a copy of a const
  4939. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  4940. old one.
  4941. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  4942. can use the release() method.
  4943. */
  4944. template <class ObjectType>
  4945. class ScopedPointer
  4946. {
  4947. public:
  4948. /** Creates a ScopedPointer containing a null pointer. */
  4949. inline ScopedPointer() throw() : object (0)
  4950. {
  4951. }
  4952. /** Creates a ScopedPointer that owns the specified object. */
  4953. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  4954. : object (objectToTakePossessionOf)
  4955. {
  4956. }
  4957. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  4958. Because a pointer can only belong to one ScopedPointer, this transfers
  4959. the pointer from the other object to this one, and the other object is reset to
  4960. be a null pointer.
  4961. */
  4962. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  4963. : object (objectToTransferFrom.object)
  4964. {
  4965. objectToTransferFrom.object = 0;
  4966. }
  4967. /** Destructor.
  4968. This will delete the object that this ScopedPointer currently refers to.
  4969. */
  4970. inline ~ScopedPointer() { delete object; }
  4971. /** Changes this ScopedPointer to point to a new object.
  4972. Because a pointer can only belong to one ScopedPointer, this transfers
  4973. the pointer from the other object to this one, and the other object is reset to
  4974. be a null pointer.
  4975. If this ScopedPointer already points to an object, that object
  4976. will first be deleted.
  4977. */
  4978. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  4979. {
  4980. if (this != objectToTransferFrom.getAddress())
  4981. {
  4982. // Two ScopedPointers should never be able to refer to the same object - if
  4983. // this happens, you must have done something dodgy!
  4984. jassert (object == 0 || object != objectToTransferFrom.object);
  4985. ObjectType* const oldObject = object;
  4986. object = objectToTransferFrom.object;
  4987. objectToTransferFrom.object = 0;
  4988. delete oldObject;
  4989. }
  4990. return *this;
  4991. }
  4992. /** Changes this ScopedPointer to point to a new object.
  4993. If this ScopedPointer already points to an object, that object
  4994. will first be deleted.
  4995. The pointer that you pass is may be null.
  4996. */
  4997. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  4998. {
  4999. if (object != newObjectToTakePossessionOf)
  5000. {
  5001. ObjectType* const oldObject = object;
  5002. object = newObjectToTakePossessionOf;
  5003. delete oldObject;
  5004. }
  5005. return *this;
  5006. }
  5007. /** Returns the object that this ScopedPointer refers to.
  5008. */
  5009. inline operator ObjectType*() const throw() { return object; }
  5010. /** Returns the object that this ScopedPointer refers to.
  5011. */
  5012. inline ObjectType& operator*() const throw() { return *object; }
  5013. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  5014. inline ObjectType* operator->() const throw() { return object; }
  5015. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  5016. inline ObjectType* const* operator&() const throw() { return static_cast <ObjectType* const*> (&object); }
  5017. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  5018. inline ObjectType** operator&() throw() { return static_cast <ObjectType**> (&object); }
  5019. /** Removes the current object from this ScopedPointer without deleting it.
  5020. This will return the current object, and set the ScopedPointer to a null pointer.
  5021. */
  5022. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  5023. /** Swaps this object with that of another ScopedPointer.
  5024. The two objects simply exchange their pointers.
  5025. */
  5026. void swapWith (ScopedPointer <ObjectType>& other) throw()
  5027. {
  5028. // Two ScopedPointers should never be able to refer to the same object - if
  5029. // this happens, you must have done something dodgy!
  5030. jassert (object != other.object);
  5031. swapVariables (object, other.object);
  5032. }
  5033. private:
  5034. ObjectType* object;
  5035. // (Required as an alternative to the overloaded & operator).
  5036. const ScopedPointer* getAddress() const throw() { return this; }
  5037. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  5038. // This is private to stop people accidentally copying a const ScopedPointer (the compiler
  5039. // will let you do so by implicitly casting the source to its raw object pointer).
  5040. ScopedPointer (const ScopedPointer&);
  5041. #endif
  5042. };
  5043. /** Compares a ScopedPointer with another pointer.
  5044. This can be handy for checking whether this is a null pointer.
  5045. */
  5046. template <class ObjectType>
  5047. inline bool operator== (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5048. {
  5049. return static_cast <ObjectType*> (pointer1) == pointer2;
  5050. }
  5051. /** Compares a ScopedPointer with another pointer.
  5052. This can be handy for checking whether this is a null pointer.
  5053. */
  5054. template <class ObjectType>
  5055. inline bool operator!= (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5056. {
  5057. return static_cast <ObjectType*> (pointer1) != pointer2;
  5058. }
  5059. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  5060. /*** End of inlined file: juce_ScopedPointer.h ***/
  5061. /** An array designed for holding objects.
  5062. This holds a list of pointers to objects, and will automatically
  5063. delete the objects when they are removed from the array, or when the
  5064. array is itself deleted.
  5065. Declare it in the form: OwnedArray<MyObjectClass>
  5066. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  5067. After adding objects, they are 'owned' by the array and will be deleted when
  5068. removed or replaced.
  5069. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5070. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5071. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  5072. */
  5073. template <class ObjectClass,
  5074. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  5075. class OwnedArray
  5076. {
  5077. public:
  5078. /** Creates an empty array. */
  5079. OwnedArray() throw()
  5080. : numUsed (0)
  5081. {
  5082. }
  5083. /** Deletes the array and also deletes any objects inside it.
  5084. To get rid of the array without deleting its objects, use its
  5085. clear (false) method before deleting it.
  5086. */
  5087. ~OwnedArray()
  5088. {
  5089. clear (true);
  5090. }
  5091. /** Clears the array, optionally deleting the objects inside it first. */
  5092. void clear (const bool deleteObjects = true)
  5093. {
  5094. const ScopedLockType lock (getLock());
  5095. if (deleteObjects)
  5096. {
  5097. while (numUsed > 0)
  5098. delete data.elements [--numUsed];
  5099. }
  5100. data.setAllocatedSize (0);
  5101. numUsed = 0;
  5102. }
  5103. /** Returns the number of items currently in the array.
  5104. @see operator[]
  5105. */
  5106. inline int size() const throw()
  5107. {
  5108. return numUsed;
  5109. }
  5110. /** Returns a pointer to the object at this index in the array.
  5111. If the index is out-of-range, this will return a null pointer, (and
  5112. it could be null anyway, because it's ok for the array to hold null
  5113. pointers as well as objects).
  5114. @see getUnchecked
  5115. */
  5116. inline ObjectClass* operator[] (const int index) const throw()
  5117. {
  5118. const ScopedLockType lock (getLock());
  5119. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  5120. : static_cast <ObjectClass*> (0);
  5121. }
  5122. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  5123. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  5124. it can be used when you're sure the index if always going to be legal.
  5125. */
  5126. inline ObjectClass* getUnchecked (const int index) const throw()
  5127. {
  5128. const ScopedLockType lock (getLock());
  5129. jassert (((unsigned int) index) < (unsigned int) numUsed);
  5130. return data.elements [index];
  5131. }
  5132. /** Returns a pointer to the first object in the array.
  5133. This will return a null pointer if the array's empty.
  5134. @see getLast
  5135. */
  5136. inline ObjectClass* getFirst() const throw()
  5137. {
  5138. const ScopedLockType lock (getLock());
  5139. return numUsed > 0 ? data.elements [0]
  5140. : static_cast <ObjectClass*> (0);
  5141. }
  5142. /** Returns a pointer to the last object in the array.
  5143. This will return a null pointer if the array's empty.
  5144. @see getFirst
  5145. */
  5146. inline ObjectClass* getLast() const throw()
  5147. {
  5148. const ScopedLockType lock (getLock());
  5149. return numUsed > 0 ? data.elements [numUsed - 1]
  5150. : static_cast <ObjectClass*> (0);
  5151. }
  5152. /** Returns a pointer to the actual array data.
  5153. This pointer will only be valid until the next time a non-const method
  5154. is called on the array.
  5155. */
  5156. inline ObjectClass** getRawDataPointer() throw()
  5157. {
  5158. return data.elements;
  5159. }
  5160. /** Finds the index of an object which might be in the array.
  5161. @param objectToLookFor the object to look for
  5162. @returns the index at which the object was found, or -1 if it's not found
  5163. */
  5164. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  5165. {
  5166. const ScopedLockType lock (getLock());
  5167. ObjectClass* const* e = data.elements.getData();
  5168. ObjectClass* const* const end = e + numUsed;
  5169. while (e != end)
  5170. {
  5171. if (objectToLookFor == *e)
  5172. return static_cast <int> (e - data.elements.getData());
  5173. ++e;
  5174. }
  5175. return -1;
  5176. }
  5177. /** Returns true if the array contains a specified object.
  5178. @param objectToLookFor the object to look for
  5179. @returns true if the object is in the array
  5180. */
  5181. bool contains (const ObjectClass* const objectToLookFor) const throw()
  5182. {
  5183. const ScopedLockType lock (getLock());
  5184. ObjectClass* const* e = data.elements.getData();
  5185. ObjectClass* const* const end = e + numUsed;
  5186. while (e != end)
  5187. {
  5188. if (objectToLookFor == *e)
  5189. return true;
  5190. ++e;
  5191. }
  5192. return false;
  5193. }
  5194. /** Appends a new object to the end of the array.
  5195. Note that the this object will be deleted by the OwnedArray when it
  5196. is removed, so be careful not to delete it somewhere else.
  5197. Also be careful not to add the same object to the array more than once,
  5198. as this will obviously cause deletion of dangling pointers.
  5199. @param newObject the new object to add to the array
  5200. @see set, insert, addIfNotAlreadyThere, addSorted
  5201. */
  5202. void add (const ObjectClass* const newObject) throw()
  5203. {
  5204. const ScopedLockType lock (getLock());
  5205. data.ensureAllocatedSize (numUsed + 1);
  5206. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5207. }
  5208. /** Inserts a new object into the array at the given index.
  5209. Note that the this object will be deleted by the OwnedArray when it
  5210. is removed, so be careful not to delete it somewhere else.
  5211. If the index is less than 0 or greater than the size of the array, the
  5212. element will be added to the end of the array.
  5213. Otherwise, it will be inserted into the array, moving all the later elements
  5214. along to make room.
  5215. Be careful not to add the same object to the array more than once,
  5216. as this will obviously cause deletion of dangling pointers.
  5217. @param indexToInsertAt the index at which the new element should be inserted
  5218. @param newObject the new object to add to the array
  5219. @see add, addSorted, addIfNotAlreadyThere, set
  5220. */
  5221. void insert (int indexToInsertAt,
  5222. const ObjectClass* const newObject) throw()
  5223. {
  5224. if (indexToInsertAt >= 0)
  5225. {
  5226. const ScopedLockType lock (getLock());
  5227. if (indexToInsertAt > numUsed)
  5228. indexToInsertAt = numUsed;
  5229. data.ensureAllocatedSize (numUsed + 1);
  5230. ObjectClass** const e = data.elements + indexToInsertAt;
  5231. const int numToMove = numUsed - indexToInsertAt;
  5232. if (numToMove > 0)
  5233. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  5234. *e = const_cast <ObjectClass*> (newObject);
  5235. ++numUsed;
  5236. }
  5237. else
  5238. {
  5239. add (newObject);
  5240. }
  5241. }
  5242. /** Appends a new object at the end of the array as long as the array doesn't
  5243. already contain it.
  5244. If the array already contains a matching object, nothing will be done.
  5245. @param newObject the new object to add to the array
  5246. */
  5247. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  5248. {
  5249. const ScopedLockType lock (getLock());
  5250. if (! contains (newObject))
  5251. add (newObject);
  5252. }
  5253. /** Replaces an object in the array with a different one.
  5254. If the index is less than zero, this method does nothing.
  5255. If the index is beyond the end of the array, the new object is added to the end of the array.
  5256. Be careful not to add the same object to the array more than once,
  5257. as this will obviously cause deletion of dangling pointers.
  5258. @param indexToChange the index whose value you want to change
  5259. @param newObject the new value to set for this index.
  5260. @param deleteOldElement whether to delete the object that's being replaced with the new one
  5261. @see add, insert, remove
  5262. */
  5263. void set (const int indexToChange,
  5264. const ObjectClass* const newObject,
  5265. const bool deleteOldElement = true)
  5266. {
  5267. if (indexToChange >= 0)
  5268. {
  5269. ScopedPointer <ObjectClass> toDelete;
  5270. const ScopedLockType lock (getLock());
  5271. if (indexToChange < numUsed)
  5272. {
  5273. if (deleteOldElement)
  5274. {
  5275. toDelete = data.elements [indexToChange];
  5276. if (toDelete == newObject)
  5277. toDelete = 0;
  5278. }
  5279. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  5280. }
  5281. else
  5282. {
  5283. data.ensureAllocatedSize (numUsed + 1);
  5284. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5285. }
  5286. }
  5287. }
  5288. /** Adds elements from another array to the end of this array.
  5289. @param arrayToAddFrom the array from which to copy the elements
  5290. @param startIndex the first element of the other array to start copying from
  5291. @param numElementsToAdd how many elements to add from the other array. If this
  5292. value is negative or greater than the number of available elements,
  5293. all available elements will be copied.
  5294. @see add
  5295. */
  5296. template <class OtherArrayType>
  5297. void addArray (const OtherArrayType& arrayToAddFrom,
  5298. int startIndex = 0,
  5299. int numElementsToAdd = -1)
  5300. {
  5301. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5302. const ScopedLockType lock2 (getLock());
  5303. if (startIndex < 0)
  5304. {
  5305. jassertfalse;
  5306. startIndex = 0;
  5307. }
  5308. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5309. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5310. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5311. while (--numElementsToAdd >= 0)
  5312. {
  5313. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  5314. ++numUsed;
  5315. }
  5316. }
  5317. /** Adds copies of the elements in another array to the end of this array.
  5318. The other array must be either an OwnedArray of a compatible type of object, or an Array
  5319. containing pointers to the same kind of object. The objects involved must provide
  5320. a copy constructor, and this will be used to create new copies of each element, and
  5321. add them to this array.
  5322. @param arrayToAddFrom the array from which to copy the elements
  5323. @param startIndex the first element of the other array to start copying from
  5324. @param numElementsToAdd how many elements to add from the other array. If this
  5325. value is negative or greater than the number of available elements,
  5326. all available elements will be copied.
  5327. @see add
  5328. */
  5329. template <class OtherArrayType>
  5330. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  5331. int startIndex = 0,
  5332. int numElementsToAdd = -1)
  5333. {
  5334. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5335. const ScopedLockType lock2 (getLock());
  5336. if (startIndex < 0)
  5337. {
  5338. jassertfalse;
  5339. startIndex = 0;
  5340. }
  5341. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5342. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5343. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5344. while (--numElementsToAdd >= 0)
  5345. {
  5346. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  5347. ++numUsed;
  5348. }
  5349. }
  5350. /** Inserts a new object into the array assuming that the array is sorted.
  5351. This will use a comparator to find the position at which the new object
  5352. should go. If the array isn't sorted, the behaviour of this
  5353. method will be unpredictable.
  5354. @param comparator the comparator to use to compare the elements - see the sort method
  5355. for details about this object's structure
  5356. @param newObject the new object to insert to the array
  5357. @see add, sort, indexOfSorted
  5358. */
  5359. template <class ElementComparator>
  5360. void addSorted (ElementComparator& comparator,
  5361. ObjectClass* const newObject) throw()
  5362. {
  5363. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5364. // avoids getting warning messages about the parameter being unused
  5365. const ScopedLockType lock (getLock());
  5366. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  5367. }
  5368. /** Finds the index of an object in the array, assuming that the array is sorted.
  5369. This will use a comparator to do a binary-chop to find the index of the given
  5370. element, if it exists. If the array isn't sorted, the behaviour of this
  5371. method will be unpredictable.
  5372. @param comparator the comparator to use to compare the elements - see the sort()
  5373. method for details about the form this object should take
  5374. @param objectToLookFor the object to search for
  5375. @returns the index of the element, or -1 if it's not found
  5376. @see addSorted, sort
  5377. */
  5378. template <class ElementComparator>
  5379. int indexOfSorted (ElementComparator& comparator,
  5380. const ObjectClass* const objectToLookFor) const throw()
  5381. {
  5382. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5383. // avoids getting warning messages about the parameter being unused
  5384. const ScopedLockType lock (getLock());
  5385. int start = 0;
  5386. int end = numUsed;
  5387. for (;;)
  5388. {
  5389. if (start >= end)
  5390. {
  5391. return -1;
  5392. }
  5393. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  5394. {
  5395. return start;
  5396. }
  5397. else
  5398. {
  5399. const int halfway = (start + end) >> 1;
  5400. if (halfway == start)
  5401. return -1;
  5402. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  5403. start = halfway;
  5404. else
  5405. end = halfway;
  5406. }
  5407. }
  5408. }
  5409. /** Removes an object from the array.
  5410. This will remove the object at a given index (optionally also
  5411. deleting it) and move back all the subsequent objects to close the gap.
  5412. If the index passed in is out-of-range, nothing will happen.
  5413. @param indexToRemove the index of the element to remove
  5414. @param deleteObject whether to delete the object that is removed
  5415. @see removeObject, removeRange
  5416. */
  5417. void remove (const int indexToRemove,
  5418. const bool deleteObject = true)
  5419. {
  5420. ScopedPointer <ObjectClass> toDelete;
  5421. const ScopedLockType lock (getLock());
  5422. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5423. {
  5424. ObjectClass** const e = data.elements + indexToRemove;
  5425. if (deleteObject)
  5426. toDelete = *e;
  5427. --numUsed;
  5428. const int numToShift = numUsed - indexToRemove;
  5429. if (numToShift > 0)
  5430. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5431. if ((numUsed << 1) < data.numAllocated)
  5432. minimiseStorageOverheads();
  5433. }
  5434. }
  5435. /** Removes and returns an object from the array without deleting it.
  5436. This will remove the object at a given index and return it, moving back all
  5437. the subsequent objects to close the gap. If the index passed in is out-of-range,
  5438. nothing will happen.
  5439. @param indexToRemove the index of the element to remove
  5440. @see remove, removeObject, removeRange
  5441. */
  5442. ObjectClass* removeAndReturn (const int indexToRemove)
  5443. {
  5444. ObjectClass* removedItem = 0;
  5445. const ScopedLockType lock (getLock());
  5446. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5447. {
  5448. ObjectClass** const e = data.elements + indexToRemove;
  5449. removedItem = *e;
  5450. --numUsed;
  5451. const int numToShift = numUsed - indexToRemove;
  5452. if (numToShift > 0)
  5453. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5454. if ((numUsed << 1) < data.numAllocated)
  5455. minimiseStorageOverheads();
  5456. }
  5457. return removedItem;
  5458. }
  5459. /** Removes a specified object from the array.
  5460. If the item isn't found, no action is taken.
  5461. @param objectToRemove the object to try to remove
  5462. @param deleteObject whether to delete the object (if it's found)
  5463. @see remove, removeRange
  5464. */
  5465. void removeObject (const ObjectClass* const objectToRemove,
  5466. const bool deleteObject = true)
  5467. {
  5468. const ScopedLockType lock (getLock());
  5469. ObjectClass** e = data.elements.getData();
  5470. for (int i = numUsed; --i >= 0;)
  5471. {
  5472. if (objectToRemove == *e)
  5473. {
  5474. remove (static_cast <int> (e - data.elements.getData()), deleteObject);
  5475. break;
  5476. }
  5477. ++e;
  5478. }
  5479. }
  5480. /** Removes a range of objects from the array.
  5481. This will remove a set of objects, starting from the given index,
  5482. and move any subsequent elements down to close the gap.
  5483. If the range extends beyond the bounds of the array, it will
  5484. be safely clipped to the size of the array.
  5485. @param startIndex the index of the first object to remove
  5486. @param numberToRemove how many objects should be removed
  5487. @param deleteObjects whether to delete the objects that get removed
  5488. @see remove, removeObject
  5489. */
  5490. void removeRange (int startIndex,
  5491. const int numberToRemove,
  5492. const bool deleteObjects = true)
  5493. {
  5494. const ScopedLockType lock (getLock());
  5495. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5496. startIndex = jlimit (0, numUsed, startIndex);
  5497. if (endIndex > startIndex)
  5498. {
  5499. if (deleteObjects)
  5500. {
  5501. for (int i = startIndex; i < endIndex; ++i)
  5502. {
  5503. delete data.elements [i];
  5504. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  5505. }
  5506. }
  5507. const int rangeSize = endIndex - startIndex;
  5508. ObjectClass** e = data.elements + startIndex;
  5509. int numToShift = numUsed - endIndex;
  5510. numUsed -= rangeSize;
  5511. while (--numToShift >= 0)
  5512. {
  5513. *e = e [rangeSize];
  5514. ++e;
  5515. }
  5516. if ((numUsed << 1) < data.numAllocated)
  5517. minimiseStorageOverheads();
  5518. }
  5519. }
  5520. /** Removes the last n objects from the array.
  5521. @param howManyToRemove how many objects to remove from the end of the array
  5522. @param deleteObjects whether to also delete the objects that are removed
  5523. @see remove, removeObject, removeRange
  5524. */
  5525. void removeLast (int howManyToRemove = 1,
  5526. const bool deleteObjects = true)
  5527. {
  5528. const ScopedLockType lock (getLock());
  5529. if (howManyToRemove >= numUsed)
  5530. clear (deleteObjects);
  5531. else
  5532. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  5533. }
  5534. /** Swaps a pair of objects in the array.
  5535. If either of the indexes passed in is out-of-range, nothing will happen,
  5536. otherwise the two objects at these positions will be exchanged.
  5537. */
  5538. void swap (const int index1,
  5539. const int index2) throw()
  5540. {
  5541. const ScopedLockType lock (getLock());
  5542. if (((unsigned int) index1) < (unsigned int) numUsed
  5543. && ((unsigned int) index2) < (unsigned int) numUsed)
  5544. {
  5545. swapVariables (data.elements [index1],
  5546. data.elements [index2]);
  5547. }
  5548. }
  5549. /** Moves one of the objects to a different position.
  5550. This will move the object to a specified index, shuffling along
  5551. any intervening elements as required.
  5552. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5553. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5554. @param currentIndex the index of the object to be moved. If this isn't a
  5555. valid index, then nothing will be done
  5556. @param newIndex the index at which you'd like this object to end up. If this
  5557. is less than zero, it will be moved to the end of the array
  5558. */
  5559. void move (const int currentIndex,
  5560. int newIndex) throw()
  5561. {
  5562. if (currentIndex != newIndex)
  5563. {
  5564. const ScopedLockType lock (getLock());
  5565. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  5566. {
  5567. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  5568. newIndex = numUsed - 1;
  5569. ObjectClass* const value = data.elements [currentIndex];
  5570. if (newIndex > currentIndex)
  5571. {
  5572. memmove (data.elements + currentIndex,
  5573. data.elements + currentIndex + 1,
  5574. (newIndex - currentIndex) * sizeof (ObjectClass*));
  5575. }
  5576. else
  5577. {
  5578. memmove (data.elements + newIndex + 1,
  5579. data.elements + newIndex,
  5580. (currentIndex - newIndex) * sizeof (ObjectClass*));
  5581. }
  5582. data.elements [newIndex] = value;
  5583. }
  5584. }
  5585. }
  5586. /** This swaps the contents of this array with those of another array.
  5587. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5588. because it just swaps their internal pointers.
  5589. */
  5590. void swapWithArray (OwnedArray& otherArray) throw()
  5591. {
  5592. const ScopedLockType lock1 (getLock());
  5593. const ScopedLockType lock2 (otherArray.getLock());
  5594. data.swapWith (otherArray.data);
  5595. swapVariables (numUsed, otherArray.numUsed);
  5596. }
  5597. /** Reduces the amount of storage being used by the array.
  5598. Arrays typically allocate slightly more storage than they need, and after
  5599. removing elements, they may have quite a lot of unused space allocated.
  5600. This method will reduce the amount of allocated storage to a minimum.
  5601. */
  5602. void minimiseStorageOverheads() throw()
  5603. {
  5604. const ScopedLockType lock (getLock());
  5605. data.shrinkToNoMoreThan (numUsed);
  5606. }
  5607. /** Increases the array's internal storage to hold a minimum number of elements.
  5608. Calling this before adding a large known number of elements means that
  5609. the array won't have to keep dynamically resizing itself as the elements
  5610. are added, and it'll therefore be more efficient.
  5611. */
  5612. void ensureStorageAllocated (const int minNumElements) throw()
  5613. {
  5614. const ScopedLockType lock (getLock());
  5615. data.ensureAllocatedSize (minNumElements);
  5616. }
  5617. /** Sorts the elements in the array.
  5618. This will use a comparator object to sort the elements into order. The object
  5619. passed must have a method of the form:
  5620. @code
  5621. int compareElements (ElementType first, ElementType second);
  5622. @endcode
  5623. ..and this method must return:
  5624. - a value of < 0 if the first comes before the second
  5625. - a value of 0 if the two objects are equivalent
  5626. - a value of > 0 if the second comes before the first
  5627. To improve performance, the compareElements() method can be declared as static or const.
  5628. @param comparator the comparator to use for comparing elements.
  5629. @param retainOrderOfEquivalentItems if this is true, then items
  5630. which the comparator says are equivalent will be
  5631. kept in the order in which they currently appear
  5632. in the array. This is slower to perform, but may
  5633. be important in some cases. If it's false, a faster
  5634. algorithm is used, but equivalent elements may be
  5635. rearranged.
  5636. @see sortArray, indexOfSorted
  5637. */
  5638. template <class ElementComparator>
  5639. void sort (ElementComparator& comparator,
  5640. const bool retainOrderOfEquivalentItems = false) const throw()
  5641. {
  5642. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5643. // avoids getting warning messages about the parameter being unused
  5644. const ScopedLockType lock (getLock());
  5645. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  5646. }
  5647. /** Returns the CriticalSection that locks this array.
  5648. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  5649. an object of ScopedLockType as an RAII lock for it.
  5650. */
  5651. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  5652. /** Returns the type of scoped lock to use for locking this array */
  5653. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  5654. juce_UseDebuggingNewOperator
  5655. private:
  5656. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  5657. int numUsed;
  5658. // disallow copy constructor and assignment
  5659. OwnedArray (const OwnedArray&);
  5660. OwnedArray& operator= (const OwnedArray&);
  5661. };
  5662. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  5663. /*** End of inlined file: juce_OwnedArray.h ***/
  5664. #endif
  5665. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5666. /*** Start of inlined file: juce_PropertySet.h ***/
  5667. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5668. #define __JUCE_PROPERTYSET_JUCEHEADER__
  5669. /*** Start of inlined file: juce_StringPairArray.h ***/
  5670. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5671. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5672. /*** Start of inlined file: juce_StringArray.h ***/
  5673. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  5674. #define __JUCE_STRINGARRAY_JUCEHEADER__
  5675. /**
  5676. A special array for holding a list of strings.
  5677. @see String, StringPairArray
  5678. */
  5679. class JUCE_API StringArray
  5680. {
  5681. public:
  5682. /** Creates an empty string array */
  5683. StringArray() throw();
  5684. /** Creates a copy of another string array */
  5685. StringArray (const StringArray& other);
  5686. /** Creates an array containing a single string. */
  5687. explicit StringArray (const String& firstValue);
  5688. /** Creates a copy of an array of string literals.
  5689. @param strings an array of strings to add. Null pointers in the array will be
  5690. treated as empty strings
  5691. @param numberOfStrings how many items there are in the array
  5692. */
  5693. StringArray (const juce_wchar* const* strings, int numberOfStrings);
  5694. /** Creates a copy of an array of string literals.
  5695. @param strings an array of strings to add. Null pointers in the array will be
  5696. treated as empty strings
  5697. @param numberOfStrings how many items there are in the array
  5698. */
  5699. StringArray (const char* const* strings, int numberOfStrings);
  5700. /** Creates a copy of a null-terminated array of string literals.
  5701. Each item from the array passed-in is added, until it encounters a null pointer,
  5702. at which point it stops.
  5703. */
  5704. explicit StringArray (const juce_wchar* const* strings);
  5705. /** Creates a copy of a null-terminated array of string literals.
  5706. Each item from the array passed-in is added, until it encounters a null pointer,
  5707. at which point it stops.
  5708. */
  5709. explicit StringArray (const char* const* strings);
  5710. /** Destructor. */
  5711. ~StringArray();
  5712. /** Copies the contents of another string array into this one */
  5713. StringArray& operator= (const StringArray& other);
  5714. /** Compares two arrays.
  5715. Comparisons are case-sensitive.
  5716. @returns true only if the other array contains exactly the same strings in the same order
  5717. */
  5718. bool operator== (const StringArray& other) const throw();
  5719. /** Compares two arrays.
  5720. Comparisons are case-sensitive.
  5721. @returns false if the other array contains exactly the same strings in the same order
  5722. */
  5723. bool operator!= (const StringArray& other) const throw();
  5724. /** Returns the number of strings in the array */
  5725. inline int size() const throw() { return strings.size(); };
  5726. /** Returns one of the strings from the array.
  5727. If the index is out-of-range, an empty string is returned.
  5728. Obviously the reference returned shouldn't be stored for later use, as the
  5729. string it refers to may disappear when the array changes.
  5730. */
  5731. const String& operator[] (int index) const throw();
  5732. /** Returns a reference to one of the strings in the array.
  5733. This lets you modify a string in-place in the array, but you must be sure that
  5734. the index is in-range.
  5735. */
  5736. String& getReference (int index) throw();
  5737. /** Searches for a string in the array.
  5738. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5739. @returns true if the string is found inside the array
  5740. */
  5741. bool contains (const String& stringToLookFor,
  5742. bool ignoreCase = false) const;
  5743. /** Searches for a string in the array.
  5744. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5745. @param stringToLookFor the string to try to find
  5746. @param ignoreCase whether the comparison should be case-insensitive
  5747. @param startIndex the first index to start searching from
  5748. @returns the index of the first occurrence of the string in this array,
  5749. or -1 if it isn't found.
  5750. */
  5751. int indexOf (const String& stringToLookFor,
  5752. bool ignoreCase = false,
  5753. int startIndex = 0) const;
  5754. /** Appends a string at the end of the array. */
  5755. void add (const String& stringToAdd);
  5756. /** Inserts a string into the array.
  5757. This will insert a string into the array at the given index, moving
  5758. up the other elements to make room for it.
  5759. If the index is less than zero or greater than the size of the array,
  5760. the new string will be added to the end of the array.
  5761. */
  5762. void insert (int index, const String& stringToAdd);
  5763. /** Adds a string to the array as long as it's not already in there.
  5764. The search can optionally be case-insensitive.
  5765. */
  5766. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  5767. /** Replaces one of the strings in the array with another one.
  5768. If the index is higher than the array's size, the new string will be
  5769. added to the end of the array; if it's less than zero nothing happens.
  5770. */
  5771. void set (int index, const String& newString);
  5772. /** Appends some strings from another array to the end of this one.
  5773. @param other the array to add
  5774. @param startIndex the first element of the other array to add
  5775. @param numElementsToAdd the maximum number of elements to add (if this is
  5776. less than zero, they are all added)
  5777. */
  5778. void addArray (const StringArray& other,
  5779. int startIndex = 0,
  5780. int numElementsToAdd = -1);
  5781. /** Breaks up a string into tokens and adds them to this array.
  5782. This will tokenise the given string using whitespace characters as the
  5783. token delimiters, and will add these tokens to the end of the array.
  5784. @returns the number of tokens added
  5785. */
  5786. int addTokens (const String& stringToTokenise,
  5787. bool preserveQuotedStrings);
  5788. /** Breaks up a string into tokens and adds them to this array.
  5789. This will tokenise the given string (using the string passed in to define the
  5790. token delimiters), and will add these tokens to the end of the array.
  5791. @param stringToTokenise the string to tokenise
  5792. @param breakCharacters a string of characters, any of which will be considered
  5793. to be a token delimiter.
  5794. @param quoteCharacters if this string isn't empty, it defines a set of characters
  5795. which are treated as quotes. Any text occurring
  5796. between quotes is not broken up into tokens.
  5797. @returns the number of tokens added
  5798. */
  5799. int addTokens (const String& stringToTokenise,
  5800. const String& breakCharacters,
  5801. const String& quoteCharacters);
  5802. /** Breaks up a string into lines and adds them to this array.
  5803. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  5804. to the array. Line-break characters are omitted from the strings that are added to
  5805. the array.
  5806. */
  5807. int addLines (const String& stringToBreakUp);
  5808. /** Removes all elements from the array. */
  5809. void clear();
  5810. /** Removes a string from the array.
  5811. If the index is out-of-range, no action will be taken.
  5812. */
  5813. void remove (int index);
  5814. /** Finds a string in the array and removes it.
  5815. This will remove the first occurrence of the given string from the array. The
  5816. comparison may be case-insensitive depending on the ignoreCase parameter.
  5817. */
  5818. void removeString (const String& stringToRemove,
  5819. bool ignoreCase = false);
  5820. /** Removes a range of elements from the array.
  5821. This will remove a set of elements, starting from the given index,
  5822. and move subsequent elements down to close the gap.
  5823. If the range extends beyond the bounds of the array, it will
  5824. be safely clipped to the size of the array.
  5825. @param startIndex the index of the first element to remove
  5826. @param numberToRemove how many elements should be removed
  5827. */
  5828. void removeRange (int startIndex, int numberToRemove);
  5829. /** Removes any duplicated elements from the array.
  5830. If any string appears in the array more than once, only the first occurrence of
  5831. it will be retained.
  5832. @param ignoreCase whether to use a case-insensitive comparison
  5833. */
  5834. void removeDuplicates (bool ignoreCase);
  5835. /** Removes empty strings from the array.
  5836. @param removeWhitespaceStrings if true, strings that only contain whitespace
  5837. characters will also be removed
  5838. */
  5839. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  5840. /** Moves one of the strings to a different position.
  5841. This will move the string to a specified index, shuffling along
  5842. any intervening elements as required.
  5843. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5844. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5845. @param currentIndex the index of the value to be moved. If this isn't a
  5846. valid index, then nothing will be done
  5847. @param newIndex the index at which you'd like this value to end up. If this
  5848. is less than zero, the value will be moved to the end
  5849. of the array
  5850. */
  5851. void move (int currentIndex, int newIndex) throw();
  5852. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  5853. void trim();
  5854. /** Adds numbers to the strings in the array, to make each string unique.
  5855. This will add numbers to the ends of groups of similar strings.
  5856. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  5857. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  5858. @param appendNumberToFirstInstance whether the first of a group of similar strings
  5859. also has a number appended to it.
  5860. @param preNumberString when adding a number, this string is added before the number.
  5861. If you pass 0, a default string will be used, which adds
  5862. brackets around the number.
  5863. @param postNumberString this string is appended after any numbers that are added.
  5864. If you pass 0, a default string will be used, which adds
  5865. brackets around the number.
  5866. */
  5867. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  5868. bool appendNumberToFirstInstance,
  5869. const juce_wchar* preNumberString = 0,
  5870. const juce_wchar* postNumberString = 0);
  5871. /** Joins the strings in the array together into one string.
  5872. This will join a range of elements from the array into a string, separating
  5873. them with a given string.
  5874. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  5875. @param separatorString the string to insert between all the strings
  5876. @param startIndex the first element to join
  5877. @param numberOfElements how many elements to join together. If this is less
  5878. than zero, all available elements will be used.
  5879. */
  5880. const String joinIntoString (const String& separatorString,
  5881. int startIndex = 0,
  5882. int numberOfElements = -1) const;
  5883. /** Sorts the array into alphabetical order.
  5884. @param ignoreCase if true, the comparisons used will be case-sensitive.
  5885. */
  5886. void sort (bool ignoreCase);
  5887. /** Reduces the amount of storage being used by the array.
  5888. Arrays typically allocate slightly more storage than they need, and after
  5889. removing elements, they may have quite a lot of unused space allocated.
  5890. This method will reduce the amount of allocated storage to a minimum.
  5891. */
  5892. void minimiseStorageOverheads();
  5893. juce_UseDebuggingNewOperator
  5894. private:
  5895. Array <String> strings;
  5896. };
  5897. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  5898. /*** End of inlined file: juce_StringArray.h ***/
  5899. /**
  5900. A container for holding a set of strings which are keyed by another string.
  5901. @see StringArray
  5902. */
  5903. class JUCE_API StringPairArray
  5904. {
  5905. public:
  5906. /** Creates an empty array */
  5907. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  5908. /** Creates a copy of another array */
  5909. StringPairArray (const StringPairArray& other);
  5910. /** Destructor. */
  5911. ~StringPairArray();
  5912. /** Copies the contents of another string array into this one */
  5913. StringPairArray& operator= (const StringPairArray& other);
  5914. /** Compares two arrays.
  5915. Comparisons are case-sensitive.
  5916. @returns true only if the other array contains exactly the same strings with the same keys
  5917. */
  5918. bool operator== (const StringPairArray& other) const;
  5919. /** Compares two arrays.
  5920. Comparisons are case-sensitive.
  5921. @returns false if the other array contains exactly the same strings with the same keys
  5922. */
  5923. bool operator!= (const StringPairArray& other) const;
  5924. /** Finds the value corresponding to a key string.
  5925. If no such key is found, this will just return an empty string. To check whether
  5926. a given key actually exists (because it might actually be paired with an empty string), use
  5927. the getAllKeys() method to obtain a list.
  5928. Obviously the reference returned shouldn't be stored for later use, as the
  5929. string it refers to may disappear when the array changes.
  5930. @see getValue
  5931. */
  5932. const String& operator[] (const String& key) const;
  5933. /** Finds the value corresponding to a key string.
  5934. If no such key is found, this will just return the value provided as a default.
  5935. @see operator[]
  5936. */
  5937. const String getValue (const String& key, const String& defaultReturnValue) const;
  5938. /** Returns a list of all keys in the array. */
  5939. const StringArray& getAllKeys() const throw() { return keys; }
  5940. /** Returns a list of all values in the array. */
  5941. const StringArray& getAllValues() const throw() { return values; }
  5942. /** Returns the number of strings in the array */
  5943. inline int size() const throw() { return keys.size(); };
  5944. /** Adds or amends a key/value pair.
  5945. If a value already exists with this key, its value will be overwritten,
  5946. otherwise the key/value pair will be added to the array.
  5947. */
  5948. void set (const String& key, const String& value);
  5949. /** Adds the items from another array to this one.
  5950. This is equivalent to using set() to add each of the pairs from the other array.
  5951. */
  5952. void addArray (const StringPairArray& other);
  5953. /** Removes all elements from the array. */
  5954. void clear();
  5955. /** Removes a string from the array based on its key.
  5956. If the key isn't found, nothing will happen.
  5957. */
  5958. void remove (const String& key);
  5959. /** Removes a string from the array based on its index.
  5960. If the index is out-of-range, no action will be taken.
  5961. */
  5962. void remove (int index);
  5963. /** Indicates whether to use a case-insensitive search when looking up a key string.
  5964. */
  5965. void setIgnoresCase (bool shouldIgnoreCase);
  5966. /** Returns a descriptive string containing the items.
  5967. This is handy for dumping the contents of an array.
  5968. */
  5969. const String getDescription() const;
  5970. /** Reduces the amount of storage being used by the array.
  5971. Arrays typically allocate slightly more storage than they need, and after
  5972. removing elements, they may have quite a lot of unused space allocated.
  5973. This method will reduce the amount of allocated storage to a minimum.
  5974. */
  5975. void minimiseStorageOverheads();
  5976. juce_UseDebuggingNewOperator
  5977. private:
  5978. StringArray keys, values;
  5979. bool ignoreCase;
  5980. };
  5981. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5982. /*** End of inlined file: juce_StringPairArray.h ***/
  5983. /*** Start of inlined file: juce_XmlElement.h ***/
  5984. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  5985. #define __JUCE_XMLELEMENT_JUCEHEADER__
  5986. /*** Start of inlined file: juce_File.h ***/
  5987. #ifndef __JUCE_FILE_JUCEHEADER__
  5988. #define __JUCE_FILE_JUCEHEADER__
  5989. /*** Start of inlined file: juce_Time.h ***/
  5990. #ifndef __JUCE_TIME_JUCEHEADER__
  5991. #define __JUCE_TIME_JUCEHEADER__
  5992. /*** Start of inlined file: juce_RelativeTime.h ***/
  5993. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5994. #define __JUCE_RELATIVETIME_JUCEHEADER__
  5995. /** A relative measure of time.
  5996. The time is stored as a number of seconds, at double-precision floating
  5997. point accuracy, and may be positive or negative.
  5998. If you need an absolute time, (i.e. a date + time), see the Time class.
  5999. */
  6000. class JUCE_API RelativeTime
  6001. {
  6002. public:
  6003. /** Creates a RelativeTime.
  6004. @param seconds the number of seconds, which may be +ve or -ve.
  6005. @see milliseconds, minutes, hours, days, weeks
  6006. */
  6007. explicit RelativeTime (double seconds = 0.0) throw();
  6008. /** Copies another relative time. */
  6009. RelativeTime (const RelativeTime& other) throw();
  6010. /** Copies another relative time. */
  6011. RelativeTime& operator= (const RelativeTime& other) throw();
  6012. /** Destructor. */
  6013. ~RelativeTime() throw();
  6014. /** Creates a new RelativeTime object representing a number of milliseconds.
  6015. @see minutes, hours, days, weeks
  6016. */
  6017. static const RelativeTime milliseconds (int milliseconds) throw();
  6018. /** Creates a new RelativeTime object representing a number of milliseconds.
  6019. @see minutes, hours, days, weeks
  6020. */
  6021. static const RelativeTime milliseconds (int64 milliseconds) throw();
  6022. /** Creates a new RelativeTime object representing a number of minutes.
  6023. @see milliseconds, hours, days, weeks
  6024. */
  6025. static const RelativeTime minutes (double numberOfMinutes) throw();
  6026. /** Creates a new RelativeTime object representing a number of hours.
  6027. @see milliseconds, minutes, days, weeks
  6028. */
  6029. static const RelativeTime hours (double numberOfHours) throw();
  6030. /** Creates a new RelativeTime object representing a number of days.
  6031. @see milliseconds, minutes, hours, weeks
  6032. */
  6033. static const RelativeTime days (double numberOfDays) throw();
  6034. /** Creates a new RelativeTime object representing a number of weeks.
  6035. @see milliseconds, minutes, hours, days
  6036. */
  6037. static const RelativeTime weeks (double numberOfWeeks) throw();
  6038. /** Returns the number of milliseconds this time represents.
  6039. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6040. */
  6041. int64 inMilliseconds() const throw();
  6042. /** Returns the number of seconds this time represents.
  6043. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  6044. */
  6045. double inSeconds() const throw() { return seconds; }
  6046. /** Returns the number of minutes this time represents.
  6047. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  6048. */
  6049. double inMinutes() const throw();
  6050. /** Returns the number of hours this time represents.
  6051. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  6052. */
  6053. double inHours() const throw();
  6054. /** Returns the number of days this time represents.
  6055. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  6056. */
  6057. double inDays() const throw();
  6058. /** Returns the number of weeks this time represents.
  6059. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  6060. */
  6061. double inWeeks() const throw();
  6062. /** Returns a readable textual description of the time.
  6063. The exact format of the string returned will depend on
  6064. the magnitude of the time - e.g.
  6065. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  6066. so that only the two most significant units are printed.
  6067. The returnValueForZeroTime value is the result that is returned if the
  6068. length is zero. Depending on your application you might want to use this
  6069. to return something more relevant like "empty" or "0 secs", etc.
  6070. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6071. */
  6072. const String getDescription (const String& returnValueForZeroTime = "0") const throw();
  6073. /** Compares two RelativeTimes. */
  6074. bool operator== (const RelativeTime& other) const throw();
  6075. /** Compares two RelativeTimes. */
  6076. bool operator!= (const RelativeTime& other) const throw();
  6077. /** Compares two RelativeTimes. */
  6078. bool operator> (const RelativeTime& other) const throw();
  6079. /** Compares two RelativeTimes. */
  6080. bool operator< (const RelativeTime& other) const throw();
  6081. /** Compares two RelativeTimes. */
  6082. bool operator>= (const RelativeTime& other) const throw();
  6083. /** Compares two RelativeTimes. */
  6084. bool operator<= (const RelativeTime& other) const throw();
  6085. /** Adds another RelativeTime to this one and returns the result. */
  6086. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  6087. /** Subtracts another RelativeTime from this one and returns the result. */
  6088. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  6089. /** Adds a number of seconds to this RelativeTime and returns the result. */
  6090. const RelativeTime operator+ (double secondsToAdd) const throw();
  6091. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  6092. const RelativeTime operator- (double secondsToSubtract) const throw();
  6093. /** Adds another RelativeTime to this one. */
  6094. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  6095. /** Subtracts another RelativeTime from this one. */
  6096. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  6097. /** Adds a number of seconds to this time. */
  6098. const RelativeTime& operator+= (double secondsToAdd) throw();
  6099. /** Subtracts a number of seconds from this time. */
  6100. const RelativeTime& operator-= (double secondsToSubtract) throw();
  6101. juce_UseDebuggingNewOperator
  6102. private:
  6103. double seconds;
  6104. };
  6105. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  6106. /*** End of inlined file: juce_RelativeTime.h ***/
  6107. /**
  6108. Holds an absolute date and time.
  6109. Internally, the time is stored at millisecond precision.
  6110. @see RelativeTime
  6111. */
  6112. class JUCE_API Time
  6113. {
  6114. public:
  6115. /** Creates a Time object.
  6116. This default constructor creates a time of 1st January 1970, (which is
  6117. represented internally as 0ms).
  6118. To create a time object representing the current time, use getCurrentTime().
  6119. @see getCurrentTime
  6120. */
  6121. Time() throw();
  6122. /** Creates a copy of another Time object. */
  6123. Time (const Time& other) throw();
  6124. /** Creates a time based on a number of milliseconds.
  6125. The internal millisecond count is set to 0 (1st January 1970). To create a
  6126. time object set to the current time, use getCurrentTime().
  6127. @param millisecondsSinceEpoch the number of milliseconds since the unix
  6128. 'epoch' (midnight Jan 1st 1970).
  6129. @see getCurrentTime, currentTimeMillis
  6130. */
  6131. Time (int64 millisecondsSinceEpoch) throw();
  6132. /** Creates a time from a set of date components.
  6133. The timezone is assumed to be whatever the system is using as its locale.
  6134. @param year the year, in 4-digit format, e.g. 2004
  6135. @param month the month, in the range 0 to 11
  6136. @param day the day of the month, in the range 1 to 31
  6137. @param hours hours in 24-hour clock format, 0 to 23
  6138. @param minutes minutes 0 to 59
  6139. @param seconds seconds 0 to 59
  6140. @param milliseconds milliseconds 0 to 999
  6141. @param useLocalTime if true, encode using the current machine's local time; if
  6142. false, it will always work in GMT.
  6143. */
  6144. Time (int year,
  6145. int month,
  6146. int day,
  6147. int hours,
  6148. int minutes,
  6149. int seconds = 0,
  6150. int milliseconds = 0,
  6151. bool useLocalTime = true) throw();
  6152. /** Destructor. */
  6153. ~Time() throw();
  6154. /** Copies this time from another one. */
  6155. Time& operator= (const Time& other) throw();
  6156. /** Returns a Time object that is set to the current system time.
  6157. @see currentTimeMillis
  6158. */
  6159. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  6160. /** Returns the time as a number of milliseconds.
  6161. @returns the number of milliseconds this Time object represents, since
  6162. midnight jan 1st 1970.
  6163. @see getMilliseconds
  6164. */
  6165. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  6166. /** Returns the year.
  6167. A 4-digit format is used, e.g. 2004.
  6168. */
  6169. int getYear() const throw();
  6170. /** Returns the number of the month.
  6171. The value returned is in the range 0 to 11.
  6172. @see getMonthName
  6173. */
  6174. int getMonth() const throw();
  6175. /** Returns the name of the month.
  6176. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6177. it'll return the long form, e.g. "January"
  6178. @see getMonth
  6179. */
  6180. const String getMonthName (bool threeLetterVersion) const throw();
  6181. /** Returns the day of the month.
  6182. The value returned is in the range 1 to 31.
  6183. */
  6184. int getDayOfMonth() const throw();
  6185. /** Returns the number of the day of the week.
  6186. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  6187. */
  6188. int getDayOfWeek() const throw();
  6189. /** Returns the name of the weekday.
  6190. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6191. false, it'll return the full version, e.g. "Tuesday".
  6192. */
  6193. const String getWeekdayName (bool threeLetterVersion) const throw();
  6194. /** Returns the number of hours since midnight.
  6195. This is in 24-hour clock format, in the range 0 to 23.
  6196. @see getHoursInAmPmFormat, isAfternoon
  6197. */
  6198. int getHours() const throw();
  6199. /** Returns true if the time is in the afternoon.
  6200. So it returns true for "PM", false for "AM".
  6201. @see getHoursInAmPmFormat, getHours
  6202. */
  6203. bool isAfternoon() const throw();
  6204. /** Returns the hours in 12-hour clock format.
  6205. This will return a value 1 to 12 - use isAfternoon() to find out
  6206. whether this is in the afternoon or morning.
  6207. @see getHours, isAfternoon
  6208. */
  6209. int getHoursInAmPmFormat() const throw();
  6210. /** Returns the number of minutes, 0 to 59. */
  6211. int getMinutes() const throw();
  6212. /** Returns the number of seconds, 0 to 59. */
  6213. int getSeconds() const throw();
  6214. /** Returns the number of milliseconds, 0 to 999.
  6215. Unlike toMilliseconds(), this just returns the position within the
  6216. current second rather than the total number since the epoch.
  6217. @see toMilliseconds
  6218. */
  6219. int getMilliseconds() const throw();
  6220. /** Returns true if the local timezone uses a daylight saving correction. */
  6221. bool isDaylightSavingTime() const throw();
  6222. /** Returns a 3-character string to indicate the local timezone. */
  6223. const String getTimeZone() const throw();
  6224. /** Quick way of getting a string version of a date and time.
  6225. For a more powerful way of formatting the date and time, see the formatted() method.
  6226. @param includeDate whether to include the date in the string
  6227. @param includeTime whether to include the time in the string
  6228. @param includeSeconds if the time is being included, this provides an option not to include
  6229. the seconds in it
  6230. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  6231. hour notation.
  6232. @see formatted
  6233. */
  6234. const String toString (bool includeDate,
  6235. bool includeTime,
  6236. bool includeSeconds = true,
  6237. bool use24HourClock = false) const throw();
  6238. /** Converts this date/time to a string with a user-defined format.
  6239. This uses the C strftime() function to format this time as a string. To save you
  6240. looking it up, these are the escape codes that strftime uses (other codes might
  6241. work on some platforms and not others, but these are the common ones):
  6242. %a is replaced by the locale's abbreviated weekday name.
  6243. %A is replaced by the locale's full weekday name.
  6244. %b is replaced by the locale's abbreviated month name.
  6245. %B is replaced by the locale's full month name.
  6246. %c is replaced by the locale's appropriate date and time representation.
  6247. %d is replaced by the day of the month as a decimal number [01,31].
  6248. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  6249. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  6250. %j is replaced by the day of the year as a decimal number [001,366].
  6251. %m is replaced by the month as a decimal number [01,12].
  6252. %M is replaced by the minute as a decimal number [00,59].
  6253. %p is replaced by the locale's equivalent of either a.m. or p.m.
  6254. %S is replaced by the second as a decimal number [00,61].
  6255. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  6256. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  6257. %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.
  6258. %x is replaced by the locale's appropriate date representation.
  6259. %X is replaced by the locale's appropriate time representation.
  6260. %y is replaced by the year without century as a decimal number [00,99].
  6261. %Y is replaced by the year with century as a decimal number.
  6262. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  6263. %% is replaced by %.
  6264. @see toString
  6265. */
  6266. const String formatted (const String& format) const throw();
  6267. /** Adds a RelativeTime to this time and returns the result. */
  6268. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  6269. /** Subtracts a RelativeTime from this time and returns the result. */
  6270. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  6271. /** Returns the relative time difference between this time and another one. */
  6272. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  6273. /** Compares two Time objects. */
  6274. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  6275. /** Compares two Time objects. */
  6276. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  6277. /** Compares two Time objects. */
  6278. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  6279. /** Compares two Time objects. */
  6280. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  6281. /** Compares two Time objects. */
  6282. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  6283. /** Compares two Time objects. */
  6284. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  6285. /** Tries to set the computer's clock.
  6286. @returns true if this succeeds, although depending on the system, the
  6287. application might not have sufficient privileges to do this.
  6288. */
  6289. bool setSystemTimeToThisTime() const;
  6290. /** Returns the name of a day of the week.
  6291. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  6292. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6293. false, it'll return the full version, e.g. "Tuesday".
  6294. */
  6295. static const String getWeekdayName (int dayNumber,
  6296. bool threeLetterVersion) throw();
  6297. /** Returns the name of one of the months.
  6298. @param monthNumber the month, 0 to 11
  6299. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6300. it'll return the long form, e.g. "January"
  6301. */
  6302. static const String getMonthName (int monthNumber,
  6303. bool threeLetterVersion) throw();
  6304. // Static methods for getting system timers directly..
  6305. /** Returns the current system time.
  6306. Returns the number of milliseconds since midnight jan 1st 1970.
  6307. Should be accurate to within a few millisecs, depending on platform,
  6308. hardware, etc.
  6309. */
  6310. static int64 currentTimeMillis() throw();
  6311. /** Returns the number of millisecs since system startup.
  6312. Should be accurate to within a few millisecs, depending on platform,
  6313. hardware, etc.
  6314. @see getApproximateMillisecondCounter
  6315. */
  6316. static uint32 getMillisecondCounter() throw();
  6317. /** Returns the number of millisecs since system startup.
  6318. Same as getMillisecondCounter(), but returns a more accurate value, using
  6319. the high-res timer.
  6320. @see getMillisecondCounter
  6321. */
  6322. static double getMillisecondCounterHiRes() throw();
  6323. /** Waits until the getMillisecondCounter() reaches a given value.
  6324. This will make the thread sleep as efficiently as it can while it's waiting.
  6325. */
  6326. static void waitForMillisecondCounter (uint32 targetTime) throw();
  6327. /** Less-accurate but faster version of getMillisecondCounter().
  6328. This will return the last value that getMillisecondCounter() returned, so doesn't
  6329. need to make a system call, but is less accurate - it shouldn't be more than
  6330. 100ms away from the correct time, though, so is still accurate enough for a
  6331. lot of purposes.
  6332. @see getMillisecondCounter
  6333. */
  6334. static uint32 getApproximateMillisecondCounter() throw();
  6335. // High-resolution timers..
  6336. /** Returns the current high-resolution counter's tick-count.
  6337. This is a similar idea to getMillisecondCounter(), but with a higher
  6338. resolution.
  6339. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  6340. secondsToHighResolutionTicks
  6341. */
  6342. static int64 getHighResolutionTicks() throw();
  6343. /** Returns the resolution of the high-resolution counter in ticks per second.
  6344. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  6345. secondsToHighResolutionTicks
  6346. */
  6347. static int64 getHighResolutionTicksPerSecond() throw();
  6348. /** Converts a number of high-resolution ticks into seconds.
  6349. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6350. secondsToHighResolutionTicks
  6351. */
  6352. static double highResolutionTicksToSeconds (int64 ticks) throw();
  6353. /** Converts a number seconds into high-resolution ticks.
  6354. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6355. highResolutionTicksToSeconds
  6356. */
  6357. static int64 secondsToHighResolutionTicks (double seconds) throw();
  6358. private:
  6359. int64 millisSinceEpoch;
  6360. };
  6361. #endif // __JUCE_TIME_JUCEHEADER__
  6362. /*** End of inlined file: juce_Time.h ***/
  6363. class FileInputStream;
  6364. class FileOutputStream;
  6365. /**
  6366. Represents a local file or directory.
  6367. This class encapsulates the absolute pathname of a file or directory, and
  6368. has methods for finding out about the file and changing its properties.
  6369. To read or write to the file, there are methods for returning an input or
  6370. output stream.
  6371. @see FileInputStream, FileOutputStream
  6372. */
  6373. class JUCE_API File
  6374. {
  6375. public:
  6376. /** Creates an (invalid) file object.
  6377. The file is initially set to an empty path, so getFullPath() will return
  6378. an empty string, and comparing the file to File::nonexistent will return
  6379. true.
  6380. You can use its operator= method to point it at a proper file.
  6381. */
  6382. File() {}
  6383. /** Creates a file from an absolute path.
  6384. If the path supplied is a relative path, it is taken to be relative
  6385. to the current working directory (see File::getCurrentWorkingDirectory()),
  6386. but this isn't a recommended way of creating a file, because you
  6387. never know what the CWD is going to be.
  6388. On the Mac/Linux, the path can include "~" notation for referring to
  6389. user home directories.
  6390. */
  6391. File (const String& path);
  6392. /** Creates a copy of another file object. */
  6393. File (const File& other);
  6394. /** Destructor. */
  6395. ~File() {}
  6396. /** Sets the file based on an absolute pathname.
  6397. If the path supplied is a relative path, it is taken to be relative
  6398. to the current working directory (see File::getCurrentWorkingDirectory()),
  6399. but this isn't a recommended way of creating a file, because you
  6400. never know what the CWD is going to be.
  6401. On the Mac/Linux, the path can include "~" notation for referring to
  6402. user home directories.
  6403. */
  6404. File& operator= (const String& newFilePath);
  6405. /** Copies from another file object. */
  6406. File& operator= (const File& otherFile);
  6407. /** This static constant is used for referring to an 'invalid' file. */
  6408. static const File nonexistent;
  6409. /** Checks whether the file actually exists.
  6410. @returns true if the file exists, either as a file or a directory.
  6411. @see existsAsFile, isDirectory
  6412. */
  6413. bool exists() const;
  6414. /** Checks whether the file exists and is a file rather than a directory.
  6415. @returns true only if this is a real file, false if it's a directory
  6416. or doesn't exist
  6417. @see exists, isDirectory
  6418. */
  6419. bool existsAsFile() const;
  6420. /** Checks whether the file is a directory that exists.
  6421. @returns true only if the file is a directory which actually exists, so
  6422. false if it's a file or doesn't exist at all
  6423. @see exists, existsAsFile
  6424. */
  6425. bool isDirectory() const;
  6426. /** Returns the size of the file in bytes.
  6427. @returns the number of bytes in the file, or 0 if it doesn't exist.
  6428. */
  6429. int64 getSize() const;
  6430. /** Utility function to convert a file size in bytes to a neat string description.
  6431. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  6432. 2000000 would produce "2 MB", etc.
  6433. */
  6434. static const String descriptionOfSizeInBytes (int64 bytes);
  6435. /** Returns the complete, absolute path of this file.
  6436. This includes the filename and all its parent folders. On Windows it'll
  6437. also include the drive letter prefix; on Mac or Linux it'll be a complete
  6438. path starting from the root folder.
  6439. If you just want the file's name, you should use getFileName() or
  6440. getFileNameWithoutExtension().
  6441. @see getFileName, getRelativePathFrom
  6442. */
  6443. const String& getFullPathName() const throw() { return fullPath; }
  6444. /** Returns the last section of the pathname.
  6445. Returns just the final part of the path - e.g. if the whole path
  6446. is "/moose/fish/foo.txt" this will return "foo.txt".
  6447. For a directory, it returns the final part of the path - e.g. for the
  6448. directory "/moose/fish" it'll return "fish".
  6449. If the filename begins with a dot, it'll return the whole filename, e.g. for
  6450. "/moose/.fish", it'll return ".fish"
  6451. @see getFullPathName, getFileNameWithoutExtension
  6452. */
  6453. const String getFileName() const;
  6454. /** Creates a relative path that refers to a file relatively to a given directory.
  6455. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  6456. would return "../../foo.txt".
  6457. If it's not possible to navigate from one file to the other, an absolute
  6458. path is returned. If the paths are invalid, an empty string may also be
  6459. returned.
  6460. @param directoryToBeRelativeTo the directory which the resultant string will
  6461. be relative to. If this is actually a file rather than
  6462. a directory, its parent directory will be used instead.
  6463. If it doesn't exist, it's assumed to be a directory.
  6464. @see getChildFile, isAbsolutePath
  6465. */
  6466. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  6467. /** Returns the file's extension.
  6468. Returns the file extension of this file, also including the dot.
  6469. e.g. "/moose/fish/foo.txt" would return ".txt"
  6470. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  6471. */
  6472. const String getFileExtension() const;
  6473. /** Checks whether the file has a given extension.
  6474. @param extensionToTest the extension to look for - it doesn't matter whether or
  6475. not this string has a dot at the start, so ".wav" and "wav"
  6476. will have the same effect. The comparison used is
  6477. case-insensitve. To compare with multiple extensions, this
  6478. parameter can contain multiple strings, separated by semi-colons -
  6479. so, for example: hasFileExtension (".jpeg;png;gif") would return
  6480. true if the file has any of those three extensions.
  6481. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  6482. */
  6483. bool hasFileExtension (const String& extensionToTest) const;
  6484. /** Returns a version of this file with a different file extension.
  6485. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  6486. @param newExtension the new extension, either with or without a dot at the start (this
  6487. doesn't make any difference). To get remove a file's extension altogether,
  6488. pass an empty string into this function.
  6489. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  6490. */
  6491. const File withFileExtension (const String& newExtension) const;
  6492. /** Returns the last part of the filename, without its file extension.
  6493. e.g. for "/moose/fish/foo.txt" this will return "foo".
  6494. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  6495. */
  6496. const String getFileNameWithoutExtension() const;
  6497. /** Returns a 32-bit hash-code that identifies this file.
  6498. This is based on the filename. Obviously it's possible, although unlikely, that
  6499. two files will have the same hash-code.
  6500. */
  6501. int hashCode() const;
  6502. /** Returns a 64-bit hash-code that identifies this file.
  6503. This is based on the filename. Obviously it's possible, although unlikely, that
  6504. two files will have the same hash-code.
  6505. */
  6506. int64 hashCode64() const;
  6507. /** Returns a file based on a relative path.
  6508. This will find a child file or directory of the current object.
  6509. e.g.
  6510. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  6511. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  6512. If the string is actually an absolute path, it will be treated as such, e.g.
  6513. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  6514. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  6515. */
  6516. const File getChildFile (String relativePath) const;
  6517. /** Returns a file which is in the same directory as this one.
  6518. This is equivalent to getParentDirectory().getChildFile (name).
  6519. @see getChildFile, getParentDirectory
  6520. */
  6521. const File getSiblingFile (const String& siblingFileName) const;
  6522. /** Returns the directory that contains this file or directory.
  6523. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  6524. */
  6525. const File getParentDirectory() const;
  6526. /** Checks whether a file is somewhere inside a directory.
  6527. Returns true if this file is somewhere inside a subdirectory of the directory
  6528. that is passed in. Neither file actually has to exist, because the function
  6529. just checks the paths for similarities.
  6530. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  6531. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  6532. */
  6533. bool isAChildOf (const File& potentialParentDirectory) const;
  6534. /** Chooses a filename relative to this one that doesn't already exist.
  6535. If this file is a directory, this will return a child file of this
  6536. directory that doesn't exist, by adding numbers to a prefix and suffix until
  6537. it finds one that isn't already there.
  6538. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  6539. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  6540. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  6541. @param prefix the string to use for the filename before the number
  6542. @param suffix the string to add to the filename after the number
  6543. @param putNumbersInBrackets if true, this will create filenames in the
  6544. format "prefix(number)suffix", if false, it will leave the
  6545. brackets out.
  6546. */
  6547. const File getNonexistentChildFile (const String& prefix,
  6548. const String& suffix,
  6549. bool putNumbersInBrackets = true) const;
  6550. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  6551. If this file doesn't exist, this will just return itself, otherwise it
  6552. will return an appropriate sibling that doesn't exist, e.g. if a file
  6553. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  6554. @param putNumbersInBrackets whether to add brackets around the numbers that
  6555. get appended to the new filename.
  6556. */
  6557. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  6558. /** Compares the pathnames for two files. */
  6559. bool operator== (const File& otherFile) const;
  6560. /** Compares the pathnames for two files. */
  6561. bool operator!= (const File& otherFile) const;
  6562. /** Compares the pathnames for two files. */
  6563. bool operator< (const File& otherFile) const;
  6564. /** Compares the pathnames for two files. */
  6565. bool operator> (const File& otherFile) const;
  6566. /** Checks whether a file can be created or written to.
  6567. @returns true if it's possible to create and write to this file. If the file
  6568. doesn't already exist, this will check its parent directory to
  6569. see if writing is allowed.
  6570. @see setReadOnly
  6571. */
  6572. bool hasWriteAccess() const;
  6573. /** Changes the write-permission of a file or directory.
  6574. @param shouldBeReadOnly whether to add or remove write-permission
  6575. @param applyRecursively if the file is a directory and this is true, it will
  6576. recurse through all the subfolders changing the permissions
  6577. of all files
  6578. @returns true if it manages to change the file's permissions.
  6579. @see hasWriteAccess
  6580. */
  6581. bool setReadOnly (bool shouldBeReadOnly,
  6582. bool applyRecursively = false) const;
  6583. /** Returns true if this file is a hidden or system file.
  6584. The criteria for deciding whether a file is hidden are platform-dependent.
  6585. */
  6586. bool isHidden() const;
  6587. /** If this file is a link, this returns the file that it points to.
  6588. If this file isn't actually link, it'll just return itself.
  6589. */
  6590. const File getLinkedTarget() const;
  6591. /** Returns the last modification time of this file.
  6592. @returns the time, or an invalid time if the file doesn't exist.
  6593. @see setLastModificationTime, getLastAccessTime, getCreationTime
  6594. */
  6595. const Time getLastModificationTime() const;
  6596. /** Returns the last time this file was accessed.
  6597. @returns the time, or an invalid time if the file doesn't exist.
  6598. @see setLastAccessTime, getLastModificationTime, getCreationTime
  6599. */
  6600. const Time getLastAccessTime() const;
  6601. /** Returns the time that this file was created.
  6602. @returns the time, or an invalid time if the file doesn't exist.
  6603. @see getLastModificationTime, getLastAccessTime
  6604. */
  6605. const Time getCreationTime() const;
  6606. /** Changes the modification time for this file.
  6607. @param newTime the time to apply to the file
  6608. @returns true if it manages to change the file's time.
  6609. @see getLastModificationTime, setLastAccessTime, setCreationTime
  6610. */
  6611. bool setLastModificationTime (const Time& newTime) const;
  6612. /** Changes the last-access time for this file.
  6613. @param newTime the time to apply to the file
  6614. @returns true if it manages to change the file's time.
  6615. @see getLastAccessTime, setLastModificationTime, setCreationTime
  6616. */
  6617. bool setLastAccessTime (const Time& newTime) const;
  6618. /** Changes the creation date for this file.
  6619. @param newTime the time to apply to the file
  6620. @returns true if it manages to change the file's time.
  6621. @see getCreationTime, setLastModificationTime, setLastAccessTime
  6622. */
  6623. bool setCreationTime (const Time& newTime) const;
  6624. /** If possible, this will try to create a version string for the given file.
  6625. The OS may be able to look at the file and give a version for it - e.g. with
  6626. executables, bundles, dlls, etc. If no version is available, this will
  6627. return an empty string.
  6628. */
  6629. const String getVersion() const;
  6630. /** Creates an empty file if it doesn't already exist.
  6631. If the file that this object refers to doesn't exist, this will create a file
  6632. of zero size.
  6633. If it already exists or is a directory, this method will do nothing.
  6634. @returns true if the file has been created (or if it already existed).
  6635. @see createDirectory
  6636. */
  6637. bool create() const;
  6638. /** Creates a new directory for this filename.
  6639. This will try to create the file as a directory, and fill also create
  6640. any parent directories it needs in order to complete the operation.
  6641. @returns true if the directory has been created successfully, (or if it
  6642. already existed beforehand).
  6643. @see create
  6644. */
  6645. bool createDirectory() const;
  6646. /** Deletes a file.
  6647. If this file is actually a directory, it may not be deleted correctly if it
  6648. contains files. See deleteRecursively() as a better way of deleting directories.
  6649. @returns true if the file has been successfully deleted (or if it didn't exist to
  6650. begin with).
  6651. @see deleteRecursively
  6652. */
  6653. bool deleteFile() const;
  6654. /** Deletes a file or directory and all its subdirectories.
  6655. If this file is a directory, this will try to delete it and all its subfolders. If
  6656. it's just a file, it will just try to delete the file.
  6657. @returns true if the file and all its subfolders have been successfully deleted
  6658. (or if it didn't exist to begin with).
  6659. @see deleteFile
  6660. */
  6661. bool deleteRecursively() const;
  6662. /** Moves this file or folder to the trash.
  6663. @returns true if the operation succeeded. It could fail if the trash is full, or
  6664. if the file is write-protected, so you should check the return value
  6665. and act appropriately.
  6666. */
  6667. bool moveToTrash() const;
  6668. /** Moves or renames a file.
  6669. Tries to move a file to a different location.
  6670. If the target file already exists, this will attempt to delete it first, and
  6671. will fail if this can't be done.
  6672. Note that the destination file isn't the directory to put it in, it's the actual
  6673. filename that you want the new file to have.
  6674. @returns true if the operation succeeds
  6675. */
  6676. bool moveFileTo (const File& targetLocation) const;
  6677. /** Copies a file.
  6678. Tries to copy a file to a different location.
  6679. If the target file already exists, this will attempt to delete it first, and
  6680. will fail if this can't be done.
  6681. @returns true if the operation succeeds
  6682. */
  6683. bool copyFileTo (const File& targetLocation) const;
  6684. /** Copies a directory.
  6685. Tries to copy an entire directory, recursively.
  6686. If this file isn't a directory or if any target files can't be created, this
  6687. will return false.
  6688. @param newDirectory the directory that this one should be copied to. Note that this
  6689. is the name of the actual directory to create, not the directory
  6690. into which the new one should be placed, so there must be enough
  6691. write privileges to create it if it doesn't exist. Any files inside
  6692. it will be overwritten by similarly named ones that are copied.
  6693. */
  6694. bool copyDirectoryTo (const File& newDirectory) const;
  6695. /** Used in file searching, to specify whether to return files, directories, or both.
  6696. */
  6697. enum TypesOfFileToFind
  6698. {
  6699. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  6700. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  6701. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  6702. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  6703. };
  6704. /** Searches inside a directory for files matching a wildcard pattern.
  6705. Assuming that this file is a directory, this method will search it
  6706. for either files or subdirectories whose names match a filename pattern.
  6707. @param results an array to which File objects will be added for the
  6708. files that the search comes up with
  6709. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6710. return files, directories, or both. If the ignoreHiddenFiles flag
  6711. is also added to this value, hidden files won't be returned
  6712. @param searchRecursively if true, all subdirectories will be recursed into to do
  6713. an exhaustive search
  6714. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6715. @returns the number of results that have been found
  6716. @see getNumberOfChildFiles, DirectoryIterator
  6717. */
  6718. int findChildFiles (Array<File>& results,
  6719. int whatToLookFor,
  6720. bool searchRecursively,
  6721. const String& wildCardPattern = "*") const;
  6722. /** Searches inside a directory and counts how many files match a wildcard pattern.
  6723. Assuming that this file is a directory, this method will search it
  6724. for either files or subdirectories whose names match a filename pattern,
  6725. and will return the number of matches found.
  6726. This isn't a recursive call, and will only search this directory, not
  6727. its children.
  6728. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6729. count files, directories, or both. If the ignoreHiddenFiles flag
  6730. is also added to this value, hidden files won't be counted
  6731. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6732. @returns the number of matches found
  6733. @see findChildFiles, DirectoryIterator
  6734. */
  6735. int getNumberOfChildFiles (int whatToLookFor,
  6736. const String& wildCardPattern = "*") const;
  6737. /** Returns true if this file is a directory that contains one or more subdirectories.
  6738. @see isDirectory, findChildFiles
  6739. */
  6740. bool containsSubDirectories() const;
  6741. /** Creates a stream to read from this file.
  6742. @returns a stream that will read from this file (initially positioned at the
  6743. start of the file), or 0 if the file can't be opened for some reason
  6744. @see createOutputStream, loadFileAsData
  6745. */
  6746. FileInputStream* createInputStream() const;
  6747. /** Creates a stream to write to this file.
  6748. If the file exists, the stream that is returned will be positioned ready for
  6749. writing at the end of the file, so you might want to use deleteFile() first
  6750. to write to an empty file.
  6751. @returns a stream that will write to this file (initially positioned at the
  6752. end of the file), or 0 if the file can't be opened for some reason
  6753. @see createInputStream, appendData, appendText
  6754. */
  6755. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  6756. /** Loads a file's contents into memory as a block of binary data.
  6757. Of course, trying to load a very large file into memory will blow up, so
  6758. it's better to check first.
  6759. @param result the data block to which the file's contents should be appended - note
  6760. that if the memory block might already contain some data, you
  6761. might want to clear it first
  6762. @returns true if the file could all be read into memory
  6763. */
  6764. bool loadFileAsData (MemoryBlock& result) const;
  6765. /** Reads a file into memory as a string.
  6766. Attempts to load the entire file as a zero-terminated string.
  6767. This makes use of InputStream::readEntireStreamAsString, which should
  6768. automatically cope with unicode/acsii file formats.
  6769. */
  6770. const String loadFileAsString() const;
  6771. /** Appends a block of binary data to the end of the file.
  6772. This will try to write the given buffer to the end of the file.
  6773. @returns false if it can't write to the file for some reason
  6774. */
  6775. bool appendData (const void* dataToAppend,
  6776. int numberOfBytes) const;
  6777. /** Replaces this file's contents with a given block of data.
  6778. This will delete the file and replace it with the given data.
  6779. A nice feature of this method is that it's safe - instead of deleting
  6780. the file first and then re-writing it, it creates a new temporary file,
  6781. writes the data to that, and then moves the new file to replace the existing
  6782. file. This means that if the power gets pulled out or something crashes,
  6783. you're a lot less likely to end up with an empty file..
  6784. Returns true if the operation succeeds, or false if it fails.
  6785. @see appendText
  6786. */
  6787. bool replaceWithData (const void* dataToWrite,
  6788. int numberOfBytes) const;
  6789. /** Appends a string to the end of the file.
  6790. This will try to append a text string to the file, as either 16-bit unicode
  6791. or 8-bit characters in the default system encoding.
  6792. It can also write the 'ff fe' unicode header bytes before the text to indicate
  6793. the endianness of the file.
  6794. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  6795. @see replaceWithText
  6796. */
  6797. bool appendText (const String& textToAppend,
  6798. bool asUnicode = false,
  6799. bool writeUnicodeHeaderBytes = false) const;
  6800. /** Replaces this file's contents with a given text string.
  6801. This will delete the file and replace it with the given text.
  6802. A nice feature of this method is that it's safe - instead of deleting
  6803. the file first and then re-writing it, it creates a new temporary file,
  6804. writes the text to that, and then moves the new file to replace the existing
  6805. file. This means that if the power gets pulled out or something crashes,
  6806. you're a lot less likely to end up with an empty file..
  6807. For an explanation of the parameters here, see the appendText() method.
  6808. Returns true if the operation succeeds, or false if it fails.
  6809. @see appendText
  6810. */
  6811. bool replaceWithText (const String& textToWrite,
  6812. bool asUnicode = false,
  6813. bool writeUnicodeHeaderBytes = false) const;
  6814. /** Attempts to scan the contents of this file and compare it to another file, returning
  6815. true if this is possible and they match byte-for-byte.
  6816. */
  6817. bool hasIdenticalContentTo (const File& other) const;
  6818. /** Creates a set of files to represent each file root.
  6819. e.g. on Windows this will create files for "c:\", "d:\" etc according
  6820. to which ones are available. On the Mac/Linux, this will probably
  6821. just add a single entry for "/".
  6822. */
  6823. static void findFileSystemRoots (Array<File>& results);
  6824. /** Finds the name of the drive on which this file lives.
  6825. @returns the volume label of the drive, or an empty string if this isn't possible
  6826. */
  6827. const String getVolumeLabel() const;
  6828. /** Returns the serial number of the volume on which this file lives.
  6829. @returns the serial number, or zero if there's a problem doing this
  6830. */
  6831. int getVolumeSerialNumber() const;
  6832. /** Returns the number of bytes free on the drive that this file lives on.
  6833. @returns the number of bytes free, or 0 if there's a problem finding this out
  6834. @see getVolumeTotalSize
  6835. */
  6836. int64 getBytesFreeOnVolume() const;
  6837. /** Returns the total size of the drive that contains this file.
  6838. @returns the total number of bytes that the volume can hold
  6839. @see getBytesFreeOnVolume
  6840. */
  6841. int64 getVolumeTotalSize() const;
  6842. /** Returns true if this file is on a CD or DVD drive. */
  6843. bool isOnCDRomDrive() const;
  6844. /** Returns true if this file is on a hard disk.
  6845. This will fail if it's a network drive, but will still be true for
  6846. removable hard-disks.
  6847. */
  6848. bool isOnHardDisk() const;
  6849. /** Returns true if this file is on a removable disk drive.
  6850. This might be a usb-drive, a CD-rom, or maybe a network drive.
  6851. */
  6852. bool isOnRemovableDrive() const;
  6853. /** Launches the file as a process.
  6854. - if the file is executable, this will run it.
  6855. - if it's a document of some kind, it will launch the document with its
  6856. default viewer application.
  6857. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  6858. @see revealToUser
  6859. */
  6860. bool startAsProcess (const String& parameters = String::empty) const;
  6861. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  6862. @see startAsProcess
  6863. */
  6864. void revealToUser() const;
  6865. /** A set of types of location that can be passed to the getSpecialLocation() method.
  6866. */
  6867. enum SpecialLocationType
  6868. {
  6869. /** The user's home folder. This is the same as using File ("~"). */
  6870. userHomeDirectory,
  6871. /** The user's default documents folder. On Windows, this might be the user's
  6872. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  6873. doesn't tend to have one of these, so it might just return their home folder.
  6874. */
  6875. userDocumentsDirectory,
  6876. /** The folder that contains the user's desktop objects. */
  6877. userDesktopDirectory,
  6878. /** The folder in which applications store their persistent user-specific settings.
  6879. On Windows, this might be "\Documents and Settings\username\Application Data".
  6880. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  6881. always create your own sub-folder to put them in, to avoid making a mess.
  6882. */
  6883. userApplicationDataDirectory,
  6884. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  6885. of the computer, rather than just the current user.
  6886. On the Mac it'll be "/Library", on Windows, it could be something like
  6887. "\Documents and Settings\All Users\Application Data".
  6888. Depending on the setup, this folder may be read-only.
  6889. */
  6890. commonApplicationDataDirectory,
  6891. /** The folder that should be used for temporary files.
  6892. Always delete them when you're finished, to keep the user's computer tidy!
  6893. */
  6894. tempDirectory,
  6895. /** Returns this application's executable file.
  6896. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6897. host app.
  6898. On the mac this will return the unix binary, not the package folder - see
  6899. currentApplicationFile for that.
  6900. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  6901. file link, invokedExecutableFile will return the name of the link.
  6902. */
  6903. currentExecutableFile,
  6904. /** Returns this application's location.
  6905. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6906. host app.
  6907. On the mac this will return the package folder (if it's in one), not the unix binary
  6908. that's inside it - compare with currentExecutableFile.
  6909. */
  6910. currentApplicationFile,
  6911. /** Returns the file that was invoked to launch this executable.
  6912. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  6913. will return the name of the link that was used, whereas currentExecutableFile will return
  6914. the actual location of the target executable.
  6915. */
  6916. invokedExecutableFile,
  6917. /** The directory in which applications normally get installed.
  6918. So on windows, this would be something like "c:\program files", on the
  6919. Mac "/Applications", or "/usr" on linux.
  6920. */
  6921. globalApplicationsDirectory,
  6922. /** The most likely place where a user might store their music files.
  6923. */
  6924. userMusicDirectory,
  6925. /** The most likely place where a user might store their movie files.
  6926. */
  6927. userMoviesDirectory,
  6928. };
  6929. /** Finds the location of a special type of file or directory, such as a home folder or
  6930. documents folder.
  6931. @see SpecialLocationType
  6932. */
  6933. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  6934. /** Returns a temporary file in the system's temp directory.
  6935. This will try to return the name of a non-existent temp file.
  6936. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  6937. */
  6938. static const File createTempFile (const String& fileNameEnding);
  6939. /** Returns the current working directory.
  6940. @see setAsCurrentWorkingDirectory
  6941. */
  6942. static const File getCurrentWorkingDirectory();
  6943. /** Sets the current working directory to be this file.
  6944. For this to work the file must point to a valid directory.
  6945. @returns true if the current directory has been changed.
  6946. @see getCurrentWorkingDirectory
  6947. */
  6948. bool setAsCurrentWorkingDirectory() const;
  6949. /** The system-specific file separator character.
  6950. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6951. */
  6952. static const juce_wchar separator;
  6953. /** The system-specific file separator character, as a string.
  6954. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6955. */
  6956. static const String separatorString;
  6957. /** Removes illegal characters from a filename.
  6958. This will return a copy of the given string after removing characters
  6959. that are not allowed in a legal filename, and possibly shortening the
  6960. string if it's too long.
  6961. Because this will remove slashes, don't use it on an absolute pathname.
  6962. @see createLegalPathName
  6963. */
  6964. static const String createLegalFileName (const String& fileNameToFix);
  6965. /** Removes illegal characters from a pathname.
  6966. Similar to createLegalFileName(), but this won't remove slashes, so can
  6967. be used on a complete pathname.
  6968. @see createLegalFileName
  6969. */
  6970. static const String createLegalPathName (const String& pathNameToFix);
  6971. /** Indicates whether filenames are case-sensitive on the current operating system.
  6972. */
  6973. static bool areFileNamesCaseSensitive();
  6974. /** Returns true if the string seems to be a fully-specified absolute path.
  6975. */
  6976. static bool isAbsolutePath (const String& path);
  6977. /** Creates a file that simply contains this string, without doing the sanity-checking
  6978. that the normal constructors do.
  6979. Best to avoid this unless you really know what you're doing.
  6980. */
  6981. static const File createFileWithoutCheckingPath (const String& path);
  6982. /** Adds a separator character to the end of a path if it doesn't already have one. */
  6983. static const String addTrailingSeparator (const String& path);
  6984. juce_UseDebuggingNewOperator
  6985. private:
  6986. String fullPath;
  6987. // internal way of contructing a file without checking the path
  6988. friend class DirectoryIterator;
  6989. File (const String&, int);
  6990. const String getPathUpToLastSlash() const;
  6991. void createDirectoryInternal (const String& fileName) const;
  6992. bool copyInternal (const File& dest) const;
  6993. bool moveInternal (const File& dest) const;
  6994. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  6995. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  6996. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  6997. static const String parseAbsolutePath (const String& path);
  6998. static bool fileTypeMatches (int whatToLookFor, bool isDir, bool isHidden);
  6999. };
  7000. #endif // __JUCE_FILE_JUCEHEADER__
  7001. /*** End of inlined file: juce_File.h ***/
  7002. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  7003. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7004. will be the name of a pointer to each child element.
  7005. E.g. @code
  7006. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7007. forEachXmlChildElement (*myParentXml, child)
  7008. {
  7009. if (child->hasTagName ("FOO"))
  7010. doSomethingWithXmlElement (child);
  7011. }
  7012. @endcode
  7013. @see forEachXmlChildElementWithTagName
  7014. */
  7015. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  7016. \
  7017. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  7018. childElementVariableName != 0; \
  7019. childElementVariableName = childElementVariableName->getNextElement())
  7020. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  7021. which have a specified tag.
  7022. This does the same job as the forEachXmlChildElement macro, but only for those
  7023. elements that have a particular tag name.
  7024. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7025. will be the name of a pointer to each child element. The requiredTagName is the
  7026. tag name to match.
  7027. E.g. @code
  7028. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7029. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  7030. {
  7031. // the child object is now guaranteed to be a <MYTAG> element..
  7032. doSomethingWithMYTAGElement (child);
  7033. }
  7034. @endcode
  7035. @see forEachXmlChildElement
  7036. */
  7037. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  7038. \
  7039. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  7040. childElementVariableName != 0; \
  7041. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  7042. /** Used to build a tree of elements representing an XML document.
  7043. An XML document can be parsed into a tree of XmlElements, each of which
  7044. represents an XML tag structure, and which may itself contain other
  7045. nested elements.
  7046. An XmlElement can also be converted back into a text document, and has
  7047. lots of useful methods for manipulating its attributes and sub-elements,
  7048. so XmlElements can actually be used as a handy general-purpose data
  7049. structure.
  7050. Here's an example of parsing some elements: @code
  7051. // check we're looking at the right kind of document..
  7052. if (myElement->hasTagName ("ANIMALS"))
  7053. {
  7054. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  7055. forEachXmlChildElement (*myElement, e)
  7056. {
  7057. if (e->hasTagName ("GIRAFFE"))
  7058. {
  7059. // found a giraffe, so use some of its attributes..
  7060. String giraffeName = e->getStringAttribute ("name");
  7061. int giraffeAge = e->getIntAttribute ("age");
  7062. bool isFriendly = e->getBoolAttribute ("friendly");
  7063. }
  7064. }
  7065. }
  7066. @endcode
  7067. And here's an example of how to create an XML document from scratch: @code
  7068. // create an outer node called "ANIMALS"
  7069. XmlElement animalsList ("ANIMALS");
  7070. for (int i = 0; i < numAnimals; ++i)
  7071. {
  7072. // create an inner element..
  7073. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7074. giraffe->setAttribute ("name", "nigel");
  7075. giraffe->setAttribute ("age", 10);
  7076. giraffe->setAttribute ("friendly", true);
  7077. // ..and add our new element to the parent node
  7078. animalsList.addChildElement (giraffe);
  7079. }
  7080. // now we can turn the whole thing into a text document..
  7081. String myXmlDoc = animalsList.createDocument (String::empty);
  7082. @endcode
  7083. @see XmlDocument
  7084. */
  7085. class JUCE_API XmlElement
  7086. {
  7087. public:
  7088. /** Creates an XmlElement with this tag name. */
  7089. explicit XmlElement (const String& tagName) throw();
  7090. /** Creates a (deep) copy of another element. */
  7091. XmlElement (const XmlElement& other);
  7092. /** Creates a (deep) copy of another element. */
  7093. XmlElement& operator= (const XmlElement& other);
  7094. /** Deleting an XmlElement will also delete all its child elements. */
  7095. ~XmlElement() throw();
  7096. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7097. The elements are only considered equivalent if they contain the same attiributes
  7098. with the same values, and have the same sub-nodes.
  7099. @param other the other element to compare to
  7100. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7101. same attributes in a different order will be
  7102. considered the same; if false, the attributes must
  7103. be in the same order as well
  7104. */
  7105. bool isEquivalentTo (const XmlElement* other,
  7106. bool ignoreOrderOfAttributes) const throw();
  7107. /** Returns an XML text document that represents this element.
  7108. The string returned can be parsed to recreate the same XmlElement that
  7109. was used to create it.
  7110. @param dtdToUse the DTD to add to the document
  7111. @param allOnOneLine if true, this means that the document will not contain any
  7112. linefeeds, so it'll be smaller but not very easy to read.
  7113. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7114. document
  7115. @param encodingType the character encoding format string to put into the xml
  7116. header
  7117. @param lineWrapLength the line length that will be used before items get placed on
  7118. a new line. This isn't an absolute maximum length, it just
  7119. determines how lists of attributes get broken up
  7120. @see writeToStream, writeToFile
  7121. */
  7122. const String createDocument (const String& dtdToUse,
  7123. bool allOnOneLine = false,
  7124. bool includeXmlHeader = true,
  7125. const String& encodingType = "UTF-8",
  7126. int lineWrapLength = 60) const;
  7127. /** Writes the document to a stream as UTF-8.
  7128. @param output the stream to write to
  7129. @param dtdToUse the DTD to add to the document
  7130. @param allOnOneLine if true, this means that the document will not contain any
  7131. linefeeds, so it'll be smaller but not very easy to read.
  7132. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7133. document
  7134. @param encodingType the character encoding format string to put into the xml
  7135. header
  7136. @param lineWrapLength the line length that will be used before items get placed on
  7137. a new line. This isn't an absolute maximum length, it just
  7138. determines how lists of attributes get broken up
  7139. @see writeToFile, createDocument
  7140. */
  7141. void writeToStream (OutputStream& output,
  7142. const String& dtdToUse,
  7143. bool allOnOneLine = false,
  7144. bool includeXmlHeader = true,
  7145. const String& encodingType = "UTF-8",
  7146. int lineWrapLength = 60) const;
  7147. /** Writes the element to a file as an XML document.
  7148. To improve safety in case something goes wrong while writing the file, this
  7149. will actually write the document to a new temporary file in the same
  7150. directory as the destination file, and if this succeeds, it will rename this
  7151. new file as the destination file (overwriting any existing file that was there).
  7152. @param destinationFile the file to write to. If this already exists, it will be
  7153. overwritten.
  7154. @param dtdToUse the DTD to add to the document
  7155. @param encodingType the character encoding format string to put into the xml
  7156. header
  7157. @param lineWrapLength the line length that will be used before items get placed on
  7158. a new line. This isn't an absolute maximum length, it just
  7159. determines how lists of attributes get broken up
  7160. @returns true if the file is written successfully; false if something goes wrong
  7161. in the process
  7162. @see createDocument
  7163. */
  7164. bool writeToFile (const File& destinationFile,
  7165. const String& dtdToUse,
  7166. const String& encodingType = "UTF-8",
  7167. int lineWrapLength = 60) const;
  7168. /** Returns this element's tag type name.
  7169. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7170. "MOOSE".
  7171. @see hasTagName
  7172. */
  7173. inline const String& getTagName() const throw() { return tagName; }
  7174. /** Tests whether this element has a particular tag name.
  7175. @param possibleTagName the tag name you're comparing it with
  7176. @see getTagName
  7177. */
  7178. bool hasTagName (const String& possibleTagName) const throw();
  7179. /** Returns the number of XML attributes this element contains.
  7180. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7181. return 2.
  7182. */
  7183. int getNumAttributes() const throw();
  7184. /** Returns the name of one of the elements attributes.
  7185. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7186. getAttributeName(1) would return "antlers".
  7187. @see getAttributeValue, getStringAttribute
  7188. */
  7189. const String& getAttributeName (int attributeIndex) const throw();
  7190. /** Returns the value of one of the elements attributes.
  7191. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7192. getAttributeName(1) would return "2".
  7193. @see getAttributeName, getStringAttribute
  7194. */
  7195. const String& getAttributeValue (int attributeIndex) const throw();
  7196. // Attribute-handling methods..
  7197. /** Checks whether the element contains an attribute with a certain name. */
  7198. bool hasAttribute (const String& attributeName) const throw();
  7199. /** Returns the value of a named attribute.
  7200. @param attributeName the name of the attribute to look up
  7201. */
  7202. const String& getStringAttribute (const String& attributeName) const throw();
  7203. /** Returns the value of a named attribute.
  7204. @param attributeName the name of the attribute to look up
  7205. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7206. with this name
  7207. */
  7208. const String getStringAttribute (const String& attributeName,
  7209. const String& defaultReturnValue) const;
  7210. /** Compares the value of a named attribute with a value passed-in.
  7211. @param attributeName the name of the attribute to look up
  7212. @param stringToCompareAgainst the value to compare it with
  7213. @param ignoreCase whether the comparison should be case-insensitive
  7214. @returns true if the value of the attribute is the same as the string passed-in;
  7215. false if it's different (or if no such attribute exists)
  7216. */
  7217. bool compareAttribute (const String& attributeName,
  7218. const String& stringToCompareAgainst,
  7219. bool ignoreCase = false) const throw();
  7220. /** Returns the value of a named attribute as an integer.
  7221. This will try to find the attribute and convert it to an integer (using
  7222. the String::getIntValue() method).
  7223. @param attributeName the name of the attribute to look up
  7224. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7225. with this name
  7226. @see setAttribute
  7227. */
  7228. int getIntAttribute (const String& attributeName,
  7229. int defaultReturnValue = 0) const;
  7230. /** Returns the value of a named attribute as floating-point.
  7231. This will try to find the attribute and convert it to an integer (using
  7232. the String::getDoubleValue() method).
  7233. @param attributeName the name of the attribute to look up
  7234. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7235. with this name
  7236. @see setAttribute
  7237. */
  7238. double getDoubleAttribute (const String& attributeName,
  7239. double defaultReturnValue = 0.0) const;
  7240. /** Returns the value of a named attribute as a boolean.
  7241. This will try to find the attribute and interpret it as a boolean. To do this,
  7242. it'll return true if the value is "1", "true", "y", etc, or false for other
  7243. values.
  7244. @param attributeName the name of the attribute to look up
  7245. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7246. with this name
  7247. */
  7248. bool getBoolAttribute (const String& attributeName,
  7249. bool defaultReturnValue = false) const;
  7250. /** Adds a named attribute to the element.
  7251. If the element already contains an attribute with this name, it's value will
  7252. be updated to the new value. If there's no such attribute yet, a new one will
  7253. be added.
  7254. Note that there are other setAttribute() methods that take integers,
  7255. doubles, etc. to make it easy to store numbers.
  7256. @param attributeName the name of the attribute to set
  7257. @param newValue the value to set it to
  7258. @see removeAttribute
  7259. */
  7260. void setAttribute (const String& attributeName,
  7261. const String& newValue);
  7262. /** Adds a named attribute to the element, setting it to an integer value.
  7263. If the element already contains an attribute with this name, it's value will
  7264. be updated to the new value. If there's no such attribute yet, a new one will
  7265. be added.
  7266. Note that there are other setAttribute() methods that take integers,
  7267. doubles, etc. to make it easy to store numbers.
  7268. @param attributeName the name of the attribute to set
  7269. @param newValue the value to set it to
  7270. */
  7271. void setAttribute (const String& attributeName,
  7272. int newValue);
  7273. /** Adds a named attribute to the element, setting it to a floating-point value.
  7274. If the element already contains an attribute with this name, it's value will
  7275. be updated to the new value. If there's no such attribute yet, a new one will
  7276. be added.
  7277. Note that there are other setAttribute() methods that take integers,
  7278. doubles, etc. to make it easy to store numbers.
  7279. @param attributeName the name of the attribute to set
  7280. @param newValue the value to set it to
  7281. */
  7282. void setAttribute (const String& attributeName,
  7283. double newValue);
  7284. /** Removes a named attribute from the element.
  7285. @param attributeName the name of the attribute to remove
  7286. @see removeAllAttributes
  7287. */
  7288. void removeAttribute (const String& attributeName) throw();
  7289. /** Removes all attributes from this element.
  7290. */
  7291. void removeAllAttributes() throw();
  7292. // Child element methods..
  7293. /** Returns the first of this element's sub-elements.
  7294. see getNextElement() for an example of how to iterate the sub-elements.
  7295. @see forEachXmlChildElement
  7296. */
  7297. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7298. /** Returns the next of this element's siblings.
  7299. This can be used for iterating an element's sub-elements, e.g.
  7300. @code
  7301. XmlElement* child = myXmlDocument->getFirstChildElement();
  7302. while (child != 0)
  7303. {
  7304. ...do stuff with this child..
  7305. child = child->getNextElement();
  7306. }
  7307. @endcode
  7308. Note that when iterating the child elements, some of them might be
  7309. text elements as well as XML tags - use isTextElement() to work this
  7310. out.
  7311. Also, it's much easier and neater to use this method indirectly via the
  7312. forEachXmlChildElement macro.
  7313. @returns the sibling element that follows this one, or zero if this is the last
  7314. element in its parent
  7315. @see getNextElement, isTextElement, forEachXmlChildElement
  7316. */
  7317. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7318. /** Returns the next of this element's siblings which has the specified tag
  7319. name.
  7320. This is like getNextElement(), but will scan through the list until it
  7321. finds an element with the given tag name.
  7322. @see getNextElement, forEachXmlChildElementWithTagName
  7323. */
  7324. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  7325. /** Returns the number of sub-elements in this element.
  7326. @see getChildElement
  7327. */
  7328. int getNumChildElements() const throw();
  7329. /** Returns the sub-element at a certain index.
  7330. It's not very efficient to iterate the sub-elements by index - see
  7331. getNextElement() for an example of how best to iterate.
  7332. @returns the n'th child of this element, or 0 if the index is out-of-range
  7333. @see getNextElement, isTextElement, getChildByName
  7334. */
  7335. XmlElement* getChildElement (int index) const throw();
  7336. /** Returns the first sub-element with a given tag-name.
  7337. @param tagNameToLookFor the tag name of the element you want to find
  7338. @returns the first element with this tag name, or 0 if none is found
  7339. @see getNextElement, isTextElement, getChildElement
  7340. */
  7341. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  7342. /** Appends an element to this element's list of children.
  7343. Child elements are deleted automatically when their parent is deleted, so
  7344. make sure the object that you pass in will not be deleted by anything else,
  7345. and make sure it's not already the child of another element.
  7346. @see getFirstChildElement, getNextElement, getNumChildElements,
  7347. getChildElement, removeChildElement
  7348. */
  7349. void addChildElement (XmlElement* const newChildElement) throw();
  7350. /** Inserts an element into this element's list of children.
  7351. Child elements are deleted automatically when their parent is deleted, so
  7352. make sure the object that you pass in will not be deleted by anything else,
  7353. and make sure it's not already the child of another element.
  7354. @param newChildNode the element to add
  7355. @param indexToInsertAt the index at which to insert the new element - if this is
  7356. below zero, it will be added to the end of the list
  7357. @see addChildElement, insertChildElement
  7358. */
  7359. void insertChildElement (XmlElement* newChildNode,
  7360. int indexToInsertAt) throw();
  7361. /** Creates a new element with the given name and returns it, after adding it
  7362. as a child element.
  7363. This is a handy method that means that instead of writing this:
  7364. @code
  7365. XmlElement* newElement = new XmlElement ("foobar");
  7366. myParentElement->addChildElement (newElement);
  7367. @endcode
  7368. ..you could just write this:
  7369. @code
  7370. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  7371. @endcode
  7372. */
  7373. XmlElement* createNewChildElement (const String& tagName);
  7374. /** Replaces one of this element's children with another node.
  7375. If the current element passed-in isn't actually a child of this element,
  7376. this will return false and the new one won't be added. Otherwise, the
  7377. existing element will be deleted, replaced with the new one, and it
  7378. will return true.
  7379. */
  7380. bool replaceChildElement (XmlElement* currentChildElement,
  7381. XmlElement* newChildNode) throw();
  7382. /** Removes a child element.
  7383. @param childToRemove the child to look for and remove
  7384. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7385. just remove it
  7386. */
  7387. void removeChildElement (XmlElement* childToRemove,
  7388. bool shouldDeleteTheChild) throw();
  7389. /** Deletes all the child elements in the element.
  7390. @see removeChildElement, deleteAllChildElementsWithTagName
  7391. */
  7392. void deleteAllChildElements() throw();
  7393. /** Deletes all the child elements with a given tag name.
  7394. @see removeChildElement
  7395. */
  7396. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  7397. /** Returns true if the given element is a child of this one. */
  7398. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7399. /** Recursively searches all sub-elements to find one that contains the specified
  7400. child element.
  7401. */
  7402. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  7403. /** Sorts the child elements using a comparator.
  7404. This will use a comparator object to sort the elements into order. The object
  7405. passed must have a method of the form:
  7406. @code
  7407. int compareElements (const XmlElement* first, const XmlElement* second);
  7408. @endcode
  7409. ..and this method must return:
  7410. - a value of < 0 if the first comes before the second
  7411. - a value of 0 if the two objects are equivalent
  7412. - a value of > 0 if the second comes before the first
  7413. To improve performance, the compareElements() method can be declared as static or const.
  7414. @param comparator the comparator to use for comparing elements.
  7415. @param retainOrderOfEquivalentItems if this is true, then items
  7416. which the comparator says are equivalent will be
  7417. kept in the order in which they currently appear
  7418. in the array. This is slower to perform, but may
  7419. be important in some cases. If it's false, a faster
  7420. algorithm is used, but equivalent elements may be
  7421. rearranged.
  7422. */
  7423. template <class ElementComparator>
  7424. void sortChildElements (ElementComparator& comparator,
  7425. bool retainOrderOfEquivalentItems = false)
  7426. {
  7427. const int num = getNumChildElements();
  7428. if (num > 1)
  7429. {
  7430. HeapBlock <XmlElement*> elems (num);
  7431. getChildElementsAsArray (elems);
  7432. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  7433. reorderChildElements (elems, num);
  7434. }
  7435. }
  7436. /** Returns true if this element is a section of text.
  7437. Elements can either be an XML tag element or a secton of text, so this
  7438. is used to find out what kind of element this one is.
  7439. @see getAllText, addTextElement, deleteAllTextElements
  7440. */
  7441. bool isTextElement() const throw();
  7442. /** Returns the text for a text element.
  7443. Note that if you have an element like this:
  7444. @code<xyz>hello</xyz>@endcode
  7445. then calling getText on the "xyz" element won't return "hello", because that is
  7446. actually stored in a special text sub-element inside the xyz element. To get the
  7447. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7448. use getAllSubText() to do this automatically.
  7449. @see isTextElement, getAllSubText, getChildElementAllSubText
  7450. */
  7451. const String& getText() const throw();
  7452. /** Sets the text in a text element.
  7453. Note that this is only a valid call if this element is a text element. If it's
  7454. not, then no action will be performed.
  7455. */
  7456. void setText (const String& newText);
  7457. /** Returns all the text from this element's child nodes.
  7458. This iterates all the child elements and when it finds text elements,
  7459. it concatenates their text into a big string which it returns.
  7460. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7461. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7462. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7463. */
  7464. const String getAllSubText() const;
  7465. /** Returns all the sub-text of a named child element.
  7466. If there is a child element with the given tag name, this will return
  7467. all of its sub-text (by calling getAllSubText() on it). If there is
  7468. no such child element, this will return the default string passed-in.
  7469. @see getAllSubText
  7470. */
  7471. const String getChildElementAllSubText (const String& childTagName,
  7472. const String& defaultReturnValue) const;
  7473. /** Appends a section of text to this element.
  7474. @see isTextElement, getText, getAllSubText
  7475. */
  7476. void addTextElement (const String& text);
  7477. /** Removes all the text elements from this element.
  7478. @see isTextElement, getText, getAllSubText, addTextElement
  7479. */
  7480. void deleteAllTextElements() throw();
  7481. /** Creates a text element that can be added to a parent element.
  7482. */
  7483. static XmlElement* createTextElement (const String& text);
  7484. juce_UseDebuggingNewOperator
  7485. private:
  7486. friend class XmlDocument;
  7487. String tagName;
  7488. XmlElement* firstChildElement;
  7489. XmlElement* nextElement;
  7490. struct XmlAttributeNode
  7491. {
  7492. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7493. XmlAttributeNode (const String& name, const String& value) throw();
  7494. String name, value;
  7495. XmlAttributeNode* next;
  7496. private:
  7497. XmlAttributeNode& operator= (const XmlAttributeNode&);
  7498. };
  7499. XmlAttributeNode* attributes;
  7500. XmlElement (int) throw();
  7501. void copyChildrenAndAttributesFrom (const XmlElement& other);
  7502. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  7503. void getChildElementsAsArray (XmlElement**) const throw();
  7504. void reorderChildElements (XmlElement** const, const int) throw();
  7505. };
  7506. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7507. /*** End of inlined file: juce_XmlElement.h ***/
  7508. /**
  7509. A set of named property values, which can be strings, integers, floating point, etc.
  7510. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7511. to load and save types other than strings.
  7512. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7513. messages and saves/loads the list from a file.
  7514. */
  7515. class JUCE_API PropertySet
  7516. {
  7517. public:
  7518. /** Creates an empty PropertySet.
  7519. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7520. case-insensitive way
  7521. */
  7522. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7523. /** Creates a copy of another PropertySet.
  7524. */
  7525. PropertySet (const PropertySet& other) throw();
  7526. /** Copies another PropertySet over this one.
  7527. */
  7528. PropertySet& operator= (const PropertySet& other) throw();
  7529. /** Destructor. */
  7530. virtual ~PropertySet();
  7531. /** Returns one of the properties as a string.
  7532. If the value isn't found in this set, then this will look for it in a fallback
  7533. property set (if you've specified one with the setFallbackPropertySet() method),
  7534. and if it can't find one there, it'll return the default value passed-in.
  7535. @param keyName the name of the property to retrieve
  7536. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7537. */
  7538. const String getValue (const String& keyName,
  7539. const String& defaultReturnValue = String::empty) const throw();
  7540. /** Returns one of the properties as an integer.
  7541. If the value isn't found in this set, then this will look for it in a fallback
  7542. property set (if you've specified one with the setFallbackPropertySet() method),
  7543. and if it can't find one there, it'll return the default value passed-in.
  7544. @param keyName the name of the property to retrieve
  7545. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7546. */
  7547. int getIntValue (const String& keyName,
  7548. const int defaultReturnValue = 0) const throw();
  7549. /** Returns one of the properties as an double.
  7550. If the value isn't found in this set, then this will look for it in a fallback
  7551. property set (if you've specified one with the setFallbackPropertySet() method),
  7552. and if it can't find one there, it'll return the default value passed-in.
  7553. @param keyName the name of the property to retrieve
  7554. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7555. */
  7556. double getDoubleValue (const String& keyName,
  7557. const double defaultReturnValue = 0.0) const throw();
  7558. /** Returns one of the properties as an boolean.
  7559. The result will be true if the string found for this key name can be parsed as a non-zero
  7560. integer.
  7561. If the value isn't found in this set, then this will look for it in a fallback
  7562. property set (if you've specified one with the setFallbackPropertySet() method),
  7563. and if it can't find one there, it'll return the default value passed-in.
  7564. @param keyName the name of the property to retrieve
  7565. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7566. */
  7567. bool getBoolValue (const String& keyName,
  7568. const bool defaultReturnValue = false) const throw();
  7569. /** Returns one of the properties as an XML element.
  7570. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7571. key isn't found, or if the entry contains an string that isn't valid XML.
  7572. If the value isn't found in this set, then this will look for it in a fallback
  7573. property set (if you've specified one with the setFallbackPropertySet() method),
  7574. and if it can't find one there, it'll return the default value passed-in.
  7575. @param keyName the name of the property to retrieve
  7576. */
  7577. XmlElement* getXmlValue (const String& keyName) const;
  7578. /** Sets a named property as a string.
  7579. @param keyName the name of the property to set. (This mustn't be an empty string)
  7580. @param value the new value to set it to
  7581. */
  7582. void setValue (const String& keyName, const String& value) throw();
  7583. /** Sets a named property to an integer.
  7584. @param keyName the name of the property to set. (This mustn't be an empty string)
  7585. @param value the new value to set it to
  7586. */
  7587. void setValue (const String& keyName, const int value) throw();
  7588. /** Sets a named property to a double.
  7589. @param keyName the name of the property to set. (This mustn't be an empty string)
  7590. @param value the new value to set it to
  7591. */
  7592. void setValue (const String& keyName, const double value) throw();
  7593. /** Sets a named property to a boolean.
  7594. @param keyName the name of the property to set. (This mustn't be an empty string)
  7595. @param value the new value to set it to
  7596. */
  7597. void setValue (const String& keyName, const bool value) throw();
  7598. /** Sets a named property to an XML element.
  7599. @param keyName the name of the property to set. (This mustn't be an empty string)
  7600. @param xml the new element to set it to. If this is zero, the value will be set to
  7601. an empty string
  7602. @see getXmlValue
  7603. */
  7604. void setValue (const String& keyName, const XmlElement* const xml);
  7605. /** Deletes a property.
  7606. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7607. */
  7608. void removeValue (const String& keyName) throw();
  7609. /** Returns true if the properies include the given key. */
  7610. bool containsKey (const String& keyName) const throw();
  7611. /** Removes all values. */
  7612. void clear();
  7613. /** Returns the keys/value pair array containing all the properties. */
  7614. StringPairArray& getAllProperties() throw() { return properties; }
  7615. /** Returns the lock used when reading or writing to this set */
  7616. const CriticalSection& getLock() const throw() { return lock; }
  7617. /** Returns an XML element which encapsulates all the items in this property set.
  7618. The string parameter is the tag name that should be used for the node.
  7619. @see restoreFromXml
  7620. */
  7621. XmlElement* createXml (const String& nodeName) const throw();
  7622. /** Reloads a set of properties that were previously stored as XML.
  7623. The node passed in must have been created by the createXml() method.
  7624. @see createXml
  7625. */
  7626. void restoreFromXml (const XmlElement& xml) throw();
  7627. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7628. set in this one.
  7629. If you set this up to be a pointer to a second property set, then whenever one
  7630. of the getValue() methods fails to find an entry in this set, it will look up that
  7631. value in the fallback set, and if it finds it, it will return that.
  7632. Make sure that you don't delete the fallback set while it's still being used by
  7633. another set! To remove the fallback set, just call this method with a null pointer.
  7634. @see getFallbackPropertySet
  7635. */
  7636. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7637. /** Returns the fallback property set.
  7638. @see setFallbackPropertySet
  7639. */
  7640. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7641. juce_UseDebuggingNewOperator
  7642. protected:
  7643. /** Subclasses can override this to be told when one of the properies has been changed.
  7644. */
  7645. virtual void propertyChanged();
  7646. private:
  7647. StringPairArray properties;
  7648. PropertySet* fallbackProperties;
  7649. CriticalSection lock;
  7650. bool ignoreCaseOfKeys;
  7651. };
  7652. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7653. /*** End of inlined file: juce_PropertySet.h ***/
  7654. #endif
  7655. #ifndef __JUCE_RANGE_JUCEHEADER__
  7656. /*** Start of inlined file: juce_Range.h ***/
  7657. #ifndef __JUCE_RANGE_JUCEHEADER__
  7658. #define __JUCE_RANGE_JUCEHEADER__
  7659. /** A general-purpose range object, that simply represents any linear range with
  7660. a start and end point.
  7661. The templated parameter is expected to be a primitive integer or floating point
  7662. type, though class types could also be used if they behave in a number-like way.
  7663. */
  7664. template <typename ValueType>
  7665. class Range
  7666. {
  7667. public:
  7668. /** Constructs an empty range. */
  7669. Range() throw()
  7670. : start (ValueType()), end (ValueType())
  7671. {
  7672. }
  7673. /** Constructs a range with given start and end values. */
  7674. Range (const ValueType start_, const ValueType end_) throw()
  7675. : start (start_), end (jmax (start_, end_))
  7676. {
  7677. }
  7678. /** Constructs a copy of another range. */
  7679. Range (const Range& other) throw()
  7680. : start (other.start), end (other.end)
  7681. {
  7682. }
  7683. /** Copies another range object. */
  7684. Range& operator= (const Range& other) throw()
  7685. {
  7686. start = other.start;
  7687. end = other.end;
  7688. return *this;
  7689. }
  7690. /** Destructor. */
  7691. ~Range() throw()
  7692. {
  7693. }
  7694. /** Returns the range that lies between two positions (in either order). */
  7695. static const Range between (const ValueType position1, const ValueType position2) throw()
  7696. {
  7697. return (position1 < position2) ? Range (position1, position2)
  7698. : Range (position2, position1);
  7699. }
  7700. /** Returns a range with the specified start position and a length of zero. */
  7701. static const Range emptyRange (const ValueType start) throw()
  7702. {
  7703. return Range (start, start);
  7704. }
  7705. /** Returns the start of the range. */
  7706. inline ValueType getStart() const throw() { return start; }
  7707. /** Returns the length of the range. */
  7708. inline ValueType getLength() const throw() { return end - start; }
  7709. /** Returns the end of the range. */
  7710. inline ValueType getEnd() const throw() { return end; }
  7711. /** Returns true if the range has a length of zero. */
  7712. inline bool isEmpty() const throw() { return start == end; }
  7713. /** Changes the start position of the range, leaving the end position unchanged.
  7714. If the new start position is higher than the current end of the range, the end point
  7715. will be pushed along to equal it, leaving an empty range at the new position.
  7716. */
  7717. void setStart (const ValueType newStart) throw()
  7718. {
  7719. start = newStart;
  7720. if (end < newStart)
  7721. end = newStart;
  7722. }
  7723. /** Returns a range with the same end as this one, but a different start.
  7724. If the new start position is higher than the current end of the range, the end point
  7725. will be pushed along to equal it, returning an empty range at the new position.
  7726. */
  7727. const Range withStart (const ValueType newStart) const throw()
  7728. {
  7729. return Range (newStart, jmax (newStart, end));
  7730. }
  7731. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7732. const Range movedToStartAt (const ValueType newStart) const throw()
  7733. {
  7734. return Range (newStart, newStart + getLength());
  7735. }
  7736. /** Changes the end position of the range, leaving the start unchanged.
  7737. If the new end position is below the current start of the range, the start point
  7738. will be pushed back to equal the new end point.
  7739. */
  7740. void setEnd (const ValueType newEnd) throw()
  7741. {
  7742. end = newEnd;
  7743. if (newEnd < start)
  7744. start = newEnd;
  7745. }
  7746. /** Returns a range with the same start position as this one, but a different end.
  7747. If the new end position is below the current start of the range, the start point
  7748. will be pushed back to equal the new end point.
  7749. */
  7750. const Range withEnd (const ValueType newEnd) const throw()
  7751. {
  7752. return Range (jmin (start, newEnd), newEnd);
  7753. }
  7754. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7755. const Range movedToEndAt (const ValueType newEnd) const throw()
  7756. {
  7757. return Range (newEnd - getLength(), newEnd);
  7758. }
  7759. /** Changes the length of the range.
  7760. Lengths less than zero are treated as zero.
  7761. */
  7762. void setLength (const ValueType newLength) throw()
  7763. {
  7764. end = start + jmax (ValueType(), newLength);
  7765. }
  7766. /** Returns a range with the same start as this one, but a different length.
  7767. Lengths less than zero are treated as zero.
  7768. */
  7769. const Range withLength (const ValueType newLength) const throw()
  7770. {
  7771. return Range (start, start + newLength);
  7772. }
  7773. /** Adds an amount to the start and end of the range. */
  7774. inline const Range& operator+= (const ValueType amountToAdd) throw()
  7775. {
  7776. start += amountToAdd;
  7777. end += amountToAdd;
  7778. return *this;
  7779. }
  7780. /** Subtracts an amount from the start and end of the range. */
  7781. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  7782. {
  7783. start -= amountToSubtract;
  7784. end -= amountToSubtract;
  7785. return *this;
  7786. }
  7787. /** Returns a range that is equal to this one with an amount added to its
  7788. start and end.
  7789. */
  7790. const Range operator+ (const ValueType amountToAdd) const throw()
  7791. {
  7792. return Range (start + amountToAdd, end + amountToAdd);
  7793. }
  7794. /** Returns a range that is equal to this one with the specified amount
  7795. subtracted from its start and end. */
  7796. const Range operator- (const ValueType amountToSubtract) const throw()
  7797. {
  7798. return Range (start - amountToSubtract, end - amountToSubtract);
  7799. }
  7800. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  7801. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  7802. /** Returns true if the given position lies inside this range. */
  7803. bool contains (const ValueType position) const throw()
  7804. {
  7805. return start <= position && position < end;
  7806. }
  7807. /** Returns the nearest value to the one supplied, which lies within the range. */
  7808. ValueType clipValue (const ValueType value) const throw()
  7809. {
  7810. return jlimit (start, end, value);
  7811. }
  7812. /** Returns true if the given range lies entirely inside this range. */
  7813. bool contains (const Range& other) const throw()
  7814. {
  7815. return start <= other.start && end >= other.end;
  7816. }
  7817. /** Returns true if the given range intersects this one. */
  7818. bool intersects (const Range& other) const throw()
  7819. {
  7820. return other.start < end && start < other.end;
  7821. }
  7822. /** Returns the range that is the intersection of the two ranges, or an empty range
  7823. with an undefined start position if they don't overlap. */
  7824. const Range getIntersectionWith (const Range& other) const throw()
  7825. {
  7826. return Range (jmax (start, other.start),
  7827. jmin (end, other.end));
  7828. }
  7829. /** Returns the smallest range that contains both this one and the other one. */
  7830. const Range getUnionWith (const Range& other) const throw()
  7831. {
  7832. return Range (jmin (start, other.start),
  7833. jmax (end, other.end));
  7834. }
  7835. /** Returns a given range, after moving it forwards or backwards to fit it
  7836. within this range.
  7837. If the supplied range has a greater length than this one, the return value
  7838. will be this range.
  7839. Otherwise, if the supplied range is smaller than this one, the return value
  7840. will be the new range, shifted forwards or backwards so that it doesn't extend
  7841. beyond this one, but keeping its original length.
  7842. */
  7843. const Range constrainRange (const Range& rangeToConstrain) const throw()
  7844. {
  7845. const ValueType otherLen = rangeToConstrain.getLength();
  7846. return getLength() <= otherLen
  7847. ? *this
  7848. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  7849. }
  7850. juce_UseDebuggingNewOperator
  7851. private:
  7852. ValueType start, end;
  7853. };
  7854. #endif // __JUCE_RANGE_JUCEHEADER__
  7855. /*** End of inlined file: juce_Range.h ***/
  7856. #endif
  7857. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7858. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  7859. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7860. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7861. /**
  7862. Holds a list of objects derived from ReferenceCountedObject.
  7863. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7864. and takes care of incrementing and decrementing their ref counts when they
  7865. are added and removed from the array.
  7866. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7867. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7868. @see Array, OwnedArray, StringArray
  7869. */
  7870. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7871. class ReferenceCountedArray
  7872. {
  7873. public:
  7874. /** Creates an empty array.
  7875. @see ReferenceCountedObject, Array, OwnedArray
  7876. */
  7877. ReferenceCountedArray() throw()
  7878. : numUsed (0)
  7879. {
  7880. }
  7881. /** Creates a copy of another array */
  7882. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7883. {
  7884. const ScopedLockType lock (other.getLock());
  7885. numUsed = other.numUsed;
  7886. data.setAllocatedSize (numUsed);
  7887. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7888. for (int i = numUsed; --i >= 0;)
  7889. if (data.elements[i] != 0)
  7890. data.elements[i]->incReferenceCount();
  7891. }
  7892. /** Copies another array into this one.
  7893. Any existing objects in this array will first be released.
  7894. */
  7895. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7896. {
  7897. if (this != &other)
  7898. {
  7899. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  7900. swapWithArray (otherCopy);
  7901. }
  7902. return *this;
  7903. }
  7904. /** Destructor.
  7905. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7906. */
  7907. ~ReferenceCountedArray()
  7908. {
  7909. clear();
  7910. }
  7911. /** Removes all objects from the array.
  7912. Any objects in the array that are not referenced from elsewhere will be deleted.
  7913. */
  7914. void clear()
  7915. {
  7916. const ScopedLockType lock (getLock());
  7917. while (numUsed > 0)
  7918. if (data.elements [--numUsed] != 0)
  7919. data.elements [numUsed]->decReferenceCount();
  7920. jassert (numUsed == 0);
  7921. data.setAllocatedSize (0);
  7922. }
  7923. /** Returns the current number of objects in the array. */
  7924. inline int size() const throw()
  7925. {
  7926. return numUsed;
  7927. }
  7928. /** Returns a pointer to the object at this index in the array.
  7929. If the index is out-of-range, this will return a null pointer, (and
  7930. it could be null anyway, because it's ok for the array to hold null
  7931. pointers as well as objects).
  7932. @see getUnchecked
  7933. */
  7934. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7935. {
  7936. const ScopedLockType lock (getLock());
  7937. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  7938. : static_cast <ObjectClass*> (0);
  7939. }
  7940. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7941. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7942. it can be used when you're sure the index if always going to be legal.
  7943. */
  7944. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7945. {
  7946. const ScopedLockType lock (getLock());
  7947. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7948. return data.elements [index];
  7949. }
  7950. /** Returns a pointer to the first object in the array.
  7951. This will return a null pointer if the array's empty.
  7952. @see getLast
  7953. */
  7954. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7955. {
  7956. const ScopedLockType lock (getLock());
  7957. return numUsed > 0 ? data.elements [0]
  7958. : static_cast <ObjectClass*> (0);
  7959. }
  7960. /** Returns a pointer to the last object in the array.
  7961. This will return a null pointer if the array's empty.
  7962. @see getFirst
  7963. */
  7964. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7965. {
  7966. const ScopedLockType lock (getLock());
  7967. return numUsed > 0 ? data.elements [numUsed - 1]
  7968. : static_cast <ObjectClass*> (0);
  7969. }
  7970. /** Finds the index of the first occurrence of an object in the array.
  7971. @param objectToLookFor the object to look for
  7972. @returns the index at which the object was found, or -1 if it's not found
  7973. */
  7974. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7975. {
  7976. const ScopedLockType lock (getLock());
  7977. ObjectClass** e = data.elements.getData();
  7978. ObjectClass** const end = e + numUsed;
  7979. while (e != end)
  7980. {
  7981. if (objectToLookFor == *e)
  7982. return static_cast <int> (e - data.elements.getData());
  7983. ++e;
  7984. }
  7985. return -1;
  7986. }
  7987. /** Returns true if the array contains a specified object.
  7988. @param objectToLookFor the object to look for
  7989. @returns true if the object is in the array
  7990. */
  7991. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7992. {
  7993. const ScopedLockType lock (getLock());
  7994. ObjectClass** e = data.elements.getData();
  7995. ObjectClass** const end = e + numUsed;
  7996. while (e != end)
  7997. {
  7998. if (objectToLookFor == *e)
  7999. return true;
  8000. ++e;
  8001. }
  8002. return false;
  8003. }
  8004. /** Appends a new object to the end of the array.
  8005. This will increase the new object's reference count.
  8006. @param newObject the new object to add to the array
  8007. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  8008. */
  8009. void add (ObjectClass* const newObject) throw()
  8010. {
  8011. const ScopedLockType lock (getLock());
  8012. data.ensureAllocatedSize (numUsed + 1);
  8013. data.elements [numUsed++] = newObject;
  8014. if (newObject != 0)
  8015. newObject->incReferenceCount();
  8016. }
  8017. /** Inserts a new object into the array at the given index.
  8018. If the index is less than 0 or greater than the size of the array, the
  8019. element will be added to the end of the array.
  8020. Otherwise, it will be inserted into the array, moving all the later elements
  8021. along to make room.
  8022. This will increase the new object's reference count.
  8023. @param indexToInsertAt the index at which the new element should be inserted
  8024. @param newObject the new object to add to the array
  8025. @see add, addSorted, addIfNotAlreadyThere, set
  8026. */
  8027. void insert (int indexToInsertAt,
  8028. ObjectClass* const newObject) throw()
  8029. {
  8030. if (indexToInsertAt >= 0)
  8031. {
  8032. const ScopedLockType lock (getLock());
  8033. if (indexToInsertAt > numUsed)
  8034. indexToInsertAt = numUsed;
  8035. data.ensureAllocatedSize (numUsed + 1);
  8036. ObjectClass** const e = data.elements + indexToInsertAt;
  8037. const int numToMove = numUsed - indexToInsertAt;
  8038. if (numToMove > 0)
  8039. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  8040. *e = newObject;
  8041. if (newObject != 0)
  8042. newObject->incReferenceCount();
  8043. ++numUsed;
  8044. }
  8045. else
  8046. {
  8047. add (newObject);
  8048. }
  8049. }
  8050. /** Appends a new object at the end of the array as long as the array doesn't
  8051. already contain it.
  8052. If the array already contains a matching object, nothing will be done.
  8053. @param newObject the new object to add to the array
  8054. */
  8055. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  8056. {
  8057. const ScopedLockType lock (getLock());
  8058. if (! contains (newObject))
  8059. add (newObject);
  8060. }
  8061. /** Replaces an object in the array with a different one.
  8062. If the index is less than zero, this method does nothing.
  8063. If the index is beyond the end of the array, the new object is added to the end of the array.
  8064. The object being added has its reference count increased, and if it's replacing
  8065. another object, then that one has its reference count decreased, and may be deleted.
  8066. @param indexToChange the index whose value you want to change
  8067. @param newObject the new value to set for this index.
  8068. @see add, insert, remove
  8069. */
  8070. void set (const int indexToChange,
  8071. ObjectClass* const newObject)
  8072. {
  8073. if (indexToChange >= 0)
  8074. {
  8075. const ScopedLockType lock (getLock());
  8076. if (newObject != 0)
  8077. newObject->incReferenceCount();
  8078. if (indexToChange < numUsed)
  8079. {
  8080. if (data.elements [indexToChange] != 0)
  8081. data.elements [indexToChange]->decReferenceCount();
  8082. data.elements [indexToChange] = newObject;
  8083. }
  8084. else
  8085. {
  8086. data.ensureAllocatedSize (numUsed + 1);
  8087. data.elements [numUsed++] = newObject;
  8088. }
  8089. }
  8090. }
  8091. /** Adds elements from another array to the end of this array.
  8092. @param arrayToAddFrom the array from which to copy the elements
  8093. @param startIndex the first element of the other array to start copying from
  8094. @param numElementsToAdd how many elements to add from the other array. If this
  8095. value is negative or greater than the number of available elements,
  8096. all available elements will be copied.
  8097. @see add
  8098. */
  8099. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8100. int startIndex = 0,
  8101. int numElementsToAdd = -1) throw()
  8102. {
  8103. arrayToAddFrom.lockArray();
  8104. const ScopedLockType lock (getLock());
  8105. if (startIndex < 0)
  8106. {
  8107. jassertfalse;
  8108. startIndex = 0;
  8109. }
  8110. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8111. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8112. if (numElementsToAdd > 0)
  8113. {
  8114. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  8115. while (--numElementsToAdd >= 0)
  8116. add (arrayToAddFrom.getUnchecked (startIndex++));
  8117. }
  8118. arrayToAddFrom.unlockArray();
  8119. }
  8120. /** Inserts a new object into the array assuming that the array is sorted.
  8121. This will use a comparator to find the position at which the new object
  8122. should go. If the array isn't sorted, the behaviour of this
  8123. method will be unpredictable.
  8124. @param comparator the comparator object to use to compare the elements - see the
  8125. sort() method for details about this object's form
  8126. @param newObject the new object to insert to the array
  8127. @see add, sort
  8128. */
  8129. template <class ElementComparator>
  8130. void addSorted (ElementComparator& comparator,
  8131. ObjectClass* newObject) throw()
  8132. {
  8133. const ScopedLockType lock (getLock());
  8134. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  8135. }
  8136. /** Inserts or replaces an object in the array, assuming it is sorted.
  8137. This is similar to addSorted, but if a matching element already exists, then it will be
  8138. replaced by the new one, rather than the new one being added as well.
  8139. */
  8140. template <class ElementComparator>
  8141. void addOrReplaceSorted (ElementComparator& comparator,
  8142. ObjectClass* newObject) throw()
  8143. {
  8144. const ScopedLockType lock (getLock());
  8145. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  8146. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  8147. set (index - 1, newObject); // replace an existing object that matches
  8148. else
  8149. insert (index, newObject); // no match, so insert the new one
  8150. }
  8151. /** Removes an object from the array.
  8152. This will remove the object at a given index and move back all the
  8153. subsequent objects to close the gap.
  8154. If the index passed in is out-of-range, nothing will happen.
  8155. The object that is removed will have its reference count decreased,
  8156. and may be deleted if not referenced from elsewhere.
  8157. @param indexToRemove the index of the element to remove
  8158. @see removeObject, removeRange
  8159. */
  8160. void remove (const int indexToRemove)
  8161. {
  8162. const ScopedLockType lock (getLock());
  8163. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8164. {
  8165. ObjectClass** const e = data.elements + indexToRemove;
  8166. if (*e != 0)
  8167. (*e)->decReferenceCount();
  8168. --numUsed;
  8169. const int numberToShift = numUsed - indexToRemove;
  8170. if (numberToShift > 0)
  8171. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8172. if ((numUsed << 1) < data.numAllocated)
  8173. minimiseStorageOverheads();
  8174. }
  8175. }
  8176. /** Removes the first occurrence of a specified object from the array.
  8177. If the item isn't found, no action is taken. If it is found, it is
  8178. removed and has its reference count decreased.
  8179. @param objectToRemove the object to try to remove
  8180. @see remove, removeRange
  8181. */
  8182. void removeObject (ObjectClass* const objectToRemove)
  8183. {
  8184. const ScopedLockType lock (getLock());
  8185. remove (indexOf (objectToRemove));
  8186. }
  8187. /** Removes a range of objects from the array.
  8188. This will remove a set of objects, starting from the given index,
  8189. and move any subsequent elements down to close the gap.
  8190. If the range extends beyond the bounds of the array, it will
  8191. be safely clipped to the size of the array.
  8192. The objects that are removed will have their reference counts decreased,
  8193. and may be deleted if not referenced from elsewhere.
  8194. @param startIndex the index of the first object to remove
  8195. @param numberToRemove how many objects should be removed
  8196. @see remove, removeObject
  8197. */
  8198. void removeRange (const int startIndex,
  8199. const int numberToRemove)
  8200. {
  8201. const ScopedLockType lock (getLock());
  8202. const int start = jlimit (0, numUsed, startIndex);
  8203. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8204. if (end > start)
  8205. {
  8206. int i;
  8207. for (i = start; i < end; ++i)
  8208. {
  8209. if (data.elements[i] != 0)
  8210. {
  8211. data.elements[i]->decReferenceCount();
  8212. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8213. }
  8214. }
  8215. const int rangeSize = end - start;
  8216. ObjectClass** e = data.elements + start;
  8217. i = numUsed - end;
  8218. numUsed -= rangeSize;
  8219. while (--i >= 0)
  8220. {
  8221. *e = e [rangeSize];
  8222. ++e;
  8223. }
  8224. if ((numUsed << 1) < data.numAllocated)
  8225. minimiseStorageOverheads();
  8226. }
  8227. }
  8228. /** Removes the last n objects from the array.
  8229. The objects that are removed will have their reference counts decreased,
  8230. and may be deleted if not referenced from elsewhere.
  8231. @param howManyToRemove how many objects to remove from the end of the array
  8232. @see remove, removeObject, removeRange
  8233. */
  8234. void removeLast (int howManyToRemove = 1)
  8235. {
  8236. const ScopedLockType lock (getLock());
  8237. if (howManyToRemove > numUsed)
  8238. howManyToRemove = numUsed;
  8239. while (--howManyToRemove >= 0)
  8240. remove (numUsed - 1);
  8241. }
  8242. /** Swaps a pair of objects in the array.
  8243. If either of the indexes passed in is out-of-range, nothing will happen,
  8244. otherwise the two objects at these positions will be exchanged.
  8245. */
  8246. void swap (const int index1,
  8247. const int index2) throw()
  8248. {
  8249. const ScopedLockType lock (getLock());
  8250. if (((unsigned int) index1) < (unsigned int) numUsed
  8251. && ((unsigned int) index2) < (unsigned int) numUsed)
  8252. {
  8253. swapVariables (data.elements [index1],
  8254. data.elements [index2]);
  8255. }
  8256. }
  8257. /** Moves one of the objects to a different position.
  8258. This will move the object to a specified index, shuffling along
  8259. any intervening elements as required.
  8260. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8261. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8262. @param currentIndex the index of the object to be moved. If this isn't a
  8263. valid index, then nothing will be done
  8264. @param newIndex the index at which you'd like this object to end up. If this
  8265. is less than zero, it will be moved to the end of the array
  8266. */
  8267. void move (const int currentIndex,
  8268. int newIndex) throw()
  8269. {
  8270. if (currentIndex != newIndex)
  8271. {
  8272. const ScopedLockType lock (getLock());
  8273. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8274. {
  8275. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8276. newIndex = numUsed - 1;
  8277. ObjectClass* const value = data.elements [currentIndex];
  8278. if (newIndex > currentIndex)
  8279. {
  8280. memmove (data.elements + currentIndex,
  8281. data.elements + currentIndex + 1,
  8282. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8283. }
  8284. else
  8285. {
  8286. memmove (data.elements + newIndex + 1,
  8287. data.elements + newIndex,
  8288. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8289. }
  8290. data.elements [newIndex] = value;
  8291. }
  8292. }
  8293. }
  8294. /** This swaps the contents of this array with those of another array.
  8295. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8296. because it just swaps their internal pointers.
  8297. */
  8298. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  8299. {
  8300. const ScopedLockType lock1 (getLock());
  8301. const ScopedLockType lock2 (otherArray.getLock());
  8302. data.swapWith (otherArray.data);
  8303. swapVariables (numUsed, otherArray.numUsed);
  8304. }
  8305. /** Compares this array to another one.
  8306. @returns true only if the other array contains the same objects in the same order
  8307. */
  8308. bool operator== (const ReferenceCountedArray& other) const throw()
  8309. {
  8310. const ScopedLockType lock2 (other.getLock());
  8311. const ScopedLockType lock1 (getLock());
  8312. if (numUsed != other.numUsed)
  8313. return false;
  8314. for (int i = numUsed; --i >= 0;)
  8315. if (data.elements [i] != other.data.elements [i])
  8316. return false;
  8317. return true;
  8318. }
  8319. /** Compares this array to another one.
  8320. @see operator==
  8321. */
  8322. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8323. {
  8324. return ! operator== (other);
  8325. }
  8326. /** Sorts the elements in the array.
  8327. This will use a comparator object to sort the elements into order. The object
  8328. passed must have a method of the form:
  8329. @code
  8330. int compareElements (ElementType first, ElementType second);
  8331. @endcode
  8332. ..and this method must return:
  8333. - a value of < 0 if the first comes before the second
  8334. - a value of 0 if the two objects are equivalent
  8335. - a value of > 0 if the second comes before the first
  8336. To improve performance, the compareElements() method can be declared as static or const.
  8337. @param comparator the comparator to use for comparing elements.
  8338. @param retainOrderOfEquivalentItems if this is true, then items
  8339. which the comparator says are equivalent will be
  8340. kept in the order in which they currently appear
  8341. in the array. This is slower to perform, but may
  8342. be important in some cases. If it's false, a faster
  8343. algorithm is used, but equivalent elements may be
  8344. rearranged.
  8345. @see sortArray
  8346. */
  8347. template <class ElementComparator>
  8348. void sort (ElementComparator& comparator,
  8349. const bool retainOrderOfEquivalentItems = false) const throw()
  8350. {
  8351. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8352. // avoids getting warning messages about the parameter being unused
  8353. const ScopedLockType lock (getLock());
  8354. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8355. }
  8356. /** Reduces the amount of storage being used by the array.
  8357. Arrays typically allocate slightly more storage than they need, and after
  8358. removing elements, they may have quite a lot of unused space allocated.
  8359. This method will reduce the amount of allocated storage to a minimum.
  8360. */
  8361. void minimiseStorageOverheads() throw()
  8362. {
  8363. const ScopedLockType lock (getLock());
  8364. data.shrinkToNoMoreThan (numUsed);
  8365. }
  8366. /** Returns the CriticalSection that locks this array.
  8367. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8368. an object of ScopedLockType as an RAII lock for it.
  8369. */
  8370. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8371. /** Returns the type of scoped lock to use for locking this array */
  8372. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8373. juce_UseDebuggingNewOperator
  8374. private:
  8375. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8376. int numUsed;
  8377. };
  8378. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8379. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  8380. #endif
  8381. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8382. #endif
  8383. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8384. #endif
  8385. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8386. /*** Start of inlined file: juce_SortedSet.h ***/
  8387. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8388. #define __JUCE_SORTEDSET_JUCEHEADER__
  8389. #if JUCE_MSVC
  8390. #pragma warning (push)
  8391. #pragma warning (disable: 4512)
  8392. #endif
  8393. /**
  8394. Holds a set of unique primitive objects, such as ints or doubles.
  8395. A set can only hold one item with a given value, so if for example it's a
  8396. set of integers, attempting to add the same integer twice will do nothing
  8397. the second time.
  8398. Internally, the list of items is kept sorted (which means that whatever
  8399. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8400. to determine the order), and searching the set for known values is very fast
  8401. because it uses a binary-chop method.
  8402. Note that if you're using a class or struct as the element type, it must be
  8403. capable of being copied or moved with a straightforward memcpy, rather than
  8404. needing construction and destruction code.
  8405. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8406. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8407. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8408. */
  8409. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8410. class SortedSet
  8411. {
  8412. public:
  8413. /** Creates an empty set. */
  8414. SortedSet() throw()
  8415. : numUsed (0)
  8416. {
  8417. }
  8418. /** Creates a copy of another set.
  8419. @param other the set to copy
  8420. */
  8421. SortedSet (const SortedSet& other) throw()
  8422. {
  8423. const ScopedLockType lock (other.getLock());
  8424. numUsed = other.numUsed;
  8425. data.setAllocatedSize (other.numUsed);
  8426. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8427. }
  8428. /** Destructor. */
  8429. ~SortedSet() throw()
  8430. {
  8431. }
  8432. /** Copies another set over this one.
  8433. @param other the set to copy
  8434. */
  8435. SortedSet& operator= (const SortedSet& other) throw()
  8436. {
  8437. if (this != &other)
  8438. {
  8439. const ScopedLockType lock1 (other.getLock());
  8440. const ScopedLockType lock2 (getLock());
  8441. data.ensureAllocatedSize (other.size());
  8442. numUsed = other.numUsed;
  8443. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8444. minimiseStorageOverheads();
  8445. }
  8446. return *this;
  8447. }
  8448. /** Compares this set to another one.
  8449. Two sets are considered equal if they both contain the same set of
  8450. elements.
  8451. @param other the other set to compare with
  8452. */
  8453. bool operator== (const SortedSet<ElementType>& other) const throw()
  8454. {
  8455. const ScopedLockType lock (getLock());
  8456. if (numUsed != other.numUsed)
  8457. return false;
  8458. for (int i = numUsed; --i >= 0;)
  8459. if (data.elements[i] != other.data.elements[i])
  8460. return false;
  8461. return true;
  8462. }
  8463. /** Compares this set to another one.
  8464. Two sets are considered equal if they both contain the same set of
  8465. elements.
  8466. @param other the other set to compare with
  8467. */
  8468. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8469. {
  8470. return ! operator== (other);
  8471. }
  8472. /** Removes all elements from the set.
  8473. This will remove all the elements, and free any storage that the set is
  8474. using. To clear it without freeing the storage, use the clearQuick()
  8475. method instead.
  8476. @see clearQuick
  8477. */
  8478. void clear() throw()
  8479. {
  8480. const ScopedLockType lock (getLock());
  8481. data.setAllocatedSize (0);
  8482. numUsed = 0;
  8483. }
  8484. /** Removes all elements from the set without freeing the array's allocated storage.
  8485. @see clear
  8486. */
  8487. void clearQuick() throw()
  8488. {
  8489. const ScopedLockType lock (getLock());
  8490. numUsed = 0;
  8491. }
  8492. /** Returns the current number of elements in the set.
  8493. */
  8494. inline int size() const throw()
  8495. {
  8496. return numUsed;
  8497. }
  8498. /** Returns one of the elements in the set.
  8499. If the index passed in is beyond the range of valid elements, this
  8500. will return zero.
  8501. If you're certain that the index will always be a valid element, you
  8502. can call getUnchecked() instead, which is faster.
  8503. @param index the index of the element being requested (0 is the first element in the set)
  8504. @see getUnchecked, getFirst, getLast
  8505. */
  8506. inline ElementType operator[] (const int index) const throw()
  8507. {
  8508. const ScopedLockType lock (getLock());
  8509. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  8510. : ElementType();
  8511. }
  8512. /** Returns one of the elements in the set, without checking the index passed in.
  8513. Unlike the operator[] method, this will try to return an element without
  8514. checking that the index is within the bounds of the set, so should only
  8515. be used when you're confident that it will always be a valid index.
  8516. @param index the index of the element being requested (0 is the first element in the set)
  8517. @see operator[], getFirst, getLast
  8518. */
  8519. inline ElementType getUnchecked (const int index) const throw()
  8520. {
  8521. const ScopedLockType lock (getLock());
  8522. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8523. return data.elements [index];
  8524. }
  8525. /** Returns the first element in the set, or 0 if the set is empty.
  8526. @see operator[], getUnchecked, getLast
  8527. */
  8528. inline ElementType getFirst() const throw()
  8529. {
  8530. const ScopedLockType lock (getLock());
  8531. return numUsed > 0 ? data.elements [0] : ElementType();
  8532. }
  8533. /** Returns the last element in the set, or 0 if the set is empty.
  8534. @see operator[], getUnchecked, getFirst
  8535. */
  8536. inline ElementType getLast() const throw()
  8537. {
  8538. const ScopedLockType lock (getLock());
  8539. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  8540. }
  8541. /** Finds the index of the first element which matches the value passed in.
  8542. This will search the set for the given object, and return the index
  8543. of its first occurrence. If the object isn't found, the method will return -1.
  8544. @param elementToLookFor the value or object to look for
  8545. @returns the index of the object, or -1 if it's not found
  8546. */
  8547. int indexOf (const ElementType elementToLookFor) const throw()
  8548. {
  8549. const ScopedLockType lock (getLock());
  8550. int start = 0;
  8551. int end = numUsed;
  8552. for (;;)
  8553. {
  8554. if (start >= end)
  8555. {
  8556. return -1;
  8557. }
  8558. else if (elementToLookFor == data.elements [start])
  8559. {
  8560. return start;
  8561. }
  8562. else
  8563. {
  8564. const int halfway = (start + end) >> 1;
  8565. if (halfway == start)
  8566. return -1;
  8567. else if (elementToLookFor >= data.elements [halfway])
  8568. start = halfway;
  8569. else
  8570. end = halfway;
  8571. }
  8572. }
  8573. }
  8574. /** Returns true if the set contains at least one occurrence of an object.
  8575. @param elementToLookFor the value or object to look for
  8576. @returns true if the item is found
  8577. */
  8578. bool contains (const ElementType elementToLookFor) const throw()
  8579. {
  8580. const ScopedLockType lock (getLock());
  8581. int start = 0;
  8582. int end = numUsed;
  8583. for (;;)
  8584. {
  8585. if (start >= end)
  8586. {
  8587. return false;
  8588. }
  8589. else if (elementToLookFor == data.elements [start])
  8590. {
  8591. return true;
  8592. }
  8593. else
  8594. {
  8595. const int halfway = (start + end) >> 1;
  8596. if (halfway == start)
  8597. return false;
  8598. else if (elementToLookFor >= data.elements [halfway])
  8599. start = halfway;
  8600. else
  8601. end = halfway;
  8602. }
  8603. }
  8604. }
  8605. /** Adds a new element to the set, (as long as it's not already in there).
  8606. @param newElement the new object to add to the set
  8607. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8608. */
  8609. void add (const ElementType newElement) throw()
  8610. {
  8611. const ScopedLockType lock (getLock());
  8612. int start = 0;
  8613. int end = numUsed;
  8614. for (;;)
  8615. {
  8616. if (start >= end)
  8617. {
  8618. jassert (start <= end);
  8619. insertInternal (start, newElement);
  8620. break;
  8621. }
  8622. else if (newElement == data.elements [start])
  8623. {
  8624. break;
  8625. }
  8626. else
  8627. {
  8628. const int halfway = (start + end) >> 1;
  8629. if (halfway == start)
  8630. {
  8631. if (newElement >= data.elements [halfway])
  8632. insertInternal (start + 1, newElement);
  8633. else
  8634. insertInternal (start, newElement);
  8635. break;
  8636. }
  8637. else if (newElement >= data.elements [halfway])
  8638. start = halfway;
  8639. else
  8640. end = halfway;
  8641. }
  8642. }
  8643. }
  8644. /** Adds elements from an array to this set.
  8645. @param elementsToAdd the array of elements to add
  8646. @param numElementsToAdd how many elements are in this other array
  8647. @see add
  8648. */
  8649. void addArray (const ElementType* elementsToAdd,
  8650. int numElementsToAdd) throw()
  8651. {
  8652. const ScopedLockType lock (getLock());
  8653. while (--numElementsToAdd >= 0)
  8654. add (*elementsToAdd++);
  8655. }
  8656. /** Adds elements from another set to this one.
  8657. @param setToAddFrom the set from which to copy the elements
  8658. @param startIndex the first element of the other set to start copying from
  8659. @param numElementsToAdd how many elements to add from the other set. If this
  8660. value is negative or greater than the number of available elements,
  8661. all available elements will be copied.
  8662. @see add
  8663. */
  8664. template <class OtherSetType>
  8665. void addSet (const OtherSetType& setToAddFrom,
  8666. int startIndex = 0,
  8667. int numElementsToAdd = -1) throw()
  8668. {
  8669. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  8670. const ScopedLockType lock2 (getLock());
  8671. jassert (this != &setToAddFrom);
  8672. if (this != &setToAddFrom)
  8673. {
  8674. if (startIndex < 0)
  8675. {
  8676. jassertfalse;
  8677. startIndex = 0;
  8678. }
  8679. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8680. numElementsToAdd = setToAddFrom.size() - startIndex;
  8681. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8682. }
  8683. }
  8684. /** Removes an element from the set.
  8685. This will remove the element at a given index.
  8686. If the index passed in is out-of-range, nothing will happen.
  8687. @param indexToRemove the index of the element to remove
  8688. @returns the element that has been removed
  8689. @see removeValue, removeRange
  8690. */
  8691. ElementType remove (const int indexToRemove) throw()
  8692. {
  8693. const ScopedLockType lock (getLock());
  8694. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8695. {
  8696. --numUsed;
  8697. ElementType* const e = data.elements + indexToRemove;
  8698. ElementType const removed = *e;
  8699. const int numberToShift = numUsed - indexToRemove;
  8700. if (numberToShift > 0)
  8701. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8702. if ((numUsed << 1) < data.numAllocated)
  8703. minimiseStorageOverheads();
  8704. return removed;
  8705. }
  8706. return 0;
  8707. }
  8708. /** Removes an item from the set.
  8709. This will remove the given element from the set, if it's there.
  8710. @param valueToRemove the object to try to remove
  8711. @see remove, removeRange
  8712. */
  8713. void removeValue (const ElementType valueToRemove) throw()
  8714. {
  8715. const ScopedLockType lock (getLock());
  8716. remove (indexOf (valueToRemove));
  8717. }
  8718. /** Removes any elements which are also in another set.
  8719. @param otherSet the other set in which to look for elements to remove
  8720. @see removeValuesNotIn, remove, removeValue, removeRange
  8721. */
  8722. template <class OtherSetType>
  8723. void removeValuesIn (const OtherSetType& otherSet) throw()
  8724. {
  8725. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8726. const ScopedLockType lock2 (getLock());
  8727. if (this == &otherSet)
  8728. {
  8729. clear();
  8730. }
  8731. else
  8732. {
  8733. if (otherSet.size() > 0)
  8734. {
  8735. for (int i = numUsed; --i >= 0;)
  8736. if (otherSet.contains (data.elements [i]))
  8737. remove (i);
  8738. }
  8739. }
  8740. }
  8741. /** Removes any elements which are not found in another set.
  8742. Only elements which occur in this other set will be retained.
  8743. @param otherSet the set in which to look for elements NOT to remove
  8744. @see removeValuesIn, remove, removeValue, removeRange
  8745. */
  8746. template <class OtherSetType>
  8747. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8748. {
  8749. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8750. const ScopedLockType lock2 (getLock());
  8751. if (this != &otherSet)
  8752. {
  8753. if (otherSet.size() <= 0)
  8754. {
  8755. clear();
  8756. }
  8757. else
  8758. {
  8759. for (int i = numUsed; --i >= 0;)
  8760. if (! otherSet.contains (data.elements [i]))
  8761. remove (i);
  8762. }
  8763. }
  8764. }
  8765. /** Reduces the amount of storage being used by the set.
  8766. Sets typically allocate slightly more storage than they need, and after
  8767. removing elements, they may have quite a lot of unused space allocated.
  8768. This method will reduce the amount of allocated storage to a minimum.
  8769. */
  8770. void minimiseStorageOverheads() throw()
  8771. {
  8772. const ScopedLockType lock (getLock());
  8773. data.shrinkToNoMoreThan (numUsed);
  8774. }
  8775. /** Returns the CriticalSection that locks this array.
  8776. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8777. an object of ScopedLockType as an RAII lock for it.
  8778. */
  8779. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8780. /** Returns the type of scoped lock to use for locking this array */
  8781. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8782. juce_UseDebuggingNewOperator
  8783. private:
  8784. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  8785. int numUsed;
  8786. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8787. {
  8788. data.ensureAllocatedSize (numUsed + 1);
  8789. ElementType* const insertPos = data.elements + indexToInsertAt;
  8790. const int numberToMove = numUsed - indexToInsertAt;
  8791. if (numberToMove > 0)
  8792. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8793. *insertPos = newElement;
  8794. ++numUsed;
  8795. }
  8796. };
  8797. #if JUCE_MSVC
  8798. #pragma warning (pop)
  8799. #endif
  8800. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8801. /*** End of inlined file: juce_SortedSet.h ***/
  8802. #endif
  8803. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8804. /*** Start of inlined file: juce_SparseSet.h ***/
  8805. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8806. #define __JUCE_SPARSESET_JUCEHEADER__
  8807. /**
  8808. Holds a set of primitive values, storing them as a set of ranges.
  8809. This container acts like an array, but can efficiently hold large continguous
  8810. ranges of values. It's quite a specialised class, mostly useful for things
  8811. like keeping the set of selected rows in a listbox.
  8812. The type used as a template paramter must be an integer type, such as int, short,
  8813. int64, etc.
  8814. */
  8815. template <class Type>
  8816. class SparseSet
  8817. {
  8818. public:
  8819. /** Creates a new empty set. */
  8820. SparseSet()
  8821. {
  8822. }
  8823. /** Creates a copy of another SparseSet. */
  8824. SparseSet (const SparseSet<Type>& other)
  8825. : values (other.values)
  8826. {
  8827. }
  8828. /** Destructor. */
  8829. ~SparseSet()
  8830. {
  8831. }
  8832. /** Clears the set. */
  8833. void clear()
  8834. {
  8835. values.clear();
  8836. }
  8837. /** Checks whether the set is empty.
  8838. This is much quicker than using (size() == 0).
  8839. */
  8840. bool isEmpty() const throw()
  8841. {
  8842. return values.size() == 0;
  8843. }
  8844. /** Returns the number of values in the set.
  8845. Because of the way the data is stored, this method can take longer if there
  8846. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8847. are any items.
  8848. */
  8849. Type size() const
  8850. {
  8851. Type total (0);
  8852. for (int i = 0; i < values.size(); i += 2)
  8853. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  8854. return total;
  8855. }
  8856. /** Returns one of the values in the set.
  8857. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8858. @returns the value at this index, or 0 if it's out-of-range
  8859. */
  8860. Type operator[] (Type index) const
  8861. {
  8862. for (int i = 0; i < values.size(); i += 2)
  8863. {
  8864. const Type start (values.getUnchecked (i));
  8865. const Type len (values.getUnchecked (i + 1) - start);
  8866. if (index < len)
  8867. return start + index;
  8868. index -= len;
  8869. }
  8870. return Type (0);
  8871. }
  8872. /** Checks whether a particular value is in the set. */
  8873. bool contains (const Type valueToLookFor) const
  8874. {
  8875. for (int i = 0; i < values.size(); ++i)
  8876. if (valueToLookFor < values.getUnchecked(i))
  8877. return (i & 1) != 0;
  8878. return false;
  8879. }
  8880. /** Returns the number of contiguous blocks of values.
  8881. @see getRange
  8882. */
  8883. int getNumRanges() const throw()
  8884. {
  8885. return values.size() >> 1;
  8886. }
  8887. /** Returns one of the contiguous ranges of values stored.
  8888. @param rangeIndex the index of the range to look up, between 0
  8889. and (getNumRanges() - 1)
  8890. @see getTotalRange
  8891. */
  8892. const Range<Type> getRange (const int rangeIndex) const
  8893. {
  8894. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8895. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  8896. values.getUnchecked ((rangeIndex << 1) + 1));
  8897. else
  8898. return Range<Type>();
  8899. }
  8900. /** Returns the range between the lowest and highest values in the set.
  8901. @see getRange
  8902. */
  8903. const Range<Type> getTotalRange() const
  8904. {
  8905. if (values.size() > 0)
  8906. {
  8907. jassert ((values.size() & 1) == 0);
  8908. return Range<Type> (values.getUnchecked (0),
  8909. values.getUnchecked (values.size() - 1));
  8910. }
  8911. return Range<Type>();
  8912. }
  8913. /** Adds a range of contiguous values to the set.
  8914. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  8915. */
  8916. void addRange (const Range<Type>& range)
  8917. {
  8918. jassert (range.getLength() >= 0);
  8919. if (range.getLength() > 0)
  8920. {
  8921. removeRange (range);
  8922. values.addUsingDefaultSort (range.getStart());
  8923. values.addUsingDefaultSort (range.getEnd());
  8924. simplify();
  8925. }
  8926. }
  8927. /** Removes a range of values from the set.
  8928. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  8929. */
  8930. void removeRange (const Range<Type>& rangeToRemove)
  8931. {
  8932. jassert (rangeToRemove.getLength() >= 0);
  8933. if (rangeToRemove.getLength() > 0
  8934. && values.size() > 0
  8935. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  8936. && values.getUnchecked(0) < rangeToRemove.getEnd())
  8937. {
  8938. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  8939. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  8940. const bool onAtEnd = contains (lastValue);
  8941. for (int i = values.size(); --i >= 0;)
  8942. {
  8943. if (values.getUnchecked(i) <= lastValue)
  8944. {
  8945. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  8946. {
  8947. values.remove (i);
  8948. if (--i < 0)
  8949. break;
  8950. }
  8951. break;
  8952. }
  8953. }
  8954. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  8955. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  8956. simplify();
  8957. }
  8958. }
  8959. /** Does an XOR of the values in a given range. */
  8960. void invertRange (const Range<Type>& range)
  8961. {
  8962. SparseSet newItems;
  8963. newItems.addRange (range);
  8964. int i;
  8965. for (i = getNumRanges(); --i >= 0;)
  8966. newItems.removeRange (getRange (i));
  8967. removeRange (range);
  8968. for (i = newItems.getNumRanges(); --i >= 0;)
  8969. addRange (newItems.getRange(i));
  8970. }
  8971. /** Checks whether any part of a given range overlaps any part of this set. */
  8972. bool overlapsRange (const Range<Type>& range)
  8973. {
  8974. if (range.getLength() > 0)
  8975. {
  8976. for (int i = getNumRanges(); --i >= 0;)
  8977. {
  8978. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8979. return false;
  8980. if (values.getUnchecked (i << 1) < range.getEnd())
  8981. return true;
  8982. }
  8983. }
  8984. return false;
  8985. }
  8986. /** Checks whether the whole of a given range is contained within this one. */
  8987. bool containsRange (const Range<Type>& range)
  8988. {
  8989. if (range.getLength() > 0)
  8990. {
  8991. for (int i = getNumRanges(); --i >= 0;)
  8992. {
  8993. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8994. return false;
  8995. if (values.getUnchecked (i << 1) <= range.getStart()
  8996. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  8997. return true;
  8998. }
  8999. }
  9000. return false;
  9001. }
  9002. bool operator== (const SparseSet<Type>& other) throw()
  9003. {
  9004. return values == other.values;
  9005. }
  9006. bool operator!= (const SparseSet<Type>& other) throw()
  9007. {
  9008. return values != other.values;
  9009. }
  9010. juce_UseDebuggingNewOperator
  9011. private:
  9012. // alternating start/end values of ranges of values that are present.
  9013. Array<Type, DummyCriticalSection> values;
  9014. void simplify()
  9015. {
  9016. jassert ((values.size() & 1) == 0);
  9017. for (int i = values.size(); --i > 0;)
  9018. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  9019. values.removeRange (--i, 2);
  9020. }
  9021. };
  9022. #endif // __JUCE_SPARSESET_JUCEHEADER__
  9023. /*** End of inlined file: juce_SparseSet.h ***/
  9024. #endif
  9025. #ifndef __JUCE_VALUE_JUCEHEADER__
  9026. /*** Start of inlined file: juce_Value.h ***/
  9027. #ifndef __JUCE_VALUE_JUCEHEADER__
  9028. #define __JUCE_VALUE_JUCEHEADER__
  9029. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  9030. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  9031. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  9032. /*** Start of inlined file: juce_MessageListener.h ***/
  9033. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  9034. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  9035. /*** Start of inlined file: juce_Message.h ***/
  9036. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  9037. #define __JUCE_MESSAGE_JUCEHEADER__
  9038. class MessageListener;
  9039. class MessageManager;
  9040. /** The base class for objects that can be delivered to a MessageListener.
  9041. The simplest Message object contains a few integer and pointer parameters
  9042. that the user can set, and this is enough for a lot of purposes. For passing more
  9043. complex data, subclasses of Message can also be used.
  9044. @see MessageListener, MessageManager, ActionListener, ChangeListener
  9045. */
  9046. class JUCE_API Message
  9047. {
  9048. public:
  9049. /** Creates an uninitialised message.
  9050. The class's variables will also be left uninitialised.
  9051. */
  9052. Message() throw();
  9053. /** Creates a message object, filling in the member variables.
  9054. The corresponding public member variables will be set from the parameters
  9055. passed in.
  9056. */
  9057. Message (int intParameter1,
  9058. int intParameter2,
  9059. int intParameter3,
  9060. void* pointerParameter) throw();
  9061. /** Destructor. */
  9062. virtual ~Message() throw();
  9063. // These values can be used for carrying simple data that the application needs to
  9064. // pass around. For more complex messages, just create a subclass.
  9065. int intParameter1; /**< user-defined integer value. */
  9066. int intParameter2; /**< user-defined integer value. */
  9067. int intParameter3; /**< user-defined integer value. */
  9068. void* pointerParameter; /**< user-defined pointer value. */
  9069. juce_UseDebuggingNewOperator
  9070. private:
  9071. friend class MessageListener;
  9072. friend class MessageManager;
  9073. MessageListener* messageRecipient;
  9074. Message (const Message&);
  9075. Message& operator= (const Message&);
  9076. };
  9077. #endif // __JUCE_MESSAGE_JUCEHEADER__
  9078. /*** End of inlined file: juce_Message.h ***/
  9079. /**
  9080. MessageListener subclasses can post and receive Message objects.
  9081. @see Message, MessageManager, ActionListener, ChangeListener
  9082. */
  9083. class JUCE_API MessageListener
  9084. {
  9085. protected:
  9086. /** Creates a MessageListener. */
  9087. MessageListener() throw();
  9088. public:
  9089. /** Destructor.
  9090. When a MessageListener is deleted, it removes itself from a global list
  9091. of registered listeners, so that the isValidMessageListener() method
  9092. will no longer return true.
  9093. */
  9094. virtual ~MessageListener();
  9095. /** This is the callback method that receives incoming messages.
  9096. This is called by the MessageManager from its dispatch loop.
  9097. @see postMessage
  9098. */
  9099. virtual void handleMessage (const Message& message) = 0;
  9100. /** Sends a message to the message queue, for asynchronous delivery to this listener
  9101. later on.
  9102. This method can be called safely by any thread.
  9103. @param message the message object to send - this will be deleted
  9104. automatically by the message queue, so don't keep any
  9105. references to it after calling this method.
  9106. @see handleMessage
  9107. */
  9108. void postMessage (Message* message) const throw();
  9109. /** Checks whether this MessageListener has been deleted.
  9110. Although not foolproof, this method is safe to call on dangling or null
  9111. pointers. A list of active MessageListeners is kept internally, so this
  9112. checks whether the object is on this list or not.
  9113. Note that it's possible to get a false-positive here, if an object is
  9114. deleted and another is subsequently created that happens to be at the
  9115. exact same memory location, but I can't think of a good way of avoiding
  9116. this.
  9117. */
  9118. bool isValidMessageListener() const throw();
  9119. };
  9120. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  9121. /*** End of inlined file: juce_MessageListener.h ***/
  9122. /**
  9123. Has a callback method that is triggered asynchronously.
  9124. This object allows an asynchronous callback function to be triggered, for
  9125. tasks such as coalescing multiple updates into a single callback later on.
  9126. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  9127. message thread calling handleAsyncUpdate() as soon as it can.
  9128. */
  9129. class JUCE_API AsyncUpdater
  9130. {
  9131. public:
  9132. /** Creates an AsyncUpdater object. */
  9133. AsyncUpdater() throw();
  9134. /** Destructor.
  9135. If there are any pending callbacks when the object is deleted, these are lost.
  9136. */
  9137. virtual ~AsyncUpdater();
  9138. /** Causes the callback to be triggered at a later time.
  9139. This method returns immediately, having made sure that a callback
  9140. to the handleAsyncUpdate() method will occur as soon as possible.
  9141. If an update callback is already pending but hasn't happened yet, calls
  9142. to this method will be ignored.
  9143. It's thread-safe to call this method from any number of threads without
  9144. needing to worry about locking.
  9145. */
  9146. void triggerAsyncUpdate() throw();
  9147. /** This will stop any pending updates from happening.
  9148. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  9149. callback happens, this will cancel the handleAsyncUpdate() callback.
  9150. */
  9151. void cancelPendingUpdate() throw();
  9152. /** If an update has been triggered and is pending, this will invoke it
  9153. synchronously.
  9154. Use this as a kind of "flush" operation - if an update is pending, the
  9155. handleAsyncUpdate() method will be called immediately; if no update is
  9156. pending, then nothing will be done.
  9157. */
  9158. void handleUpdateNowIfNeeded();
  9159. /** Called back to do whatever your class needs to do.
  9160. This method is called by the message thread at the next convenient time
  9161. after the triggerAsyncUpdate() method has been called.
  9162. */
  9163. virtual void handleAsyncUpdate() = 0;
  9164. private:
  9165. class AsyncUpdaterInternal : public MessageListener
  9166. {
  9167. public:
  9168. AsyncUpdaterInternal() throw() {}
  9169. ~AsyncUpdaterInternal() {}
  9170. void handleMessage (const Message&);
  9171. AsyncUpdater* owner;
  9172. private:
  9173. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  9174. AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  9175. };
  9176. AsyncUpdaterInternal internalAsyncHandler;
  9177. bool asyncMessagePending;
  9178. };
  9179. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  9180. /*** End of inlined file: juce_AsyncUpdater.h ***/
  9181. /*** Start of inlined file: juce_ListenerList.h ***/
  9182. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  9183. #define __JUCE_LISTENERLIST_JUCEHEADER__
  9184. /**
  9185. Holds a set of objects and can invoke a member function callback on each object
  9186. in the set with a single call.
  9187. Use a ListenerList to manage a set of objects which need a callback, and you
  9188. can invoke a member function by simply calling call() or callChecked().
  9189. E.g.
  9190. @code
  9191. class MyListenerType
  9192. {
  9193. public:
  9194. void myCallbackMethod (int foo, bool bar);
  9195. };
  9196. ListenerList <MyListenerType> listeners;
  9197. listeners.add (someCallbackObjects...);
  9198. // This will invoke myCallbackMethod (1234, true) on each of the objects
  9199. // in the list...
  9200. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  9201. @endcode
  9202. If you add or remove listeners from the list during one of the callbacks - i.e. while
  9203. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  9204. will be mistakenly called after they've been removed, but it may mean that some of the
  9205. listeners could be called more than once, or not at all, depending on the list's order.
  9206. Sometimes, there's a chance that invoking one of the callbacks might result in the
  9207. list itself being deleted while it's still iterating - to survive this situation, you can
  9208. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  9209. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  9210. the list will check this after each callback to determine whether it should abort the
  9211. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  9212. which can be used to check when a Component has been deleted. See also
  9213. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  9214. */
  9215. template <class ListenerClass,
  9216. class ArrayType = Array <ListenerClass*> >
  9217. class ListenerList
  9218. {
  9219. // Horrible macros required to support VC6/7..
  9220. #if defined (_MSC_VER) && _MSC_VER <= 1400
  9221. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  9222. #define LL_PARAM(a) Q##a& param##a
  9223. #else
  9224. #define LL_TEMPLATE(a) typename P##a
  9225. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  9226. #endif
  9227. public:
  9228. /** Creates an empty list. */
  9229. ListenerList()
  9230. {
  9231. }
  9232. /** Destructor. */
  9233. ~ListenerList()
  9234. {
  9235. }
  9236. /** Adds a listener to the list.
  9237. A listener can only be added once, so if the listener is already in the list,
  9238. this method has no effect.
  9239. @see remove
  9240. */
  9241. void add (ListenerClass* const listenerToAdd)
  9242. {
  9243. // Listeners can't be null pointers!
  9244. jassert (listenerToAdd != 0);
  9245. if (listenerToAdd != 0)
  9246. listeners.addIfNotAlreadyThere (listenerToAdd);
  9247. }
  9248. /** Removes a listener from the list.
  9249. If the listener wasn't in the list, this has no effect.
  9250. */
  9251. void remove (ListenerClass* const listenerToRemove)
  9252. {
  9253. // Listeners can't be null pointers!
  9254. jassert (listenerToRemove != 0);
  9255. listeners.removeValue (listenerToRemove);
  9256. }
  9257. /** Returns the number of registered listeners. */
  9258. int size() const throw()
  9259. {
  9260. return listeners.size();
  9261. }
  9262. /** Returns true if any listeners are registered. */
  9263. bool isEmpty() const throw()
  9264. {
  9265. return listeners.size() == 0;
  9266. }
  9267. /** Returns true if the specified listener has been added to the list. */
  9268. bool contains (ListenerClass* const listener) const throw()
  9269. {
  9270. return listeners.contains (listener);
  9271. }
  9272. /** Calls a member function on each listener in the list, with no parameters. */
  9273. void call (void (ListenerClass::*callbackFunction) ())
  9274. {
  9275. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  9276. }
  9277. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  9278. See the class description for info about writing a bail-out checker. */
  9279. template <class BailOutCheckerType>
  9280. void callChecked (const BailOutCheckerType& bailOutChecker,
  9281. void (ListenerClass::*callbackFunction) ())
  9282. {
  9283. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9284. (iter.getListener()->*callbackFunction) ();
  9285. }
  9286. /** Calls a member function on each listener in the list, with 1 parameter. */
  9287. template <LL_TEMPLATE(1)>
  9288. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  9289. {
  9290. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9291. (iter.getListener()->*callbackFunction) (param1);
  9292. }
  9293. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  9294. See the class description for info about writing a bail-out checker. */
  9295. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  9296. void callChecked (const BailOutCheckerType& bailOutChecker,
  9297. void (ListenerClass::*callbackFunction) (P1),
  9298. LL_PARAM(1))
  9299. {
  9300. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9301. (iter.getListener()->*callbackFunction) (param1);
  9302. }
  9303. /** Calls a member function on each listener in the list, with 2 parameters. */
  9304. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9305. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  9306. LL_PARAM(1), LL_PARAM(2))
  9307. {
  9308. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9309. (iter.getListener()->*callbackFunction) (param1, param2);
  9310. }
  9311. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  9312. See the class description for info about writing a bail-out checker. */
  9313. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9314. void callChecked (const BailOutCheckerType& bailOutChecker,
  9315. void (ListenerClass::*callbackFunction) (P1, P2),
  9316. LL_PARAM(1), LL_PARAM(2))
  9317. {
  9318. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9319. (iter.getListener()->*callbackFunction) (param1, param2);
  9320. }
  9321. /** Calls a member function on each listener in the list, with 3 parameters. */
  9322. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9323. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9324. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9325. {
  9326. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9327. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9328. }
  9329. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  9330. See the class description for info about writing a bail-out checker. */
  9331. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9332. void callChecked (const BailOutCheckerType& bailOutChecker,
  9333. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9334. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9335. {
  9336. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9337. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9338. }
  9339. /** Calls a member function on each listener in the list, with 4 parameters. */
  9340. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9341. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9342. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9343. {
  9344. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9345. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9346. }
  9347. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  9348. See the class description for info about writing a bail-out checker. */
  9349. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9350. void callChecked (const BailOutCheckerType& bailOutChecker,
  9351. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9352. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9353. {
  9354. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9355. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9356. }
  9357. /** Calls a member function on each listener in the list, with 5 parameters. */
  9358. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9359. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9360. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9361. {
  9362. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9363. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9364. }
  9365. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  9366. See the class description for info about writing a bail-out checker. */
  9367. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9368. void callChecked (const BailOutCheckerType& bailOutChecker,
  9369. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9370. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9371. {
  9372. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9373. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9374. }
  9375. /** A dummy bail-out checker that always returns false.
  9376. See the ListenerList notes for more info about bail-out checkers.
  9377. */
  9378. class DummyBailOutChecker
  9379. {
  9380. public:
  9381. inline bool shouldBailOut() const throw() { return false; }
  9382. };
  9383. /** Iterates the listeners in a ListenerList. */
  9384. template <class BailOutCheckerType, class ListType>
  9385. class Iterator
  9386. {
  9387. public:
  9388. Iterator (const ListType& list_, const BailOutCheckerType& bailOutChecker_)
  9389. : list (list_), bailOutChecker (bailOutChecker_), index (list_.size())
  9390. {}
  9391. ~Iterator() {}
  9392. bool next()
  9393. {
  9394. if (index <= 0 || bailOutChecker.shouldBailOut())
  9395. return false;
  9396. const int listSize = list.size();
  9397. if (--index < listSize)
  9398. return true;
  9399. index = listSize - 1;
  9400. return index >= 0;
  9401. }
  9402. typename ListType::ListenerType* getListener() const throw()
  9403. {
  9404. return list.getListeners().getUnchecked (index);
  9405. }
  9406. private:
  9407. const ListType& list;
  9408. const BailOutCheckerType& bailOutChecker;
  9409. int index;
  9410. Iterator (const Iterator&);
  9411. Iterator& operator= (const Iterator&);
  9412. };
  9413. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  9414. typedef ListenerClass ListenerType;
  9415. const ArrayType& getListeners() const throw() { return listeners; }
  9416. private:
  9417. ArrayType listeners;
  9418. ListenerList (const ListenerList&);
  9419. ListenerList& operator= (const ListenerList&);
  9420. #undef LL_TEMPLATE
  9421. #undef LL_PARAM
  9422. };
  9423. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  9424. /*** End of inlined file: juce_ListenerList.h ***/
  9425. /**
  9426. Represents a shared variant value.
  9427. A Value object contains a reference to a var object, and can get and set its value.
  9428. Listeners can be attached to be told when the value is changed.
  9429. The Value class is a wrapper around a shared, reference-counted underlying data
  9430. object - this means that multiple Value objects can all refer to the same piece of
  9431. data, allowing all of them to be notified when any of them changes it.
  9432. When you create a Value with its default constructor, it acts as a wrapper around a
  9433. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  9434. you can map the Value onto any kind of underlying data.
  9435. */
  9436. class JUCE_API Value
  9437. {
  9438. public:
  9439. /** Creates an empty Value, containing a void var. */
  9440. Value();
  9441. /** Creates a Value that refers to the same value as another one.
  9442. Note that this doesn't make a copy of the other value - both this and the other
  9443. Value will share the same underlying value, so that when either one alters it, both
  9444. will see it change.
  9445. */
  9446. Value (const Value& other);
  9447. /** Creates a Value that is set to the specified value. */
  9448. explicit Value (const var& initialValue);
  9449. /** Destructor. */
  9450. ~Value();
  9451. /** Returns the current value. */
  9452. const var getValue() const;
  9453. /** Returns the current value. */
  9454. operator const var() const;
  9455. /** Returns the value as a string.
  9456. This is alternative to writing things like "myValue.getValue().toString()".
  9457. */
  9458. const String toString() const;
  9459. /** Sets the current value.
  9460. You can also use operator= to set the value.
  9461. If there are any listeners registered, they will be notified of the
  9462. change asynchronously.
  9463. */
  9464. void setValue (const var& newValue);
  9465. /** Sets the current value.
  9466. This is the same as calling setValue().
  9467. If there are any listeners registered, they will be notified of the
  9468. change asynchronously.
  9469. */
  9470. Value& operator= (const var& newValue);
  9471. /** Makes this object refer to the same underlying ValueSource as another one.
  9472. Once this object has been connected to another one, changing either one
  9473. will update the other.
  9474. Existing listeners will still be registered after you call this method, and
  9475. they'll continue to receive messages when the new value changes.
  9476. */
  9477. void referTo (const Value& valueToReferTo);
  9478. /** Returns true if this value and the other one are references to the same value.
  9479. */
  9480. bool refersToSameSourceAs (const Value& other) const;
  9481. /** Compares two values.
  9482. This is a compare-by-value comparison, so is effectively the same as
  9483. saying (this->getValue() == other.getValue()).
  9484. */
  9485. bool operator== (const Value& other) const;
  9486. /** Compares two values.
  9487. This is a compare-by-value comparison, so is effectively the same as
  9488. saying (this->getValue() != other.getValue()).
  9489. */
  9490. bool operator!= (const Value& other) const;
  9491. /** Receives callbacks when a Value object changes.
  9492. @see Value::addListener
  9493. */
  9494. class JUCE_API Listener
  9495. {
  9496. public:
  9497. Listener() {}
  9498. virtual ~Listener() {}
  9499. /** Called when a Value object is changed.
  9500. Note that the Value object passed as a parameter may not be exactly the same
  9501. object that you registered the listener with - it might be a copy that refers
  9502. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  9503. */
  9504. virtual void valueChanged (Value& value) = 0;
  9505. };
  9506. /** Adds a listener to receive callbacks when the value changes.
  9507. The listener is added to this specific Value object, and not to the shared
  9508. object that it refers to. When this object is deleted, all the listeners will
  9509. be lost, even if other references to the same Value still exist. So when you're
  9510. adding a listener, make sure that you add it to a ValueTree instance that will last
  9511. for as long as you need the listener. In general, you'd never want to add a listener
  9512. to a local stack-based ValueTree, but more likely to one that's a member variable.
  9513. @see removeListener
  9514. */
  9515. void addListener (Listener* listener);
  9516. /** Removes a listener that was previously added with addListener(). */
  9517. void removeListener (Listener* listener);
  9518. /**
  9519. Used internally by the Value class as the base class for its shared value objects.
  9520. The Value class is essentially a reference-counted pointer to a shared instance
  9521. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  9522. ValueSource classes to allow Value objects to represent your own custom data items.
  9523. */
  9524. class JUCE_API ValueSource : public ReferenceCountedObject,
  9525. public AsyncUpdater
  9526. {
  9527. public:
  9528. ValueSource();
  9529. virtual ~ValueSource();
  9530. /** Returns the current value of this object. */
  9531. virtual const var getValue() const = 0;
  9532. /** Changes the current value.
  9533. This must also trigger a change message if the value actually changes.
  9534. */
  9535. virtual void setValue (const var& newValue) = 0;
  9536. /** Delivers a change message to all the listeners that are registered with
  9537. this value.
  9538. If dispatchSynchronously is true, the method will call all the listeners
  9539. before returning; otherwise it'll dispatch a message and make the call later.
  9540. */
  9541. void sendChangeMessage (bool dispatchSynchronously);
  9542. juce_UseDebuggingNewOperator
  9543. protected:
  9544. friend class Value;
  9545. SortedSet <Value*> valuesWithListeners;
  9546. void handleAsyncUpdate();
  9547. ValueSource (const ValueSource&);
  9548. ValueSource& operator= (const ValueSource&);
  9549. };
  9550. /** Creates a Value object that uses this valueSource object as its underlying data. */
  9551. explicit Value (ValueSource* valueSource);
  9552. /** Returns the ValueSource that this value is referring to. */
  9553. ValueSource& getValueSource() throw() { return *value; }
  9554. juce_UseDebuggingNewOperator
  9555. private:
  9556. friend class ValueSource;
  9557. ReferenceCountedObjectPtr <ValueSource> value;
  9558. ListenerList <Listener> listeners;
  9559. void callListeners();
  9560. // This is disallowed to avoid confusion about whether it should
  9561. // do a by-value or by-reference copy.
  9562. Value& operator= (const Value& other);
  9563. };
  9564. /** Writes a Value to an OutputStream as a UTF8 string. */
  9565. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  9566. #endif // __JUCE_VALUE_JUCEHEADER__
  9567. /*** End of inlined file: juce_Value.h ***/
  9568. #endif
  9569. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9570. /*** Start of inlined file: juce_ValueTree.h ***/
  9571. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9572. #define __JUCE_VALUETREE_JUCEHEADER__
  9573. /*** Start of inlined file: juce_UndoManager.h ***/
  9574. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  9575. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  9576. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  9577. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9578. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9579. /*** Start of inlined file: juce_ChangeListenerList.h ***/
  9580. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9581. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9582. /*** Start of inlined file: juce_ChangeListener.h ***/
  9583. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  9584. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  9585. /**
  9586. Receives callbacks about changes to some kind of object.
  9587. Many objects use a ChangeListenerList to keep a set of listeners which they
  9588. will inform when something changes. A subclass of ChangeListener
  9589. is used to receive these callbacks.
  9590. Note that the major difference between an ActionListener and a ChangeListener
  9591. is that for a ChangeListener, multiple changes will be coalesced into fewer
  9592. callbacks, but ActionListeners perform one callback for every event posted.
  9593. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  9594. */
  9595. class JUCE_API ChangeListener
  9596. {
  9597. public:
  9598. /** Destructor. */
  9599. virtual ~ChangeListener() {}
  9600. /** Overridden by your subclass to receive the callback.
  9601. @param objectThatHasChanged the value that was passed to the
  9602. ChangeListenerList::sendChangeMessage() method
  9603. */
  9604. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  9605. };
  9606. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  9607. /*** End of inlined file: juce_ChangeListener.h ***/
  9608. /*** Start of inlined file: juce_ScopedLock.h ***/
  9609. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  9610. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  9611. /**
  9612. Automatically locks and unlocks a CriticalSection object.
  9613. Use one of these as a local variable to control access to a CriticalSection.
  9614. e.g. @code
  9615. CriticalSection myCriticalSection;
  9616. for (;;)
  9617. {
  9618. const ScopedLock myScopedLock (myCriticalSection);
  9619. // myCriticalSection is now locked
  9620. ...do some stuff...
  9621. // myCriticalSection gets unlocked here.
  9622. }
  9623. @endcode
  9624. @see CriticalSection, ScopedUnlock
  9625. */
  9626. class JUCE_API ScopedLock
  9627. {
  9628. public:
  9629. /** Creates a ScopedLock.
  9630. As soon as it is created, this will lock the CriticalSection, and
  9631. when the ScopedLock object is deleted, the CriticalSection will
  9632. be unlocked.
  9633. Make sure this object is created and deleted by the same thread,
  9634. otherwise there are no guarantees what will happen! Best just to use it
  9635. as a local stack object, rather than creating one with the new() operator.
  9636. */
  9637. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  9638. /** Destructor.
  9639. The CriticalSection will be unlocked when the destructor is called.
  9640. Make sure this object is created and deleted by the same thread,
  9641. otherwise there are no guarantees what will happen!
  9642. */
  9643. inline ~ScopedLock() throw() { lock_.exit(); }
  9644. private:
  9645. const CriticalSection& lock_;
  9646. ScopedLock (const ScopedLock&);
  9647. ScopedLock& operator= (const ScopedLock&);
  9648. };
  9649. /**
  9650. Automatically unlocks and re-locks a CriticalSection object.
  9651. This is the reverse of a ScopedLock object - instead of locking the critical
  9652. section for the lifetime of this object, it unlocks it.
  9653. Make sure you don't try to unlock critical sections that aren't actually locked!
  9654. e.g. @code
  9655. CriticalSection myCriticalSection;
  9656. for (;;)
  9657. {
  9658. const ScopedLock myScopedLock (myCriticalSection);
  9659. // myCriticalSection is now locked
  9660. ... do some stuff with it locked ..
  9661. while (xyz)
  9662. {
  9663. ... do some stuff with it locked ..
  9664. const ScopedUnlock unlocker (myCriticalSection);
  9665. // myCriticalSection is now unlocked for the remainder of this block,
  9666. // and re-locked at the end.
  9667. ...do some stuff with it unlocked ...
  9668. }
  9669. // myCriticalSection gets unlocked here.
  9670. }
  9671. @endcode
  9672. @see CriticalSection, ScopedLock
  9673. */
  9674. class ScopedUnlock
  9675. {
  9676. public:
  9677. /** Creates a ScopedUnlock.
  9678. As soon as it is created, this will unlock the CriticalSection, and
  9679. when the ScopedLock object is deleted, the CriticalSection will
  9680. be re-locked.
  9681. Make sure this object is created and deleted by the same thread,
  9682. otherwise there are no guarantees what will happen! Best just to use it
  9683. as a local stack object, rather than creating one with the new() operator.
  9684. */
  9685. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  9686. /** Destructor.
  9687. The CriticalSection will be unlocked when the destructor is called.
  9688. Make sure this object is created and deleted by the same thread,
  9689. otherwise there are no guarantees what will happen!
  9690. */
  9691. inline ~ScopedUnlock() throw() { lock_.enter(); }
  9692. private:
  9693. const CriticalSection& lock_;
  9694. ScopedUnlock (const ScopedLock&);
  9695. ScopedUnlock& operator= (const ScopedUnlock&);
  9696. };
  9697. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  9698. /*** End of inlined file: juce_ScopedLock.h ***/
  9699. /**
  9700. A set of ChangeListeners.
  9701. Listeners can be added and removed from the list, and change messages can be
  9702. broadcast to all the listeners.
  9703. @see ChangeListener, ChangeBroadcaster
  9704. */
  9705. class JUCE_API ChangeListenerList : public MessageListener
  9706. {
  9707. public:
  9708. /** Creates an empty list. */
  9709. ChangeListenerList() throw();
  9710. /** Destructor. */
  9711. ~ChangeListenerList() throw();
  9712. /** Adds a listener to the list.
  9713. (Trying to add a listener that's already on the list will have no effect).
  9714. */
  9715. void addChangeListener (ChangeListener* listener) throw();
  9716. /** Removes a listener from the list.
  9717. If the listener isn't on the list, this won't have any effect.
  9718. */
  9719. void removeChangeListener (ChangeListener* listener) throw();
  9720. /** Removes all listeners from the list. */
  9721. void removeAllChangeListeners() throw();
  9722. /** Posts an asynchronous change message to all the listeners.
  9723. If a message has already been sent and hasn't yet been delivered, this
  9724. method won't send another - in this way it coalesces multiple frequent
  9725. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  9726. with the ActionListener, which posts a new event for every call to its
  9727. sendActionMessage() method.
  9728. Only listeners which are on the list when the change event is delivered
  9729. will receive the event - and this may include listeners that weren't on
  9730. the list when the change message was sent.
  9731. @param objectThatHasChanged this pointer is passed to the
  9732. ChangeListener::changeListenerCallback() method,
  9733. and can be any value the application needs
  9734. @see sendSynchronousChangeMessage
  9735. */
  9736. void sendChangeMessage (void* objectThatHasChanged) throw();
  9737. /** This will synchronously callback all the ChangeListeners.
  9738. Use this if you need to synchronously force a call to all the
  9739. listeners' ChangeListener::changeListenerCallback() methods.
  9740. */
  9741. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9742. /** If a change message has been sent but not yet dispatched, this will
  9743. use sendSynchronousChangeMessage() to make the callback immediately.
  9744. */
  9745. void dispatchPendingMessages();
  9746. /** @internal */
  9747. void handleMessage (const Message&);
  9748. juce_UseDebuggingNewOperator
  9749. private:
  9750. SortedSet <void*> listeners;
  9751. CriticalSection lock;
  9752. void* lastChangedObject;
  9753. bool messagePending;
  9754. ChangeListenerList (const ChangeListenerList&);
  9755. ChangeListenerList& operator= (const ChangeListenerList&);
  9756. };
  9757. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9758. /*** End of inlined file: juce_ChangeListenerList.h ***/
  9759. /** Manages a list of ChangeListeners, and can send them messages.
  9760. To quickly add methods to your class that can add/remove change
  9761. listeners and broadcast to them, you can derive from this.
  9762. @see ChangeListenerList, ChangeListener
  9763. */
  9764. class JUCE_API ChangeBroadcaster
  9765. {
  9766. public:
  9767. /** Creates an ChangeBroadcaster. */
  9768. ChangeBroadcaster() throw();
  9769. /** Destructor. */
  9770. virtual ~ChangeBroadcaster();
  9771. /** Adds a listener to the list.
  9772. (Trying to add a listener that's already on the list will have no effect).
  9773. */
  9774. void addChangeListener (ChangeListener* listener) throw();
  9775. /** Removes a listener from the list.
  9776. If the listener isn't on the list, this won't have any effect.
  9777. */
  9778. void removeChangeListener (ChangeListener* listener) throw();
  9779. /** Removes all listeners from the list. */
  9780. void removeAllChangeListeners() throw();
  9781. /** Broadcasts a change message to all the registered listeners.
  9782. The message will be delivered asynchronously by the event thread, so this
  9783. method will not directly call any of the listeners. For a synchronous
  9784. message, use sendSynchronousChangeMessage().
  9785. @see ChangeListenerList::sendActionMessage
  9786. */
  9787. void sendChangeMessage (void* objectThatHasChanged) throw();
  9788. /** Sends a synchronous change message to all the registered listeners.
  9789. @see ChangeListenerList::sendSynchronousChangeMessage
  9790. */
  9791. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9792. /** If a change message has been sent but not yet dispatched, this will
  9793. use sendSynchronousChangeMessage() to make the callback immediately.
  9794. */
  9795. void dispatchPendingMessages();
  9796. private:
  9797. ChangeListenerList changeListenerList;
  9798. ChangeBroadcaster (const ChangeBroadcaster&);
  9799. ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  9800. };
  9801. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9802. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  9803. /*** Start of inlined file: juce_UndoableAction.h ***/
  9804. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  9805. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  9806. /**
  9807. Used by the UndoManager class to store an action which can be done
  9808. and undone.
  9809. @see UndoManager
  9810. */
  9811. class JUCE_API UndoableAction
  9812. {
  9813. protected:
  9814. /** Creates an action. */
  9815. UndoableAction() throw() {}
  9816. public:
  9817. /** Destructor. */
  9818. virtual ~UndoableAction() {}
  9819. /** Overridden by a subclass to perform the action.
  9820. This method is called by the UndoManager, and shouldn't be used directly by
  9821. applications.
  9822. Be careful not to make any calls in a perform() method that could call
  9823. recursively back into the UndoManager::perform() method
  9824. @returns true if the action could be performed.
  9825. @see UndoManager::perform
  9826. */
  9827. virtual bool perform() = 0;
  9828. /** Overridden by a subclass to undo the action.
  9829. This method is called by the UndoManager, and shouldn't be used directly by
  9830. applications.
  9831. Be careful not to make any calls in an undo() method that could call
  9832. recursively back into the UndoManager::perform() method
  9833. @returns true if the action could be undone without any errors.
  9834. @see UndoManager::perform
  9835. */
  9836. virtual bool undo() = 0;
  9837. /** Returns a value to indicate how much memory this object takes up.
  9838. Because the UndoManager keeps a list of UndoableActions, this is used
  9839. to work out how much space each one will take up, so that the UndoManager
  9840. can work out how many to keep.
  9841. The default value returned here is 10 - units are arbitrary and
  9842. don't have to be accurate.
  9843. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9844. UndoManager::setMaxNumberOfStoredUnits
  9845. */
  9846. virtual int getSizeInUnits() { return 10; }
  9847. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  9848. If possible, this method should create and return a single action that does the same job as
  9849. this one followed by the supplied action.
  9850. If it's not possible to merge the two actions, the method should return zero.
  9851. */
  9852. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  9853. };
  9854. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9855. /*** End of inlined file: juce_UndoableAction.h ***/
  9856. /**
  9857. Manages a list of undo/redo commands.
  9858. An UndoManager object keeps a list of past actions and can use these actions
  9859. to move backwards and forwards through an undo history.
  9860. To use it, create subclasses of UndoableAction which perform all the
  9861. actions you need, then when you need to actually perform an action, create one
  9862. and pass it to the UndoManager's perform() method.
  9863. The manager also uses the concept of 'transactions' to group the actions
  9864. together - all actions performed between calls to beginNewTransaction() are
  9865. grouped together and are all undone/redone as a group.
  9866. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9867. when actions are performed or undone.
  9868. @see UndoableAction
  9869. */
  9870. class JUCE_API UndoManager : public ChangeBroadcaster
  9871. {
  9872. public:
  9873. /** Creates an UndoManager.
  9874. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9875. to indicate how much storage it takes up
  9876. (UndoableAction::getSizeInUnits()), so this
  9877. lets you specify the maximum total number of
  9878. units that the undomanager is allowed to
  9879. keep in memory before letting the older actions
  9880. drop off the end of the list.
  9881. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9882. that will be kept, even if this involves exceeding
  9883. the amount of space specified in maxNumberOfUnitsToKeep
  9884. */
  9885. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  9886. int minimumTransactionsToKeep = 30);
  9887. /** Destructor. */
  9888. ~UndoManager();
  9889. /** Deletes all stored actions in the list. */
  9890. void clearUndoHistory();
  9891. /** Returns the current amount of space to use for storing UndoableAction objects.
  9892. @see setMaxNumberOfStoredUnits
  9893. */
  9894. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9895. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9896. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9897. to indicate how much storage it takes up
  9898. (UndoableAction::getSizeInUnits()), so this
  9899. lets you specify the maximum total number of
  9900. units that the undomanager is allowed to
  9901. keep in memory before letting the older actions
  9902. drop off the end of the list.
  9903. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9904. that will be kept, even if this involves exceeding
  9905. the amount of space specified in maxNumberOfUnitsToKeep
  9906. @see getNumberOfUnitsTakenUpByStoredCommands
  9907. */
  9908. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  9909. int minimumTransactionsToKeep);
  9910. /** Performs an action and adds it to the undo history list.
  9911. @param action the action to perform - this will be deleted by the UndoManager
  9912. when no longer needed
  9913. @param actionName if this string is non-empty, the current transaction will be
  9914. given this name; if it's empty, the current transaction name will
  9915. be left unchanged. See setCurrentTransactionName()
  9916. @returns true if the command succeeds - see UndoableAction::perform
  9917. @see beginNewTransaction
  9918. */
  9919. bool perform (UndoableAction* action,
  9920. const String& actionName = String::empty);
  9921. /** Starts a new group of actions that together will be treated as a single transaction.
  9922. All actions that are passed to the perform() method between calls to this
  9923. method are grouped together and undone/redone together by a single call to
  9924. undo() or redo().
  9925. @param actionName a description of the transaction that is about to be
  9926. performed
  9927. */
  9928. void beginNewTransaction (const String& actionName = String::empty);
  9929. /** Changes the name stored for the current transaction.
  9930. Each transaction is given a name when the beginNewTransaction() method is
  9931. called, but this can be used to change that name without starting a new
  9932. transaction.
  9933. */
  9934. void setCurrentTransactionName (const String& newName);
  9935. /** Returns true if there's at least one action in the list to undo.
  9936. @see getUndoDescription, undo, canRedo
  9937. */
  9938. bool canUndo() const;
  9939. /** Returns the description of the transaction that would be next to get undone.
  9940. The description returned is the one that was passed into beginNewTransaction
  9941. before the set of actions was performed.
  9942. @see undo
  9943. */
  9944. const String getUndoDescription() const;
  9945. /** Tries to roll-back the last transaction.
  9946. @returns true if the transaction can be undone, and false if it fails, or
  9947. if there aren't any transactions to undo
  9948. */
  9949. bool undo();
  9950. /** Tries to roll-back any actions that were added to the current transaction.
  9951. This will perform an undo() only if there are some actions in the undo list
  9952. that were added after the last call to beginNewTransaction().
  9953. This is useful because it lets you call beginNewTransaction(), then
  9954. perform an operation which may or may not actually perform some actions, and
  9955. then call this method to get rid of any actions that might have been done
  9956. without it rolling back the previous transaction if nothing was actually
  9957. done.
  9958. @returns true if any actions were undone.
  9959. */
  9960. bool undoCurrentTransactionOnly();
  9961. /** Returns a list of the UndoableAction objects that have been performed during the
  9962. transaction that is currently open.
  9963. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9964. were to be called now.
  9965. The first item in the list is the earliest action performed.
  9966. */
  9967. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9968. /** Returns the number of UndoableAction objects that have been performed during the
  9969. transaction that is currently open.
  9970. @see getActionsInCurrentTransaction
  9971. */
  9972. int getNumActionsInCurrentTransaction() const;
  9973. /** Returns true if there's at least one action in the list to redo.
  9974. @see getRedoDescription, redo, canUndo
  9975. */
  9976. bool canRedo() const;
  9977. /** Returns the description of the transaction that would be next to get redone.
  9978. The description returned is the one that was passed into beginNewTransaction
  9979. before the set of actions was performed.
  9980. @see redo
  9981. */
  9982. const String getRedoDescription() const;
  9983. /** Tries to redo the last transaction that was undone.
  9984. @returns true if the transaction can be redone, and false if it fails, or
  9985. if there aren't any transactions to redo
  9986. */
  9987. bool redo();
  9988. juce_UseDebuggingNewOperator
  9989. private:
  9990. OwnedArray <OwnedArray <UndoableAction> > transactions;
  9991. StringArray transactionNames;
  9992. String currentTransactionName;
  9993. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  9994. bool newTransaction, reentrancyCheck;
  9995. // disallow copy constructor
  9996. UndoManager (const UndoManager&);
  9997. UndoManager& operator= (const UndoManager&);
  9998. };
  9999. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  10000. /*** End of inlined file: juce_UndoManager.h ***/
  10001. /**
  10002. A powerful tree structure that can be used to hold free-form data, and which can
  10003. handle its own undo and redo behaviour.
  10004. A ValueTree contains a list of named properties as var objects, and also holds
  10005. any number of sub-trees.
  10006. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  10007. they're simply a lightweight reference to a shared data container. Creating a copy
  10008. of another ValueTree simply creates a new reference to the same underlying object - to
  10009. make a separate, deep copy of a tree you should explicitly call createCopy().
  10010. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  10011. and much of the structure of a ValueTree is similar to an XmlElement tree.
  10012. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  10013. contain text elements, the conversion works well and makes a good serialisation
  10014. format. They can also be serialised to a binary format, which is very fast and compact.
  10015. All the methods that change data take an optional UndoManager, which will be used
  10016. to track any changes to the object. For this to work, you have to be careful to
  10017. consistently always use the same UndoManager for all operations to any node inside
  10018. the tree.
  10019. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  10020. one tree to another, be careful to always remove it first, before adding it. This
  10021. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  10022. assertions if you try to do anything dangerous, but there are still plenty of ways it
  10023. could go wrong.
  10024. Listeners can be added to a ValueTree to be told when properies change and when
  10025. nodes are added or removed.
  10026. @see var, XmlElement
  10027. */
  10028. class JUCE_API ValueTree
  10029. {
  10030. public:
  10031. /** Creates an empty, invalid ValueTree.
  10032. A ValueTree that is created with this constructor can't actually be used for anything,
  10033. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  10034. To create a real one, use the constructor that takes a string.
  10035. @see ValueTree::invalid
  10036. */
  10037. ValueTree() throw();
  10038. /** Creates an empty ValueTree with the given type name.
  10039. Like an XmlElement, each ValueTree node has a type, which you can access with
  10040. getType() and hasType().
  10041. */
  10042. explicit ValueTree (const Identifier& type);
  10043. /** Creates a reference to another ValueTree. */
  10044. ValueTree (const ValueTree& other);
  10045. /** Makes this object reference another node. */
  10046. ValueTree& operator= (const ValueTree& other);
  10047. /** Destructor. */
  10048. ~ValueTree();
  10049. /** Returns true if both this and the other tree node refer to the same underlying structure.
  10050. Note that this isn't a value comparison - two independently-created trees which
  10051. contain identical data are not considered equal.
  10052. */
  10053. bool operator== (const ValueTree& other) const throw();
  10054. /** Returns true if this and the other node refer to different underlying structures.
  10055. Note that this isn't a value comparison - two independently-created trees which
  10056. contain identical data are not considered equal.
  10057. */
  10058. bool operator!= (const ValueTree& other) const throw();
  10059. /** Performs a deep comparison between the properties and children of two trees.
  10060. If all the properties and children of the two trees are the same (recursively), this
  10061. returns true.
  10062. The normal operator==() only checks whether two trees refer to the same shared data
  10063. structure, so use this method if you need to do a proper value comparison.
  10064. */
  10065. bool isEquivalentTo (const ValueTree& other) const;
  10066. /** Returns true if this node refers to some valid data.
  10067. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  10068. call to getChild().
  10069. */
  10070. bool isValid() const { return object != 0; }
  10071. /** Returns a deep copy of this tree and all its sub-nodes. */
  10072. ValueTree createCopy() const;
  10073. /** Returns the type of this node.
  10074. The type is specified when the ValueTree is created.
  10075. @see hasType
  10076. */
  10077. const Identifier getType() const;
  10078. /** Returns true if the node has this type.
  10079. The comparison is case-sensitive.
  10080. */
  10081. bool hasType (const Identifier& typeName) const;
  10082. /** Returns the value of a named property.
  10083. If no such property has been set, this will return a void variant.
  10084. You can also use operator[] to get a property.
  10085. @see var, setProperty, hasProperty
  10086. */
  10087. const var& getProperty (const Identifier& name) const;
  10088. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  10089. If no such property has been set, this will return the value of defaultReturnValue.
  10090. You can also use operator[] and getProperty to get a property.
  10091. @see var, getProperty, setProperty, hasProperty
  10092. */
  10093. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10094. /** Returns the value of a named property.
  10095. If no such property has been set, this will return a void variant. This is the same as
  10096. calling getProperty().
  10097. @see getProperty
  10098. */
  10099. const var& operator[] (const Identifier& name) const;
  10100. /** Changes a named property of the node.
  10101. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10102. so that this change can be undone.
  10103. @see var, getProperty, removeProperty
  10104. */
  10105. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  10106. /** Returns true if the node contains a named property. */
  10107. bool hasProperty (const Identifier& name) const;
  10108. /** Removes a property from the node.
  10109. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10110. so that this change can be undone.
  10111. */
  10112. void removeProperty (const Identifier& name, UndoManager* undoManager);
  10113. /** Removes all properties from the node.
  10114. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10115. so that this change can be undone.
  10116. */
  10117. void removeAllProperties (UndoManager* undoManager);
  10118. /** Returns the total number of properties that the node contains.
  10119. @see getProperty.
  10120. */
  10121. int getNumProperties() const;
  10122. /** Returns the identifier of the property with a given index.
  10123. @see getNumProperties
  10124. */
  10125. const Identifier getPropertyName (int index) const;
  10126. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  10127. The Value object will maintain a reference to this tree, and will use the undo manager when
  10128. it needs to change the value. Attaching a Value::Listener to the value object will provide
  10129. callbacks whenever the property changes.
  10130. */
  10131. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  10132. /** Returns the number of child nodes belonging to this one.
  10133. @see getChild
  10134. */
  10135. int getNumChildren() const;
  10136. /** Returns one of this node's child nodes.
  10137. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  10138. whether a node is valid).
  10139. */
  10140. ValueTree getChild (int index) const;
  10141. /** Returns the first child node with the speficied type name.
  10142. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10143. whether a node is valid).
  10144. @see getOrCreateChildWithName
  10145. */
  10146. ValueTree getChildWithName (const Identifier& type) const;
  10147. /** Returns the first child node with the speficied type name, creating and adding
  10148. a child with this name if there wasn't already one there.
  10149. The only time this will return an invalid object is when the object that you're calling
  10150. the method on is itself invalid.
  10151. @see getChildWithName
  10152. */
  10153. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10154. /** Looks for the first child node that has the speficied property value.
  10155. This will scan the child nodes in order, until it finds one that has property that matches
  10156. the specified value.
  10157. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10158. whether a node is valid).
  10159. */
  10160. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10161. /** Adds a child to this node.
  10162. Make sure that the child is removed from any former parent node before calling this, or
  10163. you'll hit an assertion.
  10164. If the index is < 0 or greater than the current number of child nodes, the new node will
  10165. be added at the end of the list.
  10166. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10167. so that this change can be undone.
  10168. */
  10169. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  10170. /** Removes the specified child from this node's child-list.
  10171. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10172. so that this change can be undone.
  10173. */
  10174. void removeChild (const ValueTree& child, UndoManager* undoManager);
  10175. /** Removes a child from this node's child-list.
  10176. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10177. so that this change can be undone.
  10178. */
  10179. void removeChild (int childIndex, UndoManager* undoManager);
  10180. /** Removes all child-nodes from this node.
  10181. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10182. so that this change can be undone.
  10183. */
  10184. void removeAllChildren (UndoManager* undoManager);
  10185. /** Moves one of the children to a different index.
  10186. This will move the child to a specified index, shuffling along any intervening
  10187. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  10188. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10189. @param currentIndex the index of the item to be moved. If this isn't a
  10190. valid index, then nothing will be done
  10191. @param newIndex the index at which you'd like this item to end up. If this
  10192. is less than zero, the value will be moved to the end
  10193. of the list
  10194. @param undoManager the optional UndoManager to use to store this transaction
  10195. */
  10196. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  10197. /** Returns true if this node is anywhere below the specified parent node.
  10198. This returns true if the node is a child-of-a-child, as well as a direct child.
  10199. */
  10200. bool isAChildOf (const ValueTree& possibleParent) const;
  10201. /** Returns the index of a child item in this parent.
  10202. If the child isn't found, this returns -1.
  10203. */
  10204. int indexOf (const ValueTree& child) const;
  10205. /** Returns the parent node that contains this one.
  10206. If the node has no parent, this will return an invalid node. (See isValid() to find out
  10207. whether a node is valid).
  10208. */
  10209. ValueTree getParent() const;
  10210. /** Returns one of this node's siblings in its parent's child list.
  10211. The delta specifies how far to move through the list, so a value of 1 would return the node
  10212. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  10213. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  10214. */
  10215. ValueTree getSibling (int delta) const;
  10216. /** Creates an XmlElement that holds a complete image of this node and all its children.
  10217. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  10218. be used to recreate a similar node by calling fromXml()
  10219. @see fromXml
  10220. */
  10221. XmlElement* createXml() const;
  10222. /** Tries to recreate a node from its XML representation.
  10223. This isn't designed to cope with random XML data - for a sensible result, it should only
  10224. be fed XML that was created by the createXml() method.
  10225. */
  10226. static ValueTree fromXml (const XmlElement& xml);
  10227. /** Stores this tree (and all its children) in a binary format.
  10228. Once written, the data can be read back with readFromStream().
  10229. It's much faster to load/save your tree in binary form than as XML, but
  10230. obviously isn't human-readable.
  10231. */
  10232. void writeToStream (OutputStream& output);
  10233. /** Reloads a tree from a stream that was written with writeToStream(). */
  10234. static ValueTree readFromStream (InputStream& input);
  10235. /** Reloads a tree from a data block that was written with writeToStream(). */
  10236. static ValueTree readFromData (const void* data, size_t numBytes);
  10237. /** Listener class for events that happen to a ValueTree.
  10238. To get events from a ValueTree, make your class implement this interface, and use
  10239. ValueTree::addListener() and ValueTree::removeListener() to register it.
  10240. */
  10241. class JUCE_API Listener
  10242. {
  10243. public:
  10244. /** Destructor. */
  10245. virtual ~Listener() {}
  10246. /** This method is called when a property of this node (or of one of its sub-nodes) has
  10247. changed.
  10248. The tree parameter indicates which tree has had its property changed, and the property
  10249. parameter indicates the property.
  10250. Note that when you register a listener to a tree, it will receive this callback for
  10251. property changes in that tree, and also for any of its children, (recursively, at any depth).
  10252. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10253. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10254. */
  10255. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  10256. const Identifier& property) = 0;
  10257. /** This method is called when a child sub-tree is added or removed.
  10258. The tree parameter indicates the tree whose child was added or removed.
  10259. Note that when you register a listener to a tree, it will receive this callback for
  10260. child changes in that tree, and also in any of its children, (recursively, at any depth).
  10261. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10262. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10263. */
  10264. virtual void valueTreeChildrenChanged (ValueTree& treeWhoseChildHasChanged) = 0;
  10265. /** This method is called when a tree has been added or removed from a parent node.
  10266. This callback happens when the tree to which the listener was registered is added or
  10267. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  10268. the listener is registered, and not to any of its children.
  10269. */
  10270. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  10271. };
  10272. /** Adds a listener to receive callbacks when this node is changed.
  10273. The listener is added to this specific ValueTree object, and not to the shared
  10274. object that it refers to. When this object is deleted, all the listeners will
  10275. be lost, even if other references to the same ValueTree still exist. And if you
  10276. use the operator= to make this refer to a different ValueTree, any listeners will
  10277. begin listening to changes to the new tree instead of the old one.
  10278. When you're adding a listener, make sure that you add it to a ValueTree instance that
  10279. will last for as long as you need the listener. In general, you'd never want to add a
  10280. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  10281. @see removeListener
  10282. */
  10283. void addListener (Listener* listener);
  10284. /** Removes a listener that was previously added with addListener(). */
  10285. void removeListener (Listener* listener);
  10286. /** This method uses a comparator object to sort the tree's children into order.
  10287. The object provided must have a method of the form:
  10288. @code
  10289. int compareElements (const ValueTree& first, const ValueTree& second);
  10290. @endcode
  10291. ..and this method must return:
  10292. - a value of < 0 if the first comes before the second
  10293. - a value of 0 if the two objects are equivalent
  10294. - a value of > 0 if the second comes before the first
  10295. To improve performance, the compareElements() method can be declared as static or const.
  10296. @param comparator the comparator to use for comparing elements.
  10297. @param retainOrderOfEquivalentItems if this is true, then items
  10298. which the comparator says are equivalent will be
  10299. kept in the order in which they currently appear
  10300. in the array. This is slower to perform, but may
  10301. be important in some cases. If it's false, a faster
  10302. algorithm is used, but equivalent elements may be
  10303. rearranged.
  10304. */
  10305. template <typename ElementComparator>
  10306. void sort (ElementComparator& comparator, const bool retainOrderOfEquivalentItems = false)
  10307. {
  10308. if (object != 0)
  10309. {
  10310. ComparatorAdapter <ElementComparator> adapter (comparator);
  10311. object->children.sort (adapter, retainOrderOfEquivalentItems);
  10312. object->sendChildChangeMessage();
  10313. }
  10314. }
  10315. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  10316. This invalid object is equivalent to ValueTree created with its default constructor.
  10317. */
  10318. static const ValueTree invalid;
  10319. juce_UseDebuggingNewOperator
  10320. private:
  10321. class SetPropertyAction;
  10322. friend class SetPropertyAction;
  10323. class AddOrRemoveChildAction;
  10324. friend class AddOrRemoveChildAction;
  10325. class MoveChildAction;
  10326. friend class MoveChildAction;
  10327. class JUCE_API SharedObject : public ReferenceCountedObject
  10328. {
  10329. public:
  10330. explicit SharedObject (const Identifier& type);
  10331. SharedObject (const SharedObject& other);
  10332. ~SharedObject();
  10333. const Identifier type;
  10334. NamedValueSet properties;
  10335. ReferenceCountedArray <SharedObject> children;
  10336. SortedSet <ValueTree*> valueTreesWithListeners;
  10337. SharedObject* parent;
  10338. void sendPropertyChangeMessage (const Identifier& property);
  10339. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  10340. void sendChildChangeMessage();
  10341. void sendChildChangeMessage (ValueTree& tree);
  10342. void sendParentChangeMessage();
  10343. const var& getProperty (const Identifier& name) const;
  10344. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10345. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  10346. bool hasProperty (const Identifier& name) const;
  10347. void removeProperty (const Identifier& name, UndoManager*);
  10348. void removeAllProperties (UndoManager*);
  10349. bool isAChildOf (const SharedObject* possibleParent) const;
  10350. int indexOf (const ValueTree& child) const;
  10351. ValueTree getChildWithName (const Identifier& type) const;
  10352. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10353. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10354. void addChild (SharedObject* child, int index, UndoManager*);
  10355. void removeChild (int childIndex, UndoManager*);
  10356. void removeAllChildren (UndoManager*);
  10357. void moveChild (int currentIndex, int newIndex, UndoManager*);
  10358. bool isEquivalentTo (const SharedObject& other) const;
  10359. XmlElement* createXml() const;
  10360. juce_UseDebuggingNewOperator
  10361. private:
  10362. SharedObject& operator= (const SharedObject&);
  10363. };
  10364. template <typename ElementComparator>
  10365. class ComparatorAdapter
  10366. {
  10367. public:
  10368. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  10369. int compareElements (SharedObject* const first, SharedObject* const second)
  10370. {
  10371. return comparator.compareElements (ValueTree (first), ValueTree (second));
  10372. }
  10373. private:
  10374. ElementComparator& comparator;
  10375. ComparatorAdapter (const ComparatorAdapter&);
  10376. ComparatorAdapter& operator= (const ComparatorAdapter&);
  10377. };
  10378. friend class SharedObject;
  10379. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  10380. SharedObjectPtr object;
  10381. ListenerList <Listener> listeners;
  10382. #if JUCE_MSVC && ! DOXYGEN
  10383. public: // (workaround for VC6)
  10384. #endif
  10385. explicit ValueTree (SharedObject*);
  10386. };
  10387. #endif // __JUCE_VALUETREE_JUCEHEADER__
  10388. /*** End of inlined file: juce_ValueTree.h ***/
  10389. #endif
  10390. #ifndef __JUCE_VARIANT_JUCEHEADER__
  10391. #endif
  10392. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  10393. #endif
  10394. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  10395. #endif
  10396. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10397. /*** Start of inlined file: juce_FileLogger.h ***/
  10398. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10399. #define __JUCE_FILELOGGER_JUCEHEADER__
  10400. /**
  10401. A simple implemenation of a Logger that writes to a file.
  10402. @see Logger
  10403. */
  10404. class JUCE_API FileLogger : public Logger
  10405. {
  10406. public:
  10407. /** Creates a FileLogger for a given file.
  10408. @param fileToWriteTo the file that to use - new messages will be appended
  10409. to the file. If the file doesn't exist, it will be created,
  10410. along with any parent directories that are needed.
  10411. @param welcomeMessage when opened, the logger will write a header to the log, along
  10412. with the current date and time, and this welcome message
  10413. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  10414. but is larger than this number of bytes, then the start of the
  10415. file will be truncated to keep the size down. This prevents a log
  10416. file getting ridiculously large over time. The file will be truncated
  10417. at a new-line boundary. If this value is less than zero, no size limit
  10418. will be imposed; if it's zero, the file will always be deleted. Note that
  10419. the size is only checked once when this object is created - any logging
  10420. that is done later will be appended without any checking
  10421. */
  10422. FileLogger (const File& fileToWriteTo,
  10423. const String& welcomeMessage,
  10424. const int maxInitialFileSizeBytes = 128 * 1024);
  10425. /** Destructor. */
  10426. ~FileLogger();
  10427. void logMessage (const String& message);
  10428. const File getLogFile() const { return logFile; }
  10429. /** Helper function to create a log file in the correct place for this platform.
  10430. On Windows this will return a logger with a path such as:
  10431. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  10432. On the Mac it'll create something like:
  10433. ~/Library/Logs/[logFileName]
  10434. The method might return 0 if the file can't be created for some reason.
  10435. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  10436. it's best to use the something like the name of your application here.
  10437. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  10438. call it "log.txt" because if it goes in a directory with logs
  10439. from other applications (as it will do on the Mac) then no-one
  10440. will know which one is yours!
  10441. @param welcomeMessage a message that will be written to the log when it's opened.
  10442. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  10443. */
  10444. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  10445. const String& logFileName,
  10446. const String& welcomeMessage,
  10447. const int maxInitialFileSizeBytes = 128 * 1024);
  10448. juce_UseDebuggingNewOperator
  10449. private:
  10450. File logFile;
  10451. CriticalSection logLock;
  10452. ScopedPointer <FileOutputStream> logStream;
  10453. void trimFileSize (int maxFileSizeBytes) const;
  10454. FileLogger (const FileLogger&);
  10455. FileLogger& operator= (const FileLogger&);
  10456. };
  10457. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  10458. /*** End of inlined file: juce_FileLogger.h ***/
  10459. #endif
  10460. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10461. /*** Start of inlined file: juce_Initialisation.h ***/
  10462. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10463. #define __JUCE_INITIALISATION_JUCEHEADER__
  10464. /** Initialises Juce's GUI classes.
  10465. If you're embedding Juce into an application that uses its own event-loop rather
  10466. than using the START_JUCE_APPLICATION macro, call this function before making any
  10467. Juce calls, to make sure things are initialised correctly.
  10468. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10469. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10470. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  10471. */
  10472. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  10473. /** Clears up any static data being used by Juce's GUI classes.
  10474. If you're embedding Juce into an application that uses its own event-loop rather
  10475. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  10476. code to clean up any juce objects that might be lying around.
  10477. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  10478. */
  10479. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  10480. /** Initialises the core parts of Juce.
  10481. If you're embedding Juce into either a command-line program, call this function
  10482. at the start of your main() function to make sure that Juce is initialised correctly.
  10483. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10484. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10485. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  10486. */
  10487. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  10488. /** Clears up any static data being used by Juce's non-gui core classes.
  10489. If you're embedding Juce into either a command-line program, call this function
  10490. at the end of your main() function if you want to make sure any Juce objects are
  10491. cleaned up correctly.
  10492. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  10493. */
  10494. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  10495. /** A utility object that helps you initialise and shutdown Juce correctly
  10496. using an RAII pattern.
  10497. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  10498. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  10499. make sure that these functions are matched correctly.
  10500. This class is particularly handy to use at the beginning of a console app's
  10501. main() function, because it'll take care of shutting down whenever you return
  10502. from the main() call.
  10503. @see ScopedJuceInitialiser_GUI
  10504. */
  10505. class ScopedJuceInitialiser_NonGUI
  10506. {
  10507. public:
  10508. /** The constructor simply calls initialiseJuce_NonGUI(). */
  10509. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  10510. /** The destructor simply calls shutdownJuce_NonGUI(). */
  10511. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  10512. };
  10513. /** A utility object that helps you initialise and shutdown Juce correctly
  10514. using an RAII pattern.
  10515. When an instance of this class is created, it calls initialiseJuce_GUI(),
  10516. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  10517. make sure that these functions are matched correctly.
  10518. This class is particularly handy to use at the beginning of a console app's
  10519. main() function, because it'll take care of shutting down whenever you return
  10520. from the main() call.
  10521. @see ScopedJuceInitialiser_NonGUI
  10522. */
  10523. class ScopedJuceInitialiser_GUI
  10524. {
  10525. public:
  10526. /** The constructor simply calls initialiseJuce_GUI(). */
  10527. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  10528. /** The destructor simply calls shutdownJuce_GUI(). */
  10529. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  10530. };
  10531. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  10532. /*** End of inlined file: juce_Initialisation.h ***/
  10533. #endif
  10534. #ifndef __JUCE_LOGGER_JUCEHEADER__
  10535. #endif
  10536. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  10537. #endif
  10538. #ifndef __JUCE_MEMORY_JUCEHEADER__
  10539. #endif
  10540. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10541. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  10542. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10543. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10544. /** A timer for measuring performance of code and dumping the results to a file.
  10545. e.g. @code
  10546. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  10547. for (;;)
  10548. {
  10549. pc.start();
  10550. doSomethingFishy();
  10551. pc.stop();
  10552. }
  10553. @endcode
  10554. In this example, the time of each period between calling start/stop will be
  10555. measured and averaged over 50 runs, and the results printed to a file
  10556. every 50 times round the loop.
  10557. */
  10558. class JUCE_API PerformanceCounter
  10559. {
  10560. public:
  10561. /** Creates a PerformanceCounter object.
  10562. @param counterName the name used when printing out the statistics
  10563. @param runsPerPrintout the number of start/stop iterations before calling
  10564. printStatistics()
  10565. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  10566. the results are just written to the debugger output
  10567. */
  10568. PerformanceCounter (const String& counterName,
  10569. int runsPerPrintout = 100,
  10570. const File& loggingFile = File::nonexistent);
  10571. /** Destructor. */
  10572. ~PerformanceCounter();
  10573. /** Starts timing.
  10574. @see stop
  10575. */
  10576. void start();
  10577. /** Stops timing and prints out the results.
  10578. The number of iterations before doing a printout of the
  10579. results is set in the constructor.
  10580. @see start
  10581. */
  10582. void stop();
  10583. /** Dumps the current metrics to the debugger output and to a file.
  10584. As well as using Logger::outputDebugString to print the results,
  10585. this will write then to the file specified in the constructor (if
  10586. this was valid).
  10587. */
  10588. void printStatistics();
  10589. juce_UseDebuggingNewOperator
  10590. private:
  10591. String name;
  10592. int numRuns, runsPerPrint;
  10593. double totalTime;
  10594. int64 started;
  10595. File outputFile;
  10596. };
  10597. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10598. /*** End of inlined file: juce_PerformanceCounter.h ***/
  10599. #endif
  10600. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  10601. #endif
  10602. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10603. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  10604. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10605. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10606. /**
  10607. A collection of miscellaneous platform-specific utilities.
  10608. */
  10609. class JUCE_API PlatformUtilities
  10610. {
  10611. public:
  10612. /** Plays the operating system's default alert 'beep' sound. */
  10613. static void beep();
  10614. /** Tries to launch the system's default reader for a given file or URL. */
  10615. static bool openDocument (const String& documentURL, const String& parameters);
  10616. /** Tries to launch the system's default email app to let the user create an email.
  10617. */
  10618. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  10619. const String& emailSubject,
  10620. const String& bodyText,
  10621. const StringArray& filesToAttach);
  10622. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  10623. /** MAC ONLY - Turns a Core CF String into a juce one. */
  10624. static const String cfStringToJuceString (CFStringRef cfString);
  10625. /** MAC ONLY - Turns a juce string into a Core CF one. */
  10626. static CFStringRef juceStringToCFString (const String& s);
  10627. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  10628. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  10629. /** MAC ONLY - Turns an FSRef into a juce string path. */
  10630. static const String makePathFromFSRef (FSRef* file);
  10631. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  10632. their precomposed equivalents.
  10633. */
  10634. static const String convertToPrecomposedUnicode (const String& s);
  10635. /** MAC ONLY - Gets the type of a file from the file's resources. */
  10636. static OSType getTypeOfFile (const String& filename);
  10637. /** MAC ONLY - Returns true if this file is actually a bundle. */
  10638. static bool isBundle (const String& filename);
  10639. /** MAC ONLY - Adds an item to the dock */
  10640. static void addItemToDock (const File& file);
  10641. /** MAC ONLY - Returns the current OS version number.
  10642. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  10643. */
  10644. static int getOSXMinorVersionNumber();
  10645. #endif
  10646. #if JUCE_WINDOWS || DOXYGEN
  10647. // Some registry helper functions:
  10648. /** WIN32 ONLY - Returns a string from the registry.
  10649. The path is a string for the entire path of a value in the registry,
  10650. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  10651. */
  10652. static const String getRegistryValue (const String& regValuePath,
  10653. const String& defaultValue = String::empty);
  10654. /** WIN32 ONLY - Sets a registry value as a string.
  10655. This will take care of creating any groups needed to get to the given
  10656. registry value.
  10657. */
  10658. static void setRegistryValue (const String& regValuePath,
  10659. const String& value);
  10660. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  10661. static bool registryValueExists (const String& regValuePath);
  10662. /** WIN32 ONLY - Deletes a registry value. */
  10663. static void deleteRegistryValue (const String& regValuePath);
  10664. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  10665. static void deleteRegistryKey (const String& regKeyPath);
  10666. /** WIN32 ONLY - Creates a file association in the registry.
  10667. This lets you set the exe that should be launched by a given file extension.
  10668. @param fileExtension the file extension to associate, including the
  10669. initial dot, e.g. ".txt"
  10670. @param symbolicDescription a space-free short token to identify the file type
  10671. @param fullDescription a human-readable description of the file type
  10672. @param targetExecutable the executable that should be launched
  10673. @param iconResourceNumber the icon that gets displayed for the file type will be
  10674. found by looking up this resource number in the
  10675. executable. Pass 0 here to not use an icon
  10676. */
  10677. static void registerFileAssociation (const String& fileExtension,
  10678. const String& symbolicDescription,
  10679. const String& fullDescription,
  10680. const File& targetExecutable,
  10681. int iconResourceNumber);
  10682. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  10683. In a normal Juce application this will be set to the module handle
  10684. of the application executable.
  10685. If you're writing a DLL using Juce and plan to use any Juce messaging or
  10686. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  10687. to set the correct module handle in your DllMain() function, because
  10688. the win32 system relies on the correct instance handle when opening windows.
  10689. */
  10690. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  10691. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  10692. @see getCurrentModuleInstanceHandle()
  10693. */
  10694. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10695. /** WIN32 ONLY - Gets the command-line params as a string.
  10696. This is needed to avoid unicode problems with the argc type params.
  10697. */
  10698. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  10699. #endif
  10700. /** Clears the floating point unit's flags.
  10701. Only has an effect under win32, currently.
  10702. */
  10703. static void fpuReset();
  10704. #if JUCE_LINUX || JUCE_WINDOWS
  10705. /** Loads a dynamically-linked library into the process's address space.
  10706. @param pathOrFilename the platform-dependent name and search path
  10707. @returns a handle which can be used by getProcedureEntryPoint(), or
  10708. zero if it fails.
  10709. @see freeDynamicLibrary, getProcedureEntryPoint
  10710. */
  10711. static void* loadDynamicLibrary (const String& pathOrFilename);
  10712. /** Frees a dynamically-linked library.
  10713. @param libraryHandle a handle created by loadDynamicLibrary
  10714. @see loadDynamicLibrary, getProcedureEntryPoint
  10715. */
  10716. static void freeDynamicLibrary (void* libraryHandle);
  10717. /** Finds a procedure call in a dynamically-linked library.
  10718. @param libraryHandle a library handle returned by loadDynamicLibrary
  10719. @param procedureName the name of the procedure call to try to load
  10720. @returns a pointer to the function if found, or 0 if it fails
  10721. @see loadDynamicLibrary
  10722. */
  10723. static void* getProcedureEntryPoint (void* libraryHandle,
  10724. const String& procedureName);
  10725. #endif
  10726. #if JUCE_LINUX || DOXYGEN
  10727. #endif
  10728. private:
  10729. PlatformUtilities();
  10730. PlatformUtilities (const PlatformUtilities&);
  10731. PlatformUtilities& operator= (const PlatformUtilities&);
  10732. };
  10733. #if JUCE_MAC || JUCE_IPHONE
  10734. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10735. using RAII.
  10736. */
  10737. class ScopedAutoReleasePool
  10738. {
  10739. public:
  10740. ScopedAutoReleasePool();
  10741. ~ScopedAutoReleasePool();
  10742. private:
  10743. void* pool;
  10744. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  10745. ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  10746. };
  10747. #endif
  10748. #if JUCE_LINUX
  10749. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  10750. using an RAII approach.
  10751. */
  10752. class ScopedXLock
  10753. {
  10754. public:
  10755. /** Creating a ScopedXLock object locks the X display.
  10756. This uses XLockDisplay() to grab the display that Juce is using.
  10757. */
  10758. ScopedXLock();
  10759. /** Deleting a ScopedXLock object unlocks the X display.
  10760. This calls XUnlockDisplay() to release the lock.
  10761. */
  10762. ~ScopedXLock();
  10763. };
  10764. #endif
  10765. #if JUCE_MAC
  10766. /**
  10767. A wrapper class for picking up events from an Apple IR remote control device.
  10768. To use it, just create a subclass of this class, implementing the buttonPressed()
  10769. callback, then call start() and stop() to start or stop receiving events.
  10770. */
  10771. class JUCE_API AppleRemoteDevice
  10772. {
  10773. public:
  10774. AppleRemoteDevice();
  10775. virtual ~AppleRemoteDevice();
  10776. /** The set of buttons that may be pressed.
  10777. @see buttonPressed
  10778. */
  10779. enum ButtonType
  10780. {
  10781. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10782. playButton, /**< The play button. */
  10783. plusButton, /**< The plus or volume-up button. */
  10784. minusButton, /**< The minus or volume-down button. */
  10785. rightButton, /**< The right button (if it's held for a short time). */
  10786. leftButton, /**< The left button (if it's held for a short time). */
  10787. rightButton_Long, /**< The right button (if it's held for a long time). */
  10788. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10789. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10790. playButtonSleepMode,
  10791. switched
  10792. };
  10793. /** Override this method to receive the callback about a button press.
  10794. The callback will happen on the application's message thread.
  10795. Some buttons trigger matching up and down events, in which the isDown parameter
  10796. will be true and then false. Others only send a single event when the
  10797. button is pressed.
  10798. */
  10799. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10800. /** Starts the device running and responding to events.
  10801. Returns true if it managed to open the device.
  10802. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10803. and will not be available to any other part of the system. If
  10804. false, it will be shared with other apps.
  10805. @see stop
  10806. */
  10807. bool start (const bool inExclusiveMode);
  10808. /** Stops the device running.
  10809. @see start
  10810. */
  10811. void stop();
  10812. /** Returns true if the device has been started successfully.
  10813. */
  10814. bool isActive() const;
  10815. /** Returns the ID number of the remote, if it has sent one.
  10816. */
  10817. int getRemoteId() const { return remoteId; }
  10818. juce_UseDebuggingNewOperator
  10819. /** @internal */
  10820. void handleCallbackInternal();
  10821. private:
  10822. void* device;
  10823. void* queue;
  10824. int remoteId;
  10825. bool open (const bool openInExclusiveMode);
  10826. AppleRemoteDevice (const AppleRemoteDevice&);
  10827. AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  10828. };
  10829. #endif
  10830. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10831. /*** End of inlined file: juce_PlatformUtilities.h ***/
  10832. #endif
  10833. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10834. /*** Start of inlined file: juce_Random.h ***/
  10835. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10836. #define __JUCE_RANDOM_JUCEHEADER__
  10837. /**
  10838. A simple pseudo-random number generator.
  10839. */
  10840. class JUCE_API Random
  10841. {
  10842. public:
  10843. /** Creates a Random object based on a seed value.
  10844. For a given seed value, the subsequent numbers generated by this object
  10845. will be predictable, so a good idea is to set this value based
  10846. on the time, e.g.
  10847. new Random (Time::currentTimeMillis())
  10848. */
  10849. explicit Random (int64 seedValue) throw();
  10850. /** Destructor. */
  10851. ~Random() throw();
  10852. /** Returns the next random 32 bit integer.
  10853. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  10854. */
  10855. int nextInt() throw();
  10856. /** Returns the next random number, limited to a given range.
  10857. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  10858. */
  10859. int nextInt (int maxValue) throw();
  10860. /** Returns the next 64-bit random number.
  10861. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  10862. */
  10863. int64 nextInt64() throw();
  10864. /** Returns the next random floating-point number.
  10865. @returns a random value in the range 0 to 1.0
  10866. */
  10867. float nextFloat() throw();
  10868. /** Returns the next random floating-point number.
  10869. @returns a random value in the range 0 to 1.0
  10870. */
  10871. double nextDouble() throw();
  10872. /** Returns the next random boolean value.
  10873. */
  10874. bool nextBool() throw();
  10875. /** Returns a BigInteger containing a random number.
  10876. @returns a random value in the range 0 to (maximumValue - 1).
  10877. */
  10878. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  10879. /** Sets a range of bits in a BigInteger to random values. */
  10880. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  10881. /** To avoid the overhead of having to create a new Random object whenever
  10882. you need a number, this is a shared application-wide object that
  10883. can be used.
  10884. It's not thread-safe though, so threads should use their own Random object.
  10885. */
  10886. static Random& getSystemRandom() throw();
  10887. /** Resets this Random object to a given seed value. */
  10888. void setSeed (int64 newSeed) throw();
  10889. /** Merges this object's seed with another value.
  10890. This sets the seed to be a value created by combining the current seed and this
  10891. new value.
  10892. */
  10893. void combineSeed (int64 seedValue) throw();
  10894. /** Reseeds this generator using a value generated from various semi-random system
  10895. properties like the current time, etc.
  10896. Because this function convolves the time with the last seed value, calling
  10897. it repeatedly will increase the randomness of the final result.
  10898. */
  10899. void setSeedRandomly();
  10900. juce_UseDebuggingNewOperator
  10901. private:
  10902. int64 seed;
  10903. };
  10904. #endif // __JUCE_RANDOM_JUCEHEADER__
  10905. /*** End of inlined file: juce_Random.h ***/
  10906. #endif
  10907. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  10908. #endif
  10909. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10910. /*** Start of inlined file: juce_Singleton.h ***/
  10911. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10912. #define __JUCE_SINGLETON_JUCEHEADER__
  10913. /**
  10914. Macro to declare member variables and methods for a singleton class.
  10915. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  10916. to the class's definition.
  10917. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  10918. implementation code.
  10919. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  10920. destructor, in case it is deleted by other means than deleteInstance()
  10921. Clients can then call the static method MyClass::getInstance() to get a pointer
  10922. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  10923. no instance currently exists.
  10924. e.g. @code
  10925. class MySingleton
  10926. {
  10927. public:
  10928. MySingleton()
  10929. {
  10930. }
  10931. ~MySingleton()
  10932. {
  10933. // this ensures that no dangling pointers are left when the
  10934. // singleton is deleted.
  10935. clearSingletonInstance();
  10936. }
  10937. juce_DeclareSingleton (MySingleton, false)
  10938. };
  10939. juce_ImplementSingleton (MySingleton)
  10940. // example of usage:
  10941. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  10942. ...
  10943. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  10944. @endcode
  10945. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10946. than once during the process's lifetime - i.e. after you've created and deleted the
  10947. object, getInstance() will refuse to create another one. This can be useful to stop
  10948. objects being accidentally re-created during your app's shutdown code.
  10949. If you know that your object will only be created and deleted by a single thread, you
  10950. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  10951. of this one.
  10952. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  10953. */
  10954. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  10955. \
  10956. static classname* _singletonInstance; \
  10957. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  10958. \
  10959. static classname* JUCE_CALLTYPE getInstance() \
  10960. { \
  10961. if (_singletonInstance == 0) \
  10962. {\
  10963. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10964. \
  10965. if (_singletonInstance == 0) \
  10966. { \
  10967. static bool alreadyInside = false; \
  10968. static bool createdOnceAlready = false; \
  10969. \
  10970. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10971. jassert (! problem); \
  10972. if (! problem) \
  10973. { \
  10974. createdOnceAlready = true; \
  10975. alreadyInside = true; \
  10976. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10977. alreadyInside = false; \
  10978. \
  10979. _singletonInstance = newObject; \
  10980. } \
  10981. } \
  10982. } \
  10983. \
  10984. return _singletonInstance; \
  10985. } \
  10986. \
  10987. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() throw() \
  10988. { \
  10989. return _singletonInstance; \
  10990. } \
  10991. \
  10992. static void JUCE_CALLTYPE deleteInstance() \
  10993. { \
  10994. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10995. if (_singletonInstance != 0) \
  10996. { \
  10997. classname* const old = _singletonInstance; \
  10998. _singletonInstance = 0; \
  10999. delete old; \
  11000. } \
  11001. } \
  11002. \
  11003. void clearSingletonInstance() throw() \
  11004. { \
  11005. if (_singletonInstance == this) \
  11006. _singletonInstance = 0; \
  11007. }
  11008. /** This is a counterpart to the juce_DeclareSingleton macro.
  11009. After adding the juce_DeclareSingleton to the class definition, this macro has
  11010. to be used in the cpp file.
  11011. */
  11012. #define juce_ImplementSingleton(classname) \
  11013. \
  11014. classname* classname::_singletonInstance = 0; \
  11015. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  11016. /**
  11017. Macro to declare member variables and methods for a singleton class.
  11018. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  11019. section to make access to it thread-safe. If you know that your object will
  11020. only ever be created or deleted by a single thread, then this is a
  11021. more efficient version to use.
  11022. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  11023. than once during the process's lifetime - i.e. after you've created and deleted the
  11024. object, getInstance() will refuse to create another one. This can be useful to stop
  11025. objects being accidentally re-created during your app's shutdown code.
  11026. See the documentation for juce_DeclareSingleton for more information about
  11027. how to use it, the only difference being that you have to use
  11028. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11029. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  11030. */
  11031. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  11032. \
  11033. static classname* _singletonInstance; \
  11034. \
  11035. static classname* getInstance() \
  11036. { \
  11037. if (_singletonInstance == 0) \
  11038. { \
  11039. static bool alreadyInside = false; \
  11040. static bool createdOnceAlready = false; \
  11041. \
  11042. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  11043. jassert (! problem); \
  11044. if (! problem) \
  11045. { \
  11046. createdOnceAlready = true; \
  11047. alreadyInside = true; \
  11048. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  11049. alreadyInside = false; \
  11050. \
  11051. _singletonInstance = newObject; \
  11052. } \
  11053. } \
  11054. \
  11055. return _singletonInstance; \
  11056. } \
  11057. \
  11058. static inline classname* getInstanceWithoutCreating() throw() \
  11059. { \
  11060. return _singletonInstance; \
  11061. } \
  11062. \
  11063. static void deleteInstance() \
  11064. { \
  11065. if (_singletonInstance != 0) \
  11066. { \
  11067. classname* const old = _singletonInstance; \
  11068. _singletonInstance = 0; \
  11069. delete old; \
  11070. } \
  11071. } \
  11072. \
  11073. void clearSingletonInstance() throw() \
  11074. { \
  11075. if (_singletonInstance == this) \
  11076. _singletonInstance = 0; \
  11077. }
  11078. /**
  11079. Macro to declare member variables and methods for a singleton class.
  11080. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  11081. for recursion or repeated instantiation. It's intended for use as a lightweight
  11082. version of a singleton, where you're using it in very straightforward
  11083. circumstances and don't need the extra checking.
  11084. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  11085. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  11086. See the documentation for juce_DeclareSingleton for more information about
  11087. how to use it, the only difference being that you have to use
  11088. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11089. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  11090. */
  11091. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  11092. \
  11093. static classname* _singletonInstance; \
  11094. \
  11095. static classname* getInstance() \
  11096. { \
  11097. if (_singletonInstance == 0) \
  11098. _singletonInstance = new classname(); \
  11099. \
  11100. return _singletonInstance; \
  11101. } \
  11102. \
  11103. static inline classname* getInstanceWithoutCreating() throw() \
  11104. { \
  11105. return _singletonInstance; \
  11106. } \
  11107. \
  11108. static void deleteInstance() \
  11109. { \
  11110. if (_singletonInstance != 0) \
  11111. { \
  11112. classname* const old = _singletonInstance; \
  11113. _singletonInstance = 0; \
  11114. delete old; \
  11115. } \
  11116. } \
  11117. \
  11118. void clearSingletonInstance() throw() \
  11119. { \
  11120. if (_singletonInstance == this) \
  11121. _singletonInstance = 0; \
  11122. }
  11123. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  11124. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  11125. to the class definition, this macro has to be used somewhere in the cpp file.
  11126. */
  11127. #define juce_ImplementSingleton_SingleThreaded(classname) \
  11128. \
  11129. classname* classname::_singletonInstance = 0;
  11130. #endif // __JUCE_SINGLETON_JUCEHEADER__
  11131. /*** End of inlined file: juce_Singleton.h ***/
  11132. #endif
  11133. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  11134. #endif
  11135. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11136. /*** Start of inlined file: juce_SystemStats.h ***/
  11137. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11138. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  11139. /**
  11140. Contains methods for finding out about the current hardware and OS configuration.
  11141. */
  11142. class JUCE_API SystemStats
  11143. {
  11144. public:
  11145. /** Returns the current version of JUCE,
  11146. (just in case you didn't already know at compile-time.)
  11147. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  11148. */
  11149. static const String getJUCEVersion();
  11150. /** The set of possible results of the getOperatingSystemType() method.
  11151. */
  11152. enum OperatingSystemType
  11153. {
  11154. UnknownOS = 0,
  11155. MacOSX = 0x1000,
  11156. Linux = 0x2000,
  11157. Win95 = 0x4001,
  11158. Win98 = 0x4002,
  11159. WinNT351 = 0x4103,
  11160. WinNT40 = 0x4104,
  11161. Win2000 = 0x4105,
  11162. WinXP = 0x4106,
  11163. WinVista = 0x4107,
  11164. Windows7 = 0x4108,
  11165. Windows = 0x4000, /**< To test whether any version of Windows is running,
  11166. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  11167. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  11168. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  11169. };
  11170. /** Returns the type of operating system we're running on.
  11171. @returns one of the values from the OperatingSystemType enum.
  11172. @see getOperatingSystemName
  11173. */
  11174. static OperatingSystemType getOperatingSystemType();
  11175. /** Returns the name of the type of operating system we're running on.
  11176. @returns a string describing the OS type.
  11177. @see getOperatingSystemType
  11178. */
  11179. static const String getOperatingSystemName();
  11180. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  11181. */
  11182. static bool isOperatingSystem64Bit();
  11183. /** Returns the current user's name, if available.
  11184. @see getFullUserName()
  11185. */
  11186. static const String getLogonName();
  11187. /** Returns the current user's full name, if available.
  11188. On some OSes, this may just return the same value as getLogonName().
  11189. @see getLogonName()
  11190. */
  11191. static const String getFullUserName();
  11192. // CPU and memory information..
  11193. /** Returns the approximate CPU speed.
  11194. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  11195. what year you're reading this...)
  11196. */
  11197. static int getCpuSpeedInMegaherz();
  11198. /** Returns a string to indicate the CPU vendor.
  11199. Might not be known on some systems.
  11200. */
  11201. static const String getCpuVendor();
  11202. /** Checks whether Intel MMX instructions are available. */
  11203. static bool hasMMX() throw() { return cpuFlags.hasMMX; }
  11204. /** Checks whether Intel SSE instructions are available. */
  11205. static bool hasSSE() throw() { return cpuFlags.hasSSE; }
  11206. /** Checks whether Intel SSE2 instructions are available. */
  11207. static bool hasSSE2() throw() { return cpuFlags.hasSSE2; }
  11208. /** Checks whether AMD 3DNOW instructions are available. */
  11209. static bool has3DNow() throw() { return cpuFlags.has3DNow; }
  11210. /** Returns the number of CPUs.
  11211. */
  11212. static int getNumCpus() throw() { return cpuFlags.numCpus; }
  11213. /** Finds out how much RAM is in the machine.
  11214. @returns the approximate number of megabytes of memory, or zero if
  11215. something goes wrong when finding out.
  11216. */
  11217. static int getMemorySizeInMegabytes();
  11218. /** Returns the system page-size.
  11219. This is only used by programmers with beards.
  11220. */
  11221. static int getPageSize();
  11222. /** Returns a list of MAC addresses found on this machine.
  11223. @param addresses an array into which the MAC addresses should be copied
  11224. @param maxNum the number of elements in this array
  11225. @param littleEndian the endianness of the numbers to return. If this is true,
  11226. the least-significant byte of each number is the first byte
  11227. of the mac address. If false, the least significant byte is
  11228. the last number. Note that the default values of this parameter
  11229. are different on Mac/PC to avoid breaking old software that was
  11230. written before this parameter was added (when the two systems
  11231. defaulted to using different endiannesses). In newer
  11232. software you probably want to specify an explicit value
  11233. for this.
  11234. @returns the number of MAC addresses that were found
  11235. */
  11236. static int getMACAddresses (int64* addresses, int maxNum,
  11237. #if JUCE_MAC
  11238. bool littleEndian = true);
  11239. #else
  11240. bool littleEndian = false);
  11241. #endif
  11242. /** Returns a list of MAC addresses found on this machine.
  11243. @returns an array of strings containing the MAC addresses that were found
  11244. */
  11245. static const StringArray getMACAddressStrings();
  11246. // not-for-public-use platform-specific method gets called at startup to initialise things.
  11247. static void initialiseStats();
  11248. private:
  11249. struct CPUFlags
  11250. {
  11251. int numCpus;
  11252. bool hasMMX : 1;
  11253. bool hasSSE : 1;
  11254. bool hasSSE2 : 1;
  11255. bool has3DNow : 1;
  11256. };
  11257. static CPUFlags cpuFlags;
  11258. SystemStats();
  11259. SystemStats (const SystemStats&);
  11260. SystemStats& operator= (const SystemStats&);
  11261. };
  11262. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  11263. /*** End of inlined file: juce_SystemStats.h ***/
  11264. #endif
  11265. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  11266. #endif
  11267. #ifndef __JUCE_TIME_JUCEHEADER__
  11268. #endif
  11269. #ifndef __JUCE_UUID_JUCEHEADER__
  11270. /*** Start of inlined file: juce_Uuid.h ***/
  11271. #ifndef __JUCE_UUID_JUCEHEADER__
  11272. #define __JUCE_UUID_JUCEHEADER__
  11273. /**
  11274. A universally unique 128-bit identifier.
  11275. This class generates very random unique numbers based on the system time
  11276. and MAC addresses if any are available. It's extremely unlikely that two identical
  11277. UUIDs would ever be created by chance.
  11278. The class includes methods for saving the ID as a string or as raw binary data.
  11279. */
  11280. class JUCE_API Uuid
  11281. {
  11282. public:
  11283. /** Creates a new unique ID. */
  11284. Uuid();
  11285. /** Destructor. */
  11286. ~Uuid() throw();
  11287. /** Creates a copy of another UUID. */
  11288. Uuid (const Uuid& other);
  11289. /** Copies another UUID. */
  11290. Uuid& operator= (const Uuid& other);
  11291. /** Returns true if the ID is zero. */
  11292. bool isNull() const throw();
  11293. /** Compares two UUIDs. */
  11294. bool operator== (const Uuid& other) const;
  11295. /** Compares two UUIDs. */
  11296. bool operator!= (const Uuid& other) const;
  11297. /** Returns a stringified version of this UUID.
  11298. A Uuid object can later be reconstructed from this string using operator= or
  11299. the constructor that takes a string parameter.
  11300. @returns a 32 character hex string.
  11301. */
  11302. const String toString() const;
  11303. /** Creates an ID from an encoded string version.
  11304. @see toString
  11305. */
  11306. Uuid (const String& uuidString);
  11307. /** Copies from a stringified UUID.
  11308. The string passed in should be one that was created with the toString() method.
  11309. */
  11310. Uuid& operator= (const String& uuidString);
  11311. /** Returns a pointer to the internal binary representation of the ID.
  11312. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  11313. the constructor or operator= method that takes an array of uint8s.
  11314. */
  11315. const uint8* getRawData() const throw() { return value.asBytes; }
  11316. /** Creates a UUID from a 16-byte array.
  11317. @see getRawData
  11318. */
  11319. Uuid (const uint8* const rawData);
  11320. /** Sets this UUID from 16-bytes of raw data. */
  11321. Uuid& operator= (const uint8* const rawData);
  11322. juce_UseDebuggingNewOperator
  11323. private:
  11324. union
  11325. {
  11326. uint8 asBytes [16];
  11327. int asInt[4];
  11328. int64 asInt64[2];
  11329. } value;
  11330. };
  11331. #endif // __JUCE_UUID_JUCEHEADER__
  11332. /*** End of inlined file: juce_Uuid.h ***/
  11333. #endif
  11334. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11335. /*** Start of inlined file: juce_BlowFish.h ***/
  11336. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11337. #define __JUCE_BLOWFISH_JUCEHEADER__
  11338. /**
  11339. BlowFish encryption class.
  11340. */
  11341. class JUCE_API BlowFish
  11342. {
  11343. public:
  11344. /** Creates an object that can encode/decode based on the specified key.
  11345. The key data can be up to 72 bytes long.
  11346. */
  11347. BlowFish (const void* keyData, int keyBytes);
  11348. /** Creates a copy of another blowfish object. */
  11349. BlowFish (const BlowFish& other);
  11350. /** Copies another blowfish object. */
  11351. BlowFish& operator= (const BlowFish& other);
  11352. /** Destructor. */
  11353. ~BlowFish();
  11354. /** Encrypts a pair of 32-bit integers. */
  11355. void encrypt (uint32& data1, uint32& data2) const throw();
  11356. /** Decrypts a pair of 32-bit integers. */
  11357. void decrypt (uint32& data1, uint32& data2) const throw();
  11358. juce_UseDebuggingNewOperator
  11359. private:
  11360. uint32 p[18];
  11361. HeapBlock <uint32> s[4];
  11362. uint32 F (uint32 x) const throw();
  11363. };
  11364. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  11365. /*** End of inlined file: juce_BlowFish.h ***/
  11366. #endif
  11367. #ifndef __JUCE_MD5_JUCEHEADER__
  11368. /*** Start of inlined file: juce_MD5.h ***/
  11369. #ifndef __JUCE_MD5_JUCEHEADER__
  11370. #define __JUCE_MD5_JUCEHEADER__
  11371. /**
  11372. MD5 checksum class.
  11373. Create one of these with a block of source data or a string, and it calculates the
  11374. MD5 checksum of that data.
  11375. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  11376. */
  11377. class JUCE_API MD5
  11378. {
  11379. public:
  11380. /** Creates a null MD5 object. */
  11381. MD5();
  11382. /** Creates a copy of another MD5. */
  11383. MD5 (const MD5& other);
  11384. /** Copies another MD5. */
  11385. MD5& operator= (const MD5& other);
  11386. /** Creates a checksum for a block of binary data. */
  11387. explicit MD5 (const MemoryBlock& data);
  11388. /** Creates a checksum for a block of binary data. */
  11389. MD5 (const void* data, const size_t numBytes);
  11390. /** Creates a checksum for a string.
  11391. Note that this operates on the string as a block of unicode characters, so the
  11392. result you get will differ from the value you'd get if the string was treated
  11393. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  11394. of this method with a checksum created by a different framework, which may have
  11395. used a different encoding.
  11396. */
  11397. explicit MD5 (const String& text);
  11398. /** Creates a checksum for the input from a stream.
  11399. This will read up to the given number of bytes from the stream, and produce the
  11400. checksum of that. If the number of bytes to read is negative, it'll read
  11401. until the stream is exhausted.
  11402. */
  11403. MD5 (InputStream& input, int64 numBytesToRead = -1);
  11404. /** Creates a checksum for a file. */
  11405. explicit MD5 (const File& file);
  11406. /** Destructor. */
  11407. ~MD5();
  11408. /** Returns the checksum as a 16-byte block of data. */
  11409. const MemoryBlock getRawChecksumData() const;
  11410. /** Returns the checksum as a 32-digit hex string. */
  11411. const String toHexString() const;
  11412. /** Compares this to another MD5. */
  11413. bool operator== (const MD5& other) const;
  11414. /** Compares this to another MD5. */
  11415. bool operator!= (const MD5& other) const;
  11416. juce_UseDebuggingNewOperator
  11417. private:
  11418. uint8 result [16];
  11419. struct ProcessContext
  11420. {
  11421. uint8 buffer [64];
  11422. uint32 state [4];
  11423. uint32 count [2];
  11424. ProcessContext();
  11425. void processBlock (const void* data, size_t dataSize);
  11426. void transform (const void* buffer);
  11427. void finish (void* const result);
  11428. };
  11429. void processStream (InputStream& input, int64 numBytesToRead);
  11430. };
  11431. #endif // __JUCE_MD5_JUCEHEADER__
  11432. /*** End of inlined file: juce_MD5.h ***/
  11433. #endif
  11434. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11435. /*** Start of inlined file: juce_Primes.h ***/
  11436. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11437. #define __JUCE_PRIMES_JUCEHEADER__
  11438. /**
  11439. Prime number creation class.
  11440. This class contains static methods for generating and testing prime numbers.
  11441. @see BigInteger
  11442. */
  11443. class JUCE_API Primes
  11444. {
  11445. public:
  11446. /** Creates a random prime number with a given bit-length.
  11447. The certainty parameter specifies how many iterations to use when testing
  11448. for primality. A safe value might be anything over about 20-30.
  11449. The randomSeeds parameter lets you optionally pass it a set of values with
  11450. which to seed the random number generation, improving the security of the
  11451. keys generated.
  11452. */
  11453. static const BigInteger createProbablePrime (int bitLength,
  11454. int certainty,
  11455. const int* randomSeeds = 0,
  11456. int numRandomSeeds = 0);
  11457. /** Tests a number to see if it's prime.
  11458. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  11459. whether the number is prime.
  11460. The certainty parameter specifies how many iterations to use when testing - a
  11461. safe value might be anything over about 20-30.
  11462. */
  11463. static bool isProbablyPrime (const BigInteger& number, int certainty);
  11464. private:
  11465. Primes();
  11466. Primes (const Primes&);
  11467. Primes& operator= (const Primes&);
  11468. };
  11469. #endif // __JUCE_PRIMES_JUCEHEADER__
  11470. /*** End of inlined file: juce_Primes.h ***/
  11471. #endif
  11472. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11473. /*** Start of inlined file: juce_RSAKey.h ***/
  11474. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11475. #define __JUCE_RSAKEY_JUCEHEADER__
  11476. /**
  11477. RSA public/private key-pair encryption class.
  11478. An object of this type makes up one half of a public/private RSA key pair. Use the
  11479. createKeyPair() method to create a matching pair for encoding/decoding.
  11480. */
  11481. class JUCE_API RSAKey
  11482. {
  11483. public:
  11484. /** Creates a null key object.
  11485. Initialise a pair of objects for use with the createKeyPair() method.
  11486. */
  11487. RSAKey();
  11488. /** Loads a key from an encoded string representation.
  11489. This reloads a key from a string created by the toString() method.
  11490. */
  11491. explicit RSAKey (const String& stringRepresentation);
  11492. /** Destructor. */
  11493. ~RSAKey();
  11494. bool operator== (const RSAKey& other) const throw();
  11495. bool operator!= (const RSAKey& other) const throw();
  11496. /** Turns the key into a string representation.
  11497. This can be reloaded using the constructor that takes a string.
  11498. */
  11499. const String toString() const;
  11500. /** Encodes or decodes a value.
  11501. Call this on the public key object to encode some data, then use the matching
  11502. private key object to decode it.
  11503. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  11504. initialised correctly.
  11505. NOTE: This method dumbly applies this key to this data. If you encode some data
  11506. and then try to decode it with a key that doesn't match, this method will still
  11507. happily do its job and return true, but the result won't be what you were expecting.
  11508. It's your responsibility to check that the result is what you wanted.
  11509. */
  11510. bool applyToValue (BigInteger& value) const;
  11511. /** Creates a public/private key-pair.
  11512. Each key will perform one-way encryption that can only be reversed by
  11513. using the other key.
  11514. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  11515. sizes are more secure, but this method will take longer to execute.
  11516. The randomSeeds parameter lets you optionally pass it a set of values with
  11517. which to seed the random number generation, improving the security of the
  11518. keys generated.
  11519. */
  11520. static void createKeyPair (RSAKey& publicKey,
  11521. RSAKey& privateKey,
  11522. int numBits,
  11523. const int* randomSeeds = 0,
  11524. int numRandomSeeds = 0);
  11525. juce_UseDebuggingNewOperator
  11526. protected:
  11527. BigInteger part1, part2;
  11528. private:
  11529. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  11530. };
  11531. #endif // __JUCE_RSAKEY_JUCEHEADER__
  11532. /*** End of inlined file: juce_RSAKey.h ***/
  11533. #endif
  11534. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11535. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  11536. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11537. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11538. /**
  11539. Searches through a the files in a directory, returning each file that is found.
  11540. A DirectoryIterator will search through a directory and its subdirectories using
  11541. a wildcard filepattern match.
  11542. If you may be finding a large number of files, this is better than
  11543. using File::findChildFiles() because it doesn't block while it finds them
  11544. all, and this is more memory-efficient.
  11545. It can also guess how far it's got using a wildly inaccurate algorithm.
  11546. */
  11547. class JUCE_API DirectoryIterator
  11548. {
  11549. public:
  11550. /** Creates a DirectoryIterator for a given directory.
  11551. After creating one of these, call its next() method to get the
  11552. first file - e.g. @code
  11553. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  11554. while (iter.next())
  11555. {
  11556. File theFileItFound (iter.getFile());
  11557. ... etc
  11558. }
  11559. @endcode
  11560. @param directory the directory to search in
  11561. @param isRecursive whether all the subdirectories should also be searched
  11562. @param wildCard the file pattern to match
  11563. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  11564. whether to look for files, directories, or both.
  11565. */
  11566. DirectoryIterator (const File& directory,
  11567. bool isRecursive,
  11568. const String& wildCard = "*",
  11569. int whatToLookFor = File::findFiles);
  11570. /** Destructor. */
  11571. ~DirectoryIterator();
  11572. /** Moves the iterator along to the next file.
  11573. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11574. false if there are no more matching files.
  11575. */
  11576. bool next();
  11577. /** Moves the iterator along to the next file, and returns various properties of that file.
  11578. If you need to find out details about the file, it's more efficient to call this method than
  11579. to call the normal next() method and then find out the details afterwards.
  11580. All the parameters are optional, so pass null pointers for any items that you're not
  11581. interested in.
  11582. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11583. false if there are no more matching files. If it returns false, then none of the
  11584. parameters will be filled-in.
  11585. */
  11586. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  11587. Time* modTime, Time* creationTime, bool* isReadOnly);
  11588. /** Returns the file that the iterator is currently pointing at.
  11589. The result of this call is only valid after a call to next() has returned true.
  11590. */
  11591. const File getFile() const;
  11592. /** Returns a guess of how far through the search the iterator has got.
  11593. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  11594. very accurate.
  11595. */
  11596. float getEstimatedProgress() const;
  11597. juce_UseDebuggingNewOperator
  11598. private:
  11599. friend class File;
  11600. class NativeIterator
  11601. {
  11602. public:
  11603. NativeIterator (const File& directory, const String& wildCard);
  11604. ~NativeIterator();
  11605. bool next (String& filenameFound,
  11606. bool* isDirectory, bool* isHidden, int64* fileSize,
  11607. Time* modTime, Time* creationTime, bool* isReadOnly);
  11608. class Pimpl;
  11609. juce_UseDebuggingNewOperator
  11610. private:
  11611. friend class DirectoryIterator;
  11612. friend class ScopedPointer<Pimpl>;
  11613. ScopedPointer<Pimpl> pimpl;
  11614. NativeIterator (const NativeIterator&);
  11615. NativeIterator& operator= (const NativeIterator&);
  11616. };
  11617. friend class ScopedPointer<NativeIterator::Pimpl>;
  11618. NativeIterator fileFinder;
  11619. String wildCard, path;
  11620. int index;
  11621. mutable int totalNumFiles;
  11622. const int whatToLookFor;
  11623. const bool isRecursive;
  11624. ScopedPointer <DirectoryIterator> subIterator;
  11625. File currentFile;
  11626. DirectoryIterator (const DirectoryIterator&);
  11627. DirectoryIterator& operator= (const DirectoryIterator&);
  11628. };
  11629. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11630. /*** End of inlined file: juce_DirectoryIterator.h ***/
  11631. #endif
  11632. #ifndef __JUCE_FILE_JUCEHEADER__
  11633. #endif
  11634. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11635. /*** Start of inlined file: juce_FileInputStream.h ***/
  11636. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11637. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11638. /**
  11639. An input stream that reads from a local file.
  11640. @see InputStream, FileOutputStream, File::createInputStream
  11641. */
  11642. class JUCE_API FileInputStream : public InputStream
  11643. {
  11644. public:
  11645. /** Creates a FileInputStream.
  11646. @param fileToRead the file to read from - if the file can't be accessed for some
  11647. reason, then the stream will just contain no data
  11648. */
  11649. explicit FileInputStream (const File& fileToRead);
  11650. /** Destructor. */
  11651. ~FileInputStream();
  11652. const File& getFile() const throw() { return file; }
  11653. int64 getTotalLength();
  11654. int read (void* destBuffer, int maxBytesToRead);
  11655. bool isExhausted();
  11656. int64 getPosition();
  11657. bool setPosition (int64 pos);
  11658. juce_UseDebuggingNewOperator
  11659. private:
  11660. File file;
  11661. void* fileHandle;
  11662. int64 currentPosition, totalSize;
  11663. bool needToSeek;
  11664. FileInputStream (const FileInputStream&);
  11665. FileInputStream& operator= (const FileInputStream&);
  11666. };
  11667. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11668. /*** End of inlined file: juce_FileInputStream.h ***/
  11669. #endif
  11670. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11671. /*** Start of inlined file: juce_FileOutputStream.h ***/
  11672. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11673. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11674. /**
  11675. An output stream that writes into a local file.
  11676. @see OutputStream, FileInputStream, File::createOutputStream
  11677. */
  11678. class JUCE_API FileOutputStream : public OutputStream
  11679. {
  11680. public:
  11681. /** Creates a FileOutputStream.
  11682. If the file doesn't exist, it will first be created. If the file can't be
  11683. created or opened, the failedToOpen() method will return
  11684. true.
  11685. If the file already exists when opened, the stream's write-postion will
  11686. be set to the end of the file. To overwrite an existing file,
  11687. use File::deleteFile() before opening the stream, or use setPosition(0)
  11688. after it's opened (although this won't truncate the file).
  11689. It's better to use File::createOutputStream() to create one of these, rather
  11690. than using the class directly.
  11691. @see TemporaryFile
  11692. */
  11693. FileOutputStream (const File& fileToWriteTo,
  11694. int bufferSizeToUse = 16384);
  11695. /** Destructor. */
  11696. ~FileOutputStream();
  11697. /** Returns the file that this stream is writing to.
  11698. */
  11699. const File& getFile() const { return file; }
  11700. /** Returns true if the stream couldn't be opened for some reason.
  11701. */
  11702. bool failedToOpen() const { return fileHandle == 0; }
  11703. void flush();
  11704. int64 getPosition();
  11705. bool setPosition (int64 pos);
  11706. bool write (const void* data, int numBytes);
  11707. juce_UseDebuggingNewOperator
  11708. private:
  11709. File file;
  11710. void* fileHandle;
  11711. int64 currentPosition;
  11712. int bufferSize, bytesInBuffer;
  11713. HeapBlock <char> buffer;
  11714. void flushInternal();
  11715. int64 getPositionInternal() const;
  11716. FileOutputStream (const FileOutputStream&);
  11717. FileOutputStream& operator= (const FileOutputStream&);
  11718. };
  11719. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11720. /*** End of inlined file: juce_FileOutputStream.h ***/
  11721. #endif
  11722. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11723. /*** Start of inlined file: juce_FileSearchPath.h ***/
  11724. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11725. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  11726. /**
  11727. Encapsulates a set of folders that make up a search path.
  11728. @see File
  11729. */
  11730. class JUCE_API FileSearchPath
  11731. {
  11732. public:
  11733. /** Creates an empty search path. */
  11734. FileSearchPath();
  11735. /** Creates a search path from a string of pathnames.
  11736. The path can be semicolon- or comma-separated, e.g.
  11737. "/foo/bar;/foo/moose;/fish/moose"
  11738. The separate folders are tokenised and added to the search path.
  11739. */
  11740. FileSearchPath (const String& path);
  11741. /** Creates a copy of another search path. */
  11742. FileSearchPath (const FileSearchPath& other);
  11743. /** Destructor. */
  11744. ~FileSearchPath();
  11745. /** Uses a string containing a list of pathnames to re-initialise this list.
  11746. This search path is cleared and the semicolon- or comma-separated folders
  11747. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  11748. */
  11749. FileSearchPath& operator= (const String& path);
  11750. /** Returns the number of folders in this search path.
  11751. @see operator[]
  11752. */
  11753. int getNumPaths() const;
  11754. /** Returns one of the folders in this search path.
  11755. The file returned isn't guaranteed to actually be a valid directory.
  11756. @see getNumPaths
  11757. */
  11758. const File operator[] (int index) const;
  11759. /** Returns the search path as a semicolon-separated list of directories. */
  11760. const String toString() const;
  11761. /** Adds a new directory to the search path.
  11762. The new directory is added to the end of the list if the insertIndex parameter is
  11763. less than zero, otherwise it is inserted at the given index.
  11764. */
  11765. void add (const File& directoryToAdd,
  11766. int insertIndex = -1);
  11767. /** Adds a new directory to the search path if it's not already in there. */
  11768. void addIfNotAlreadyThere (const File& directoryToAdd);
  11769. /** Removes a directory from the search path. */
  11770. void remove (int indexToRemove);
  11771. /** Merges another search path into this one.
  11772. This will remove any duplicate directories.
  11773. */
  11774. void addPath (const FileSearchPath& other);
  11775. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  11776. If the search is intended to be recursive, there's no point having nested folders in the search
  11777. path, because they'll just get searched twice and you'll get duplicate results.
  11778. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  11779. */
  11780. void removeRedundantPaths();
  11781. /** Removes any directories that don't actually exist. */
  11782. void removeNonExistentPaths();
  11783. /** Searches the path for a wildcard.
  11784. This will search all the directories in the search path in order, adding any
  11785. matching files to the results array.
  11786. @param results an array to append the results to
  11787. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  11788. return files, directories, or both.
  11789. @param searchRecursively whether to recursively search the subdirectories too
  11790. @param wildCardPattern a pattern to match against the filenames
  11791. @returns the number of files added to the array
  11792. @see File::findChildFiles
  11793. */
  11794. int findChildFiles (Array<File>& results,
  11795. int whatToLookFor,
  11796. bool searchRecursively,
  11797. const String& wildCardPattern = "*") const;
  11798. /** Finds out whether a file is inside one of the path's directories.
  11799. This will return true if the specified file is a child of one of the
  11800. directories specified by this path. Note that this doesn't actually do any
  11801. searching or check that the files exist - it just looks at the pathnames
  11802. to work out whether the file would be inside a directory.
  11803. @param fileToCheck the file to look for
  11804. @param checkRecursively if true, then this will return true if the file is inside a
  11805. subfolder of one of the path's directories (at any depth). If false
  11806. it will only return true if the file is actually a direct child
  11807. of one of the directories.
  11808. @see File::isAChildOf
  11809. */
  11810. bool isFileInPath (const File& fileToCheck,
  11811. bool checkRecursively) const;
  11812. juce_UseDebuggingNewOperator
  11813. private:
  11814. StringArray directories;
  11815. void init (const String& path);
  11816. };
  11817. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  11818. /*** End of inlined file: juce_FileSearchPath.h ***/
  11819. #endif
  11820. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11821. /*** Start of inlined file: juce_NamedPipe.h ***/
  11822. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11823. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  11824. /**
  11825. A cross-process pipe that can have data written to and read from it.
  11826. Two or more processes can use these for inter-process communication.
  11827. @see InterprocessConnection
  11828. */
  11829. class JUCE_API NamedPipe
  11830. {
  11831. public:
  11832. /** Creates a NamedPipe. */
  11833. NamedPipe();
  11834. /** Destructor. */
  11835. ~NamedPipe();
  11836. /** Tries to open a pipe that already exists.
  11837. Returns true if it succeeds.
  11838. */
  11839. bool openExisting (const String& pipeName);
  11840. /** Tries to create a new pipe.
  11841. Returns true if it succeeds.
  11842. */
  11843. bool createNewPipe (const String& pipeName);
  11844. /** Closes the pipe, if it's open. */
  11845. void close();
  11846. /** True if the pipe is currently open. */
  11847. bool isOpen() const;
  11848. /** Returns the last name that was used to try to open this pipe. */
  11849. const String getName() const;
  11850. /** Reads data from the pipe.
  11851. This will block until another thread has written enough data into the pipe to fill
  11852. the number of bytes specified, or until another thread calls the cancelPendingReads()
  11853. method.
  11854. If the operation fails, it returns -1, otherwise, it will return the number of
  11855. bytes read.
  11856. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  11857. this is a maximum timeout for reading from the pipe.
  11858. */
  11859. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  11860. /** Writes some data to the pipe.
  11861. If the operation fails, it returns -1, otherwise, it will return the number of
  11862. bytes written.
  11863. */
  11864. int write (const void* sourceBuffer, int numBytesToWrite,
  11865. int timeOutMilliseconds = 2000);
  11866. /** If any threads are currently blocked on a read operation, this tells them to abort.
  11867. */
  11868. void cancelPendingReads();
  11869. juce_UseDebuggingNewOperator
  11870. private:
  11871. void* internal;
  11872. String currentPipeName;
  11873. CriticalSection lock;
  11874. NamedPipe (const NamedPipe&);
  11875. NamedPipe& operator= (const NamedPipe&);
  11876. bool openInternal (const String& pipeName, const bool createPipe);
  11877. };
  11878. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  11879. /*** End of inlined file: juce_NamedPipe.h ***/
  11880. #endif
  11881. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11882. /*** Start of inlined file: juce_TemporaryFile.h ***/
  11883. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11884. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  11885. /**
  11886. Manages a temporary file, which will be deleted when this object is deleted.
  11887. This object is intended to be used as a stack based object, using its scope
  11888. to make sure the temporary file isn't left lying around.
  11889. For example:
  11890. @code
  11891. {
  11892. File myTargetFile ("~/myfile.txt");
  11893. // this will choose a file called something like "~/myfile_temp239348.txt"
  11894. // which definitely doesn't exist at the time the constructor is called.
  11895. TemporaryFile temp (myTargetFile);
  11896. // create a stream to the temporary file, and write some data to it...
  11897. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  11898. if (out != 0)
  11899. {
  11900. out->write ( ...etc )
  11901. out->flush();
  11902. out = 0; // (deletes the stream)
  11903. // ..now we've finished writing, this will rename the temp file to
  11904. // make it replace the target file we specified above.
  11905. bool succeeded = temp.overwriteTargetFileWithTemporary();
  11906. }
  11907. // ..and even if something went wrong and our overwrite failed,
  11908. // as the TemporaryFile object goes out of scope here, it'll make sure
  11909. // that the temp file gets deleted.
  11910. }
  11911. @endcode
  11912. @see File, FileOutputStream
  11913. */
  11914. class JUCE_API TemporaryFile
  11915. {
  11916. public:
  11917. enum OptionFlags
  11918. {
  11919. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  11920. i.e. its name should start with a dot. */
  11921. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  11922. the file is unique, they should go in brackets rather
  11923. than just being appended (see File::getNonexistentSibling() )*/
  11924. };
  11925. /** Creates a randomly-named temporary file in the default temp directory.
  11926. @param suffix a file suffix to use for the file
  11927. @param optionFlags a combination of the values listed in the OptionFlags enum
  11928. The file will not be created until you write to it. And remember that when
  11929. this object is deleted, the file will also be deleted!
  11930. */
  11931. TemporaryFile (const String& suffix = String::empty,
  11932. int optionFlags = 0);
  11933. /** Creates a temporary file in the same directory as a specified file.
  11934. This is useful if you have a file that you want to overwrite, but don't
  11935. want to harm the original file if the write operation fails. You can
  11936. use this to create a temporary file next to the target file, then
  11937. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  11938. to replace the target file with the one you've just written.
  11939. This class won't create any files until you actually write to them. And remember
  11940. that when this object is deleted, the temporary file will also be deleted!
  11941. @param targetFile the file that you intend to overwrite - the temporary
  11942. file will be created in the same directory as this
  11943. @param optionFlags a combination of the values listed in the OptionFlags enum
  11944. */
  11945. TemporaryFile (const File& targetFile,
  11946. int optionFlags = 0);
  11947. /** Destructor.
  11948. When this object is deleted it will make sure that its temporary file is
  11949. also deleted! If the operation fails, it'll throw an assertion in debug
  11950. mode.
  11951. */
  11952. ~TemporaryFile();
  11953. /** Returns the temporary file. */
  11954. const File getFile() const { return temporaryFile; }
  11955. /** Returns the target file that was specified in the constructor. */
  11956. const File getTargetFile() const { return targetFile; }
  11957. /** Tries to move the temporary file to overwrite the target file that was
  11958. specified in the constructor.
  11959. If you used the constructor that specified a target file, this will attempt
  11960. to replace that file with the temporary one.
  11961. Before calling this, make sure:
  11962. - that you've actually written to the temporary file
  11963. - that you've closed any open streams that you were using to write to it
  11964. - and that you don't have any streams open to the target file, which would
  11965. prevent it being overwritten
  11966. If the file move succeeds, this returns false, and the temporary file will
  11967. have disappeared. If it fails, the temporary file will probably still exist,
  11968. but will be deleted when this object is destroyed.
  11969. */
  11970. bool overwriteTargetFileWithTemporary() const;
  11971. juce_UseDebuggingNewOperator
  11972. private:
  11973. File temporaryFile, targetFile;
  11974. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  11975. TemporaryFile (const TemporaryFile&);
  11976. TemporaryFile& operator= (const TemporaryFile&);
  11977. };
  11978. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  11979. /*** End of inlined file: juce_TemporaryFile.h ***/
  11980. #endif
  11981. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11982. /*** Start of inlined file: juce_ZipFile.h ***/
  11983. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11984. #define __JUCE_ZIPFILE_JUCEHEADER__
  11985. /*** Start of inlined file: juce_InputSource.h ***/
  11986. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  11987. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  11988. /**
  11989. A lightweight object that can create a stream to read some kind of resource.
  11990. This may be used to refer to a file, or some other kind of source, allowing a
  11991. caller to create an input stream that can read from it when required.
  11992. @see FileInputSource
  11993. */
  11994. class JUCE_API InputSource
  11995. {
  11996. public:
  11997. InputSource() throw() {}
  11998. /** Destructor. */
  11999. virtual ~InputSource() {}
  12000. /** Returns a new InputStream to read this item.
  12001. @returns an inputstream that the caller will delete, or 0 if
  12002. the filename isn't found.
  12003. */
  12004. virtual InputStream* createInputStream() = 0;
  12005. /** Returns a new InputStream to read an item, relative.
  12006. @param relatedItemPath the relative pathname of the resource that is required
  12007. @returns an inputstream that the caller will delete, or 0 if
  12008. the item isn't found.
  12009. */
  12010. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  12011. /** Returns a hash code that uniquely represents this item.
  12012. */
  12013. virtual int64 hashCode() const = 0;
  12014. juce_UseDebuggingNewOperator
  12015. };
  12016. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  12017. /*** End of inlined file: juce_InputSource.h ***/
  12018. /**
  12019. Decodes a ZIP file from a stream.
  12020. This can enumerate the items in a ZIP file and can create suitable stream objects
  12021. to read each one.
  12022. */
  12023. class JUCE_API ZipFile
  12024. {
  12025. public:
  12026. /** Creates a ZipFile for a given stream.
  12027. @param inputStream the stream to read from
  12028. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  12029. will be deleted when this ZipFile object is deleted
  12030. */
  12031. ZipFile (InputStream* inputStream,
  12032. bool deleteStreamWhenDestroyed) throw();
  12033. /** Creates a ZipFile based for a file. */
  12034. ZipFile (const File& file);
  12035. /** Creates a ZipFile for an input source.
  12036. The inputSource object will be owned by the zip file, which will delete
  12037. it later when not needed.
  12038. */
  12039. ZipFile (InputSource* inputSource);
  12040. /** Destructor. */
  12041. ~ZipFile() throw();
  12042. /**
  12043. Contains information about one of the entries in a ZipFile.
  12044. @see ZipFile::getEntry
  12045. */
  12046. struct ZipEntry
  12047. {
  12048. /** The name of the file, which may also include a partial pathname. */
  12049. String filename;
  12050. /** The file's original size. */
  12051. unsigned int uncompressedSize;
  12052. /** The last time the file was modified. */
  12053. Time fileTime;
  12054. };
  12055. /** Returns the number of items in the zip file. */
  12056. int getNumEntries() const throw();
  12057. /** Returns a structure that describes one of the entries in the zip file.
  12058. This may return zero if the index is out of range.
  12059. @see ZipFile::ZipEntry
  12060. */
  12061. const ZipEntry* getEntry (int index) const throw();
  12062. /** Returns the index of the first entry with a given filename.
  12063. This uses a case-sensitive comparison to look for a filename in the
  12064. list of entries. It might return -1 if no match is found.
  12065. @see ZipFile::ZipEntry
  12066. */
  12067. int getIndexOfFileName (const String& fileName) const throw();
  12068. /** Returns a structure that describes one of the entries in the zip file.
  12069. This uses a case-sensitive comparison to look for a filename in the
  12070. list of entries. It might return 0 if no match is found.
  12071. @see ZipFile::ZipEntry
  12072. */
  12073. const ZipEntry* getEntry (const String& fileName) const throw();
  12074. /** Sorts the list of entries, based on the filename.
  12075. */
  12076. void sortEntriesByFilename();
  12077. /** Creates a stream that can read from one of the zip file's entries.
  12078. The stream that is returned must be deleted by the caller (and
  12079. zero might be returned if a stream can't be opened for some reason).
  12080. The stream must not be used after the ZipFile object that created
  12081. has been deleted.
  12082. */
  12083. InputStream* createStreamForEntry (int index);
  12084. /** Uncompresses all of the files in the zip file.
  12085. This will expand all the entires into a target directory. The relative
  12086. paths of the entries are used.
  12087. @param targetDirectory the root folder to uncompress to
  12088. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  12089. */
  12090. void uncompressTo (const File& targetDirectory,
  12091. bool shouldOverwriteFiles = true);
  12092. juce_UseDebuggingNewOperator
  12093. private:
  12094. class ZipInputStream;
  12095. class ZipFilenameComparator;
  12096. class ZipEntryInfo;
  12097. friend class ZipInputStream;
  12098. friend class ZipFilenameComparator;
  12099. friend class ZipEntryInfo;
  12100. OwnedArray <ZipEntryInfo> entries;
  12101. CriticalSection lock;
  12102. InputStream* inputStream;
  12103. ScopedPointer <InputStream> streamToDelete;
  12104. ScopedPointer <InputSource> inputSource;
  12105. #if JUCE_DEBUG
  12106. int numOpenStreams;
  12107. #endif
  12108. void init();
  12109. int findEndOfZipEntryTable (InputStream* in, int& numEntries);
  12110. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  12111. ZipFile (const ZipFile&);
  12112. ZipFile& operator= (const ZipFile&);
  12113. };
  12114. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  12115. /*** End of inlined file: juce_ZipFile.h ***/
  12116. #endif
  12117. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12118. /*** Start of inlined file: juce_Socket.h ***/
  12119. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12120. #define __JUCE_SOCKET_JUCEHEADER__
  12121. /**
  12122. A wrapper for a streaming (TCP) socket.
  12123. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12124. sockets, you could also try the InterprocessConnection class.
  12125. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  12126. */
  12127. class JUCE_API StreamingSocket
  12128. {
  12129. public:
  12130. /** Creates an uninitialised socket.
  12131. To connect it, use the connect() method, after which you can read() or write()
  12132. to it.
  12133. To wait for other sockets to connect to this one, the createListener() method
  12134. enters "listener" mode, and can be used to spawn new sockets for each connection
  12135. that comes along.
  12136. */
  12137. StreamingSocket();
  12138. /** Destructor. */
  12139. ~StreamingSocket();
  12140. /** Binds the socket to the specified local port.
  12141. @returns true on success; false may indicate that another socket is already bound
  12142. on the same port
  12143. */
  12144. bool bindToPort (int localPortNumber);
  12145. /** Tries to connect the socket to hostname:port.
  12146. If timeOutMillisecs is 0, then this method will block until the operating system
  12147. rejects the connection (which could take a long time).
  12148. @returns true if it succeeds.
  12149. @see isConnected
  12150. */
  12151. bool connect (const String& remoteHostname,
  12152. int remotePortNumber,
  12153. int timeOutMillisecs = 3000);
  12154. /** True if the socket is currently connected. */
  12155. bool isConnected() const throw() { return connected; }
  12156. /** Closes the connection. */
  12157. void close();
  12158. /** Returns the name of the currently connected host. */
  12159. const String& getHostName() const throw() { return hostName; }
  12160. /** Returns the port number that's currently open. */
  12161. int getPort() const throw() { return portNumber; }
  12162. /** True if the socket is connected to this machine rather than over the network. */
  12163. bool isLocal() const throw();
  12164. /** Waits until the socket is ready for reading or writing.
  12165. If readyForReading is true, it will wait until the socket is ready for
  12166. reading; if false, it will wait until it's ready for writing.
  12167. If the timeout is < 0, it will wait forever, or else will give up after
  12168. the specified time.
  12169. If the socket is ready on return, this returns 1. If it times-out before
  12170. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12171. */
  12172. int waitUntilReady (bool readyForReading,
  12173. int timeoutMsecs) const;
  12174. /** Reads bytes from the socket.
  12175. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12176. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12177. flag is false, the method will return as much data as is currently available
  12178. without blocking.
  12179. @returns the number of bytes read, or -1 if there was an error.
  12180. @see waitUntilReady
  12181. */
  12182. int read (void* destBuffer, int maxBytesToRead,
  12183. bool blockUntilSpecifiedAmountHasArrived);
  12184. /** Writes bytes to the socket from a buffer.
  12185. Note that this method will block unless you have checked the socket is ready
  12186. for writing before calling it (see the waitUntilReady() method).
  12187. @returns the number of bytes written, or -1 if there was an error.
  12188. */
  12189. int write (const void* sourceBuffer, int numBytesToWrite);
  12190. /** Puts this socket into "listener" mode.
  12191. When in this mode, your thread can call waitForNextConnection() repeatedly,
  12192. which will spawn new sockets for each new connection, so that these can
  12193. be handled in parallel by other threads.
  12194. @param portNumber the port number to listen on
  12195. @param localHostName the interface address to listen on - pass an empty
  12196. string to listen on all addresses
  12197. @returns true if it manages to open the socket successfully.
  12198. @see waitForNextConnection
  12199. */
  12200. bool createListener (int portNumber, const String& localHostName = String::empty);
  12201. /** When in "listener" mode, this waits for a connection and spawns it as a new
  12202. socket.
  12203. The object that gets returned will be owned by the caller.
  12204. This method can only be called after using createListener().
  12205. @see createListener
  12206. */
  12207. StreamingSocket* waitForNextConnection() const;
  12208. juce_UseDebuggingNewOperator
  12209. private:
  12210. String hostName;
  12211. int volatile portNumber, handle;
  12212. bool connected, isListener;
  12213. StreamingSocket (const String& hostname, int portNumber, int handle);
  12214. StreamingSocket (const StreamingSocket&);
  12215. StreamingSocket& operator= (const StreamingSocket&);
  12216. };
  12217. /**
  12218. A wrapper for a datagram (UDP) socket.
  12219. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12220. sockets, you could also try the InterprocessConnection class.
  12221. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  12222. */
  12223. class JUCE_API DatagramSocket
  12224. {
  12225. public:
  12226. /**
  12227. Creates an (uninitialised) datagram socket.
  12228. The localPortNumber is the port on which to bind this socket. If this value is 0,
  12229. the port number is assigned by the operating system.
  12230. To use the socket for sending, call the connect() method. This will not immediately
  12231. make a connection, but will save the destination you've provided. After this, you can
  12232. call read() or write().
  12233. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  12234. (may require extra privileges on linux)
  12235. To wait for other sockets to connect to this one, call waitForNextConnection().
  12236. */
  12237. DatagramSocket (int localPortNumber,
  12238. bool enableBroadcasting = false);
  12239. /** Destructor. */
  12240. ~DatagramSocket();
  12241. /** Binds the socket to the specified local port.
  12242. @returns true on success; false may indicate that another socket is already bound
  12243. on the same port
  12244. */
  12245. bool bindToPort (int localPortNumber);
  12246. /** Tries to connect the socket to hostname:port.
  12247. If timeOutMillisecs is 0, then this method will block until the operating system
  12248. rejects the connection (which could take a long time).
  12249. @returns true if it succeeds.
  12250. @see isConnected
  12251. */
  12252. bool connect (const String& remoteHostname,
  12253. int remotePortNumber,
  12254. int timeOutMillisecs = 3000);
  12255. /** True if the socket is currently connected. */
  12256. bool isConnected() const throw() { return connected; }
  12257. /** Closes the connection. */
  12258. void close();
  12259. /** Returns the name of the currently connected host. */
  12260. const String& getHostName() const throw() { return hostName; }
  12261. /** Returns the port number that's currently open. */
  12262. int getPort() const throw() { return portNumber; }
  12263. /** True if the socket is connected to this machine rather than over the network. */
  12264. bool isLocal() const throw();
  12265. /** Waits until the socket is ready for reading or writing.
  12266. If readyForReading is true, it will wait until the socket is ready for
  12267. reading; if false, it will wait until it's ready for writing.
  12268. If the timeout is < 0, it will wait forever, or else will give up after
  12269. the specified time.
  12270. If the socket is ready on return, this returns 1. If it times-out before
  12271. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12272. */
  12273. int waitUntilReady (bool readyForReading,
  12274. int timeoutMsecs) const;
  12275. /** Reads bytes from the socket.
  12276. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12277. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12278. flag is false, the method will return as much data as is currently available
  12279. without blocking.
  12280. @returns the number of bytes read, or -1 if there was an error.
  12281. @see waitUntilReady
  12282. */
  12283. int read (void* destBuffer, int maxBytesToRead,
  12284. bool blockUntilSpecifiedAmountHasArrived);
  12285. /** Writes bytes to the socket from a buffer.
  12286. Note that this method will block unless you have checked the socket is ready
  12287. for writing before calling it (see the waitUntilReady() method).
  12288. @returns the number of bytes written, or -1 if there was an error.
  12289. */
  12290. int write (const void* sourceBuffer, int numBytesToWrite);
  12291. /** This waits for incoming data to be sent, and returns a socket that can be used
  12292. to read it.
  12293. The object that gets returned is owned by the caller, and can't be used for
  12294. sending, but can be used to read the data.
  12295. */
  12296. DatagramSocket* waitForNextConnection() const;
  12297. juce_UseDebuggingNewOperator
  12298. private:
  12299. String hostName;
  12300. int volatile portNumber, handle;
  12301. bool connected, allowBroadcast;
  12302. void* serverAddress;
  12303. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  12304. DatagramSocket (const DatagramSocket&);
  12305. DatagramSocket& operator= (const DatagramSocket&);
  12306. };
  12307. #endif // __JUCE_SOCKET_JUCEHEADER__
  12308. /*** End of inlined file: juce_Socket.h ***/
  12309. #endif
  12310. #ifndef __JUCE_URL_JUCEHEADER__
  12311. /*** Start of inlined file: juce_URL.h ***/
  12312. #ifndef __JUCE_URL_JUCEHEADER__
  12313. #define __JUCE_URL_JUCEHEADER__
  12314. /**
  12315. Represents a URL and has a bunch of useful functions to manipulate it.
  12316. This class can be used to launch URLs in browsers, and also to create
  12317. InputStreams that can read from remote http or ftp sources.
  12318. */
  12319. class JUCE_API URL
  12320. {
  12321. public:
  12322. /** Creates an empty URL. */
  12323. URL();
  12324. /** Creates a URL from a string. */
  12325. URL (const String& url);
  12326. /** Creates a copy of another URL. */
  12327. URL (const URL& other);
  12328. /** Destructor. */
  12329. ~URL();
  12330. /** Copies this URL from another one. */
  12331. URL& operator= (const URL& other);
  12332. /** Returns a string version of the URL.
  12333. If includeGetParameters is true and any parameters have been set with the
  12334. withParameter() method, then the string will have these appended on the
  12335. end and url-encoded.
  12336. */
  12337. const String toString (bool includeGetParameters) const;
  12338. /** True if it seems to be valid. */
  12339. bool isWellFormed() const;
  12340. /** Returns just the domain part of the URL.
  12341. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  12342. */
  12343. const String getDomain() const;
  12344. /** Returns the path part of the URL.
  12345. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  12346. */
  12347. const String getSubPath() const;
  12348. /** Returns the scheme of the URL.
  12349. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  12350. include the colon).
  12351. */
  12352. const String getScheme() const;
  12353. /** Returns a new version of this URL that uses a different sub-path.
  12354. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  12355. "bar", it'll return "http://www.xyz.com/bar?x=1".
  12356. */
  12357. const URL withNewSubPath (const String& newPath) const;
  12358. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  12359. Any control characters in the value will be encoded.
  12360. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  12361. would produce a new url whose toString(true) method would return
  12362. "www.fish.com?amount=some+fish".
  12363. */
  12364. const URL withParameter (const String& parameterName,
  12365. const String& parameterValue) const;
  12366. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  12367. When performing a POST where one of your parameters is a binary file, this
  12368. lets you specify the file.
  12369. Note that the filename is stored, but the file itself won't actually be read
  12370. until this URL is later used to create a network input stream.
  12371. */
  12372. const URL withFileToUpload (const String& parameterName,
  12373. const File& fileToUpload,
  12374. const String& mimeType) const;
  12375. /** Returns a set of all the parameters encoded into the url.
  12376. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  12377. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  12378. The values returned will have been cleaned up to remove any escape characters.
  12379. @see getNamedParameter, withParameter
  12380. */
  12381. const StringPairArray& getParameters() const;
  12382. /** Returns the set of files that should be uploaded as part of a POST operation.
  12383. This is the set of files that were added to the URL with the withFileToUpload()
  12384. method.
  12385. */
  12386. const StringPairArray& getFilesToUpload() const;
  12387. /** Returns the set of mime types associated with each of the upload files.
  12388. */
  12389. const StringPairArray& getMimeTypesOfUploadFiles() const;
  12390. /** Returns a copy of this URL, with a block of data to send as the POST data.
  12391. If you're setting the POST data, be careful not to have any parameters set
  12392. as well, otherwise it'll all get thrown in together, and might not have the
  12393. desired effect.
  12394. If the URL already contains some POST data, this will replace it, rather
  12395. than being appended to it.
  12396. This data will only be used if you specify a post operation when you call
  12397. createInputStream().
  12398. */
  12399. const URL withPOSTData (const String& postData) const;
  12400. /** Returns the data that was set using withPOSTData().
  12401. */
  12402. const String getPostData() const { return postData; }
  12403. /** Tries to launch the system's default browser to open the URL.
  12404. Returns true if this seems to have worked.
  12405. */
  12406. bool launchInDefaultBrowser() const;
  12407. /** Takes a guess as to whether a string might be a valid website address.
  12408. This isn't foolproof!
  12409. */
  12410. static bool isProbablyAWebsiteURL (const String& possibleURL);
  12411. /** Takes a guess as to whether a string might be a valid email address.
  12412. This isn't foolproof!
  12413. */
  12414. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  12415. /** This callback function can be used by the createInputStream() method.
  12416. It allows your app to receive progress updates during a lengthy POST operation. If you
  12417. want to continue the operation, this should return true, or false to abort.
  12418. */
  12419. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  12420. /** Attempts to open a stream that can read from this URL.
  12421. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  12422. the paramters, otherwise it'll encode them into the
  12423. URL and do a 'GET'.
  12424. @param progressCallback if this is non-zero, it lets you supply a callback function
  12425. to keep track of the operation's progress. This can be useful
  12426. for lengthy POST operations, so that you can provide user feedback.
  12427. @param progressCallbackContext if a callback is specified, this value will be passed to
  12428. the function
  12429. @param extraHeaders if not empty, this string is appended onto the headers that
  12430. are used for the request. It must therefore be a valid set of HTML
  12431. header directives, separated by newlines.
  12432. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  12433. a negative number, it will be infinite. Otherwise it specifies a
  12434. time in milliseconds.
  12435. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  12436. in the response will be stored in this array
  12437. @returns an input stream that the caller must delete, or a null pointer if there was an
  12438. error trying to open it.
  12439. */
  12440. InputStream* createInputStream (bool usePostCommand,
  12441. OpenStreamProgressCallback* progressCallback = 0,
  12442. void* progressCallbackContext = 0,
  12443. const String& extraHeaders = String::empty,
  12444. int connectionTimeOutMs = 0,
  12445. StringPairArray* responseHeaders = 0) const;
  12446. /** Tries to download the entire contents of this URL into a binary data block.
  12447. If it succeeds, this will return true and append the data it read onto the end
  12448. of the memory block.
  12449. @param destData the memory block to append the new data to
  12450. @param usePostCommand whether to use a POST command to get the data (uses
  12451. a GET command if this is false)
  12452. @see readEntireTextStream, readEntireXmlStream
  12453. */
  12454. bool readEntireBinaryStream (MemoryBlock& destData,
  12455. bool usePostCommand = false) const;
  12456. /** Tries to download the entire contents of this URL as a string.
  12457. If it fails, this will return an empty string, otherwise it will return the
  12458. contents of the downloaded file. If you need to distinguish between a read
  12459. operation that fails and one that returns an empty string, you'll need to use
  12460. a different method, such as readEntireBinaryStream().
  12461. @param usePostCommand whether to use a POST command to get the data (uses
  12462. a GET command if this is false)
  12463. @see readEntireBinaryStream, readEntireXmlStream
  12464. */
  12465. const String readEntireTextStream (bool usePostCommand = false) const;
  12466. /** Tries to download the entire contents of this URL and parse it as XML.
  12467. If it fails, or if the text that it reads can't be parsed as XML, this will
  12468. return 0.
  12469. When it returns a valid XmlElement object, the caller is responsibile for deleting
  12470. this object when no longer needed.
  12471. @param usePostCommand whether to use a POST command to get the data (uses
  12472. a GET command if this is false)
  12473. @see readEntireBinaryStream, readEntireTextStream
  12474. */
  12475. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  12476. /** Adds escape sequences to a string to encode any characters that aren't
  12477. legal in a URL.
  12478. E.g. any spaces will be replaced with "%20".
  12479. This is the opposite of removeEscapeChars().
  12480. If isParameter is true, it means that the string is going to be used
  12481. as a parameter, so it also encodes '$' and ',' (which would otherwise
  12482. be legal in a URL.
  12483. @see removeEscapeChars
  12484. */
  12485. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  12486. bool isParameter);
  12487. /** Replaces any escape character sequences in a string with their original
  12488. character codes.
  12489. E.g. any instances of "%20" will be replaced by a space.
  12490. This is the opposite of addEscapeChars().
  12491. @see addEscapeChars
  12492. */
  12493. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  12494. juce_UseDebuggingNewOperator
  12495. private:
  12496. String url, postData;
  12497. StringPairArray parameters, filesToUpload, mimeTypes;
  12498. };
  12499. #endif // __JUCE_URL_JUCEHEADER__
  12500. /*** End of inlined file: juce_URL.h ***/
  12501. #endif
  12502. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12503. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  12504. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12505. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12506. /** Wraps another input stream, and reads from it using an intermediate buffer
  12507. If you're using an input stream such as a file input stream, and making lots of
  12508. small read accesses to it, it's probably sensible to wrap it in one of these,
  12509. so that the source stream gets accessed in larger chunk sizes, meaning less
  12510. work for the underlying stream.
  12511. */
  12512. class JUCE_API BufferedInputStream : public InputStream
  12513. {
  12514. public:
  12515. /** Creates a BufferedInputStream from an input source.
  12516. @param sourceStream the source stream to read from
  12517. @param bufferSize the size of reservoir to use to buffer the source
  12518. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12519. deleted by this object when it is itself deleted.
  12520. */
  12521. BufferedInputStream (InputStream* sourceStream,
  12522. int bufferSize,
  12523. bool deleteSourceWhenDestroyed);
  12524. /** Destructor.
  12525. This may also delete the source stream, if that option was chosen when the
  12526. buffered stream was created.
  12527. */
  12528. ~BufferedInputStream();
  12529. int64 getTotalLength();
  12530. int64 getPosition();
  12531. bool setPosition (int64 newPosition);
  12532. int read (void* destBuffer, int maxBytesToRead);
  12533. const String readString();
  12534. bool isExhausted();
  12535. juce_UseDebuggingNewOperator
  12536. private:
  12537. InputStream* const source;
  12538. ScopedPointer <InputStream> sourceToDelete;
  12539. int bufferSize;
  12540. int64 position, lastReadPos, bufferStart, bufferOverlap;
  12541. HeapBlock <char> buffer;
  12542. void ensureBuffered();
  12543. BufferedInputStream (const BufferedInputStream&);
  12544. BufferedInputStream& operator= (const BufferedInputStream&);
  12545. };
  12546. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12547. /*** End of inlined file: juce_BufferedInputStream.h ***/
  12548. #endif
  12549. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12550. /*** Start of inlined file: juce_FileInputSource.h ***/
  12551. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12552. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12553. /**
  12554. A type of InputSource that represents a normal file.
  12555. @see InputSource
  12556. */
  12557. class JUCE_API FileInputSource : public InputSource
  12558. {
  12559. public:
  12560. FileInputSource (const File& file);
  12561. ~FileInputSource();
  12562. InputStream* createInputStream();
  12563. InputStream* createInputStreamFor (const String& relatedItemPath);
  12564. int64 hashCode() const;
  12565. juce_UseDebuggingNewOperator
  12566. private:
  12567. const File file;
  12568. FileInputSource (const FileInputSource&);
  12569. FileInputSource& operator= (const FileInputSource&);
  12570. };
  12571. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12572. /*** End of inlined file: juce_FileInputSource.h ***/
  12573. #endif
  12574. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12575. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12576. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12577. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12578. class GZIPCompressorHelper;
  12579. /**
  12580. A stream which uses zlib to compress the data written into it.
  12581. @see GZIPDecompressorInputStream
  12582. */
  12583. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  12584. {
  12585. public:
  12586. /** Creates a compression stream.
  12587. @param destStream the stream into which the compressed data should
  12588. be written
  12589. @param compressionLevel how much to compress the data, between 1 and 9, where
  12590. 1 is the fastest/lowest compression, and 9 is the
  12591. slowest/highest compression. Any value outside this range
  12592. indicates that a default compression level should be used.
  12593. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  12594. this stream is destroyed
  12595. @param noWrap this is used internally by the ZipFile class
  12596. and should be ignored by user applications
  12597. */
  12598. GZIPCompressorOutputStream (OutputStream* destStream,
  12599. int compressionLevel = 0,
  12600. bool deleteDestStreamWhenDestroyed = false,
  12601. bool noWrap = false);
  12602. /** Destructor. */
  12603. ~GZIPCompressorOutputStream();
  12604. void flush();
  12605. int64 getPosition();
  12606. bool setPosition (int64 newPosition);
  12607. bool write (const void* destBuffer, int howMany);
  12608. juce_UseDebuggingNewOperator
  12609. private:
  12610. OutputStream* const destStream;
  12611. ScopedPointer <OutputStream> streamToDelete;
  12612. HeapBlock <uint8> buffer;
  12613. ScopedPointer <GZIPCompressorHelper> helper;
  12614. bool doNextBlock();
  12615. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  12616. GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  12617. };
  12618. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12619. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12620. #endif
  12621. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12622. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12623. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12624. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12625. class GZIPDecompressHelper;
  12626. /**
  12627. This stream will decompress a source-stream using zlib.
  12628. Tip: if you're reading lots of small items from one of these streams, you
  12629. can increase the performance enormously by passing it through a
  12630. BufferedInputStream, so that it has to read larger blocks less often.
  12631. @see GZIPCompressorOutputStream
  12632. */
  12633. class JUCE_API GZIPDecompressorInputStream : public InputStream
  12634. {
  12635. public:
  12636. /** Creates a decompressor stream.
  12637. @param sourceStream the stream to read from
  12638. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  12639. when this object is destroyed
  12640. @param noWrap this is used internally by the ZipFile class
  12641. and should be ignored by user applications
  12642. @param uncompressedStreamLength if the creator knows the length that the
  12643. uncompressed stream will be, then it can supply this
  12644. value, which will be returned by getTotalLength()
  12645. */
  12646. GZIPDecompressorInputStream (InputStream* sourceStream,
  12647. bool deleteSourceWhenDestroyed,
  12648. bool noWrap = false,
  12649. int64 uncompressedStreamLength = -1);
  12650. /** Destructor. */
  12651. ~GZIPDecompressorInputStream();
  12652. int64 getPosition();
  12653. bool setPosition (int64 pos);
  12654. int64 getTotalLength();
  12655. bool isExhausted();
  12656. int read (void* destBuffer, int maxBytesToRead);
  12657. juce_UseDebuggingNewOperator
  12658. private:
  12659. InputStream* const sourceStream;
  12660. ScopedPointer <InputStream> streamToDelete;
  12661. const int64 uncompressedStreamLength;
  12662. const bool noWrap;
  12663. bool isEof;
  12664. int activeBufferSize;
  12665. int64 originalSourcePos, currentPos;
  12666. HeapBlock <uint8> buffer;
  12667. ScopedPointer <GZIPDecompressHelper> helper;
  12668. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  12669. GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  12670. };
  12671. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12672. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12673. #endif
  12674. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12675. #endif
  12676. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  12677. #endif
  12678. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12679. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  12680. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12681. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12682. /**
  12683. Allows a block of data and to be accessed as a stream.
  12684. This can either be used to refer to a shared block of memory, or can make its
  12685. own internal copy of the data when the MemoryInputStream is created.
  12686. */
  12687. class JUCE_API MemoryInputStream : public InputStream
  12688. {
  12689. public:
  12690. /** Creates a MemoryInputStream.
  12691. @param sourceData the block of data to use as the stream's source
  12692. @param sourceDataSize the number of bytes in the source data block
  12693. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  12694. the source data, so this data shouldn't be changed
  12695. for the lifetime of the stream; if this parameter is
  12696. true, the stream will make its own copy of the
  12697. data and use that.
  12698. */
  12699. MemoryInputStream (const void* sourceData,
  12700. size_t sourceDataSize,
  12701. bool keepInternalCopyOfData);
  12702. /** Creates a MemoryInputStream.
  12703. @param data a block of data to use as the stream's source
  12704. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  12705. the source data, so this data shouldn't be changed
  12706. for the lifetime of the stream; if this parameter is
  12707. true, the stream will make its own copy of the
  12708. data and use that.
  12709. */
  12710. MemoryInputStream (const MemoryBlock& data,
  12711. bool keepInternalCopyOfData);
  12712. /** Destructor. */
  12713. ~MemoryInputStream();
  12714. int64 getPosition();
  12715. bool setPosition (int64 pos);
  12716. int64 getTotalLength();
  12717. bool isExhausted();
  12718. int read (void* destBuffer, int maxBytesToRead);
  12719. juce_UseDebuggingNewOperator
  12720. private:
  12721. const char* data;
  12722. size_t dataSize, position;
  12723. MemoryBlock internalCopy;
  12724. MemoryInputStream (const MemoryInputStream&);
  12725. MemoryInputStream& operator= (const MemoryInputStream&);
  12726. };
  12727. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12728. /*** End of inlined file: juce_MemoryInputStream.h ***/
  12729. #endif
  12730. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12731. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  12732. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12733. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12734. /** Writes data to an internal memory buffer, which grows as required.
  12735. The data that was written into the stream can then be accessed later as
  12736. a contiguous block of memory.
  12737. */
  12738. class JUCE_API MemoryOutputStream : public OutputStream
  12739. {
  12740. public:
  12741. /** Creates a memory stream ready for writing into.
  12742. @param initialSize the intial amount of space to allocate for writing into
  12743. @param granularity the increments by which the internal storage will be increased
  12744. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  12745. place that the data gets stored. If it's zero, the stream
  12746. will allocate its own storage internally, which you can
  12747. access using getData() and getDataSize()
  12748. */
  12749. MemoryOutputStream (size_t initialSize = 256,
  12750. size_t granularity = 256,
  12751. MemoryBlock* memoryBlockToWriteTo = 0);
  12752. /** Destructor.
  12753. This will free any data that was written to it.
  12754. */
  12755. ~MemoryOutputStream();
  12756. /** Returns a pointer to the data that has been written to the stream.
  12757. @see getDataSize
  12758. */
  12759. const char* getData() const throw();
  12760. /** Returns the number of bytes of data that have been written to the stream.
  12761. @see getData
  12762. */
  12763. size_t getDataSize() const throw() { return size; }
  12764. /** Resets the stream, clearing any data that has been written to it so far. */
  12765. void reset() throw();
  12766. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  12767. const String toUTF8() const;
  12768. void flush();
  12769. bool write (const void* buffer, int howMany);
  12770. int64 getPosition() { return position; }
  12771. bool setPosition (int64 newPosition);
  12772. juce_UseDebuggingNewOperator
  12773. private:
  12774. MemoryBlock* data;
  12775. ScopedPointer <MemoryBlock> dataToDelete;
  12776. size_t position, size, blockSize;
  12777. MemoryOutputStream (const MemoryOutputStream&);
  12778. MemoryOutputStream& operator= (const MemoryOutputStream&);
  12779. };
  12780. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12781. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  12782. #endif
  12783. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  12784. #endif
  12785. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12786. /*** Start of inlined file: juce_SubregionStream.h ***/
  12787. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12788. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12789. /** Wraps another input stream, and reads from a specific part of it.
  12790. This lets you take a subsection of a stream and present it as an entire
  12791. stream in its own right.
  12792. */
  12793. class JUCE_API SubregionStream : public InputStream
  12794. {
  12795. public:
  12796. /** Creates a SubregionStream from an input source.
  12797. @param sourceStream the source stream to read from
  12798. @param startPositionInSourceStream this is the position in the source stream that
  12799. corresponds to position 0 in this stream
  12800. @param lengthOfSourceStream this specifies the maximum number of bytes
  12801. from the source stream that will be passed through
  12802. by this stream. When the position of this stream
  12803. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  12804. If the length passed in here is greater than the length
  12805. of the source stream (as returned by getTotalLength()),
  12806. then the smaller value will be used.
  12807. Passing a negative value for this parameter means it
  12808. will keep reading until the source's end-of-stream.
  12809. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12810. deleted by this object when it is itself deleted.
  12811. */
  12812. SubregionStream (InputStream* sourceStream,
  12813. int64 startPositionInSourceStream,
  12814. int64 lengthOfSourceStream,
  12815. bool deleteSourceWhenDestroyed);
  12816. /** Destructor.
  12817. This may also delete the source stream, if that option was chosen when the
  12818. buffered stream was created.
  12819. */
  12820. ~SubregionStream();
  12821. int64 getTotalLength();
  12822. int64 getPosition();
  12823. bool setPosition (int64 newPosition);
  12824. int read (void* destBuffer, int maxBytesToRead);
  12825. bool isExhausted();
  12826. juce_UseDebuggingNewOperator
  12827. private:
  12828. InputStream* const source;
  12829. ScopedPointer <InputStream> sourceToDelete;
  12830. const int64 startPositionInSourceStream, lengthOfSourceStream;
  12831. SubregionStream (const SubregionStream&);
  12832. SubregionStream& operator= (const SubregionStream&);
  12833. };
  12834. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12835. /*** End of inlined file: juce_SubregionStream.h ***/
  12836. #endif
  12837. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  12838. #endif
  12839. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12840. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  12841. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12842. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12843. /** Used in the same way as the T(text) macro, this will attempt to translate a
  12844. string into a localised version using the LocalisedStrings class.
  12845. @see LocalisedStrings
  12846. */
  12847. #define TRANS(stringLiteral) \
  12848. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  12849. /**
  12850. Used to convert strings to localised foreign-language versions.
  12851. This is basically a look-up table of strings and their translated equivalents.
  12852. It can be loaded from a text file, so that you can supply a set of localised
  12853. versions of strings that you use in your app.
  12854. To use it in your code, simply call the translate() method on each string that
  12855. might have foreign versions, and if none is found, the method will just return
  12856. the original string.
  12857. The translation file should start with some lines specifying a description of
  12858. the language it contains, and also a list of ISO country codes where it might
  12859. be appropriate to use the file. After that, each line of the file should contain
  12860. a pair of quoted strings with an '=' sign.
  12861. E.g. for a french translation, the file might be:
  12862. @code
  12863. language: French
  12864. countries: fr be mc ch lu
  12865. "hello" = "bonjour"
  12866. "goodbye" = "au revoir"
  12867. @endcode
  12868. If the strings need to contain a quote character, they can use '\"' instead, and
  12869. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  12870. (you can use this to add comments).
  12871. Note that this is a singleton class, so don't create or destroy the object directly.
  12872. There's also a TRANS(text) macro defined to make it easy to use the this.
  12873. E.g. @code
  12874. printSomething (TRANS("hello"));
  12875. @endcode
  12876. This macro is used in the Juce classes themselves, so your application has a chance to
  12877. intercept and translate any internal Juce text strings that might be shown. (You can easily
  12878. get a list of all the messages by searching for the TRANS() macro in the Juce source
  12879. code).
  12880. */
  12881. class JUCE_API LocalisedStrings
  12882. {
  12883. public:
  12884. /** Creates a set of translations from the text of a translation file.
  12885. When you create one of these, you can call setCurrentMappings() to make it
  12886. the set of mappings that the system's using.
  12887. */
  12888. LocalisedStrings (const String& fileContents);
  12889. /** Creates a set of translations from a file.
  12890. When you create one of these, you can call setCurrentMappings() to make it
  12891. the set of mappings that the system's using.
  12892. */
  12893. LocalisedStrings (const File& fileToLoad);
  12894. /** Destructor. */
  12895. ~LocalisedStrings();
  12896. /** Selects the current set of mappings to be used by the system.
  12897. The object you pass in will be automatically deleted when no longer needed, so
  12898. don't keep a pointer to it. You can also pass in zero to remove the current
  12899. mappings.
  12900. See also the TRANS() macro, which uses the current set to do its translation.
  12901. @see translateWithCurrentMappings
  12902. */
  12903. static void setCurrentMappings (LocalisedStrings* newTranslations);
  12904. /** Returns the currently selected set of mappings.
  12905. This is the object that was last passed to setCurrentMappings(). It may
  12906. be 0 if none has been created.
  12907. */
  12908. static LocalisedStrings* getCurrentMappings();
  12909. /** Tries to translate a string using the currently selected set of mappings.
  12910. If no mapping has been set, or if the mapping doesn't contain a translation
  12911. for the string, this will just return the original string.
  12912. See also the TRANS() macro, which uses this method to do its translation.
  12913. @see setCurrentMappings, getCurrentMappings
  12914. */
  12915. static const String translateWithCurrentMappings (const String& text);
  12916. /** Tries to translate a string using the currently selected set of mappings.
  12917. If no mapping has been set, or if the mapping doesn't contain a translation
  12918. for the string, this will just return the original string.
  12919. See also the TRANS() macro, which uses this method to do its translation.
  12920. @see setCurrentMappings, getCurrentMappings
  12921. */
  12922. static const String translateWithCurrentMappings (const char* text);
  12923. /** Attempts to look up a string and return its localised version.
  12924. If the string isn't found in the list, the original string will be returned.
  12925. */
  12926. const String translate (const String& text) const;
  12927. /** Returns the name of the language specified in the translation file.
  12928. This is specified in the file using a line starting with "language:", e.g.
  12929. @code
  12930. language: german
  12931. @endcode
  12932. */
  12933. const String getLanguageName() const { return languageName; }
  12934. /** Returns the list of suitable country codes listed in the translation file.
  12935. These is specified in the file using a line starting with "countries:", e.g.
  12936. @code
  12937. countries: fr be mc ch lu
  12938. @endcode
  12939. The country codes are supposed to be 2-character ISO complient codes.
  12940. */
  12941. const StringArray getCountryCodes() const { return countryCodes; }
  12942. /** Indicates whether to use a case-insensitive search when looking up a string.
  12943. This defaults to true.
  12944. */
  12945. void setIgnoresCase (const bool shouldIgnoreCase);
  12946. juce_UseDebuggingNewOperator
  12947. private:
  12948. String languageName;
  12949. StringArray countryCodes;
  12950. StringPairArray translations;
  12951. void loadFromText (const String& fileContents);
  12952. };
  12953. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12954. /*** End of inlined file: juce_LocalisedStrings.h ***/
  12955. #endif
  12956. #ifndef __JUCE_STRING_JUCEHEADER__
  12957. #endif
  12958. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  12959. #endif
  12960. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  12961. #endif
  12962. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  12963. #endif
  12964. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12965. /*** Start of inlined file: juce_XmlDocument.h ***/
  12966. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12967. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  12968. /**
  12969. Parses a text-based XML document and creates an XmlElement object from it.
  12970. The parser will parse DTDs to load external entities but won't
  12971. check the document for validity against the DTD.
  12972. e.g.
  12973. @code
  12974. XmlDocument myDocument (File ("myfile.xml"));
  12975. XmlElement* mainElement = myDocument.getDocumentElement();
  12976. if (mainElement == 0)
  12977. {
  12978. String error = myDocument.getLastParseError();
  12979. }
  12980. else
  12981. {
  12982. ..use the element
  12983. }
  12984. @endcode
  12985. @see XmlElement
  12986. */
  12987. class JUCE_API XmlDocument
  12988. {
  12989. public:
  12990. /** Creates an XmlDocument from the xml text.
  12991. The text doesn't actually get parsed until the getDocumentElement() method is
  12992. called.
  12993. */
  12994. XmlDocument (const String& documentText);
  12995. /** Creates an XmlDocument from a file.
  12996. The text doesn't actually get parsed until the getDocumentElement() method is
  12997. called.
  12998. */
  12999. XmlDocument (const File& file);
  13000. /** Destructor. */
  13001. ~XmlDocument();
  13002. /** Creates an XmlElement object to represent the main document node.
  13003. This method will do the actual parsing of the text, and if there's a
  13004. parse error, it may returns 0 (and you can find out the error using
  13005. the getLastParseError() method).
  13006. @param onlyReadOuterDocumentElement if true, the parser will only read the
  13007. first section of the file, and will only
  13008. return the outer document element - this
  13009. allows quick checking of large files to
  13010. see if they contain the correct type of
  13011. tag, without having to parse the entire file
  13012. @returns a new XmlElement which the caller will need to delete, or null if
  13013. there was an error.
  13014. @see getLastParseError
  13015. */
  13016. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  13017. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  13018. @returns the error, or an empty string if there was no error.
  13019. */
  13020. const String& getLastParseError() const throw();
  13021. /** Sets an input source object to use for parsing documents that reference external entities.
  13022. If the document has been created from a file, this probably won't be needed, but
  13023. if you're parsing some text and there might be a DTD that references external
  13024. files, you may need to create a custom input source that can retrieve the
  13025. other files it needs.
  13026. The object that is passed-in will be deleted automatically when no longer needed.
  13027. @see InputSource
  13028. */
  13029. void setInputSource (InputSource* const newSource) throw();
  13030. /** Sets a flag to change the treatment of empty text elements.
  13031. If this is true (the default state), then any text elements that contain only
  13032. whitespace characters will be ingored during parsing. If you need to catch
  13033. whitespace-only text, then you should set this to false before calling the
  13034. getDocumentElement() method.
  13035. */
  13036. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  13037. juce_UseDebuggingNewOperator
  13038. private:
  13039. String originalText;
  13040. const juce_wchar* input;
  13041. bool outOfData, errorOccurred;
  13042. bool identifierLookupTable [128];
  13043. String lastError, dtdText;
  13044. StringArray tokenisedDTD;
  13045. bool needToLoadDTD, ignoreEmptyTextElements;
  13046. ScopedPointer <InputSource> inputSource;
  13047. void setLastError (const String& desc, const bool carryOn);
  13048. void skipHeader();
  13049. void skipNextWhiteSpace();
  13050. juce_wchar readNextChar() throw();
  13051. XmlElement* readNextElement (const bool alsoParseSubElements);
  13052. void readChildElements (XmlElement* parent);
  13053. int findNextTokenLength() throw();
  13054. void readQuotedString (String& result);
  13055. void readEntity (String& result);
  13056. static bool isXmlIdentifierCharSlow (juce_wchar c) throw();
  13057. bool isXmlIdentifierChar (juce_wchar c) const throw();
  13058. const String getFileContents (const String& filename) const;
  13059. const String expandEntity (const String& entity);
  13060. const String expandExternalEntity (const String& entity);
  13061. const String getParameterEntity (const String& entity);
  13062. XmlDocument (const XmlDocument&);
  13063. XmlDocument& operator= (const XmlDocument&);
  13064. };
  13065. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  13066. /*** End of inlined file: juce_XmlDocument.h ***/
  13067. #endif
  13068. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  13069. #endif
  13070. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  13071. #endif
  13072. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13073. /*** Start of inlined file: juce_InterProcessLock.h ***/
  13074. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13075. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13076. /**
  13077. Acts as a critical section which processes can use to block each other.
  13078. @see CriticalSection
  13079. */
  13080. class JUCE_API InterProcessLock
  13081. {
  13082. public:
  13083. /** Creates a lock object.
  13084. @param name a name that processes will use to identify this lock object
  13085. */
  13086. explicit InterProcessLock (const String& name);
  13087. /** Destructor.
  13088. This will also release the lock if it's currently held by this process.
  13089. */
  13090. ~InterProcessLock();
  13091. /** Attempts to lock the critical section.
  13092. @param timeOutMillisecs how many milliseconds to wait if the lock
  13093. is already held by another process - a value of
  13094. 0 will return immediately, negative values will wait
  13095. forever
  13096. @returns true if the lock could be gained within the timeout period, or
  13097. false if the timeout expired.
  13098. */
  13099. bool enter (int timeOutMillisecs = -1);
  13100. /** Releases the lock if it's currently held by this process.
  13101. */
  13102. void exit();
  13103. /**
  13104. Automatically locks and unlocks an InterProcessLock object.
  13105. This works like a ScopedLock, but using an InterprocessLock rather than
  13106. a CriticalSection.
  13107. @see ScopedLock
  13108. */
  13109. class ScopedLockType
  13110. {
  13111. public:
  13112. /** Creates a scoped lock.
  13113. As soon as it is created, this will lock the InterProcessLock, and
  13114. when the ScopedLockType object is deleted, the InterProcessLock will
  13115. be unlocked.
  13116. Note that since an InterprocessLock can fail due to errors, you should check
  13117. isLocked() to make sure that the lock was successful before using it.
  13118. Make sure this object is created and deleted by the same thread,
  13119. otherwise there are no guarantees what will happen! Best just to use it
  13120. as a local stack object, rather than creating one with the new() operator.
  13121. */
  13122. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  13123. /** Destructor.
  13124. The InterProcessLock will be unlocked when the destructor is called.
  13125. Make sure this object is created and deleted by the same thread,
  13126. otherwise there are no guarantees what will happen!
  13127. */
  13128. inline ~ScopedLockType() { lock_.exit(); }
  13129. /** Returns true if the InterProcessLock was successfully locked. */
  13130. bool isLocked() const throw() { return lockWasSuccessful; }
  13131. private:
  13132. InterProcessLock& lock_;
  13133. bool lockWasSuccessful;
  13134. ScopedLockType (const ScopedLockType&);
  13135. ScopedLockType& operator= (const ScopedLockType&);
  13136. };
  13137. juce_UseDebuggingNewOperator
  13138. private:
  13139. class Pimpl;
  13140. friend class ScopedPointer <Pimpl>;
  13141. ScopedPointer <Pimpl> pimpl;
  13142. CriticalSection lock;
  13143. String name;
  13144. InterProcessLock (const InterProcessLock&);
  13145. InterProcessLock& operator= (const InterProcessLock&);
  13146. };
  13147. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13148. /*** End of inlined file: juce_InterProcessLock.h ***/
  13149. #endif
  13150. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13151. /*** Start of inlined file: juce_Process.h ***/
  13152. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13153. #define __JUCE_PROCESS_JUCEHEADER__
  13154. /** Represents the current executable's process.
  13155. This contains methods for controlling the current application at the
  13156. process-level.
  13157. @see Thread, JUCEApplication
  13158. */
  13159. class JUCE_API Process
  13160. {
  13161. public:
  13162. enum ProcessPriority
  13163. {
  13164. LowPriority = 0,
  13165. NormalPriority = 1,
  13166. HighPriority = 2,
  13167. RealtimePriority = 3
  13168. };
  13169. /** Changes the current process's priority.
  13170. @param priority the process priority, where
  13171. 0=low, 1=normal, 2=high, 3=realtime
  13172. */
  13173. static void setPriority (const ProcessPriority priority);
  13174. /** Kills the current process immediately.
  13175. This is an emergency process terminator that kills the application
  13176. immediately - it's intended only for use only when something goes
  13177. horribly wrong.
  13178. @see JUCEApplication::quit
  13179. */
  13180. static void terminate();
  13181. /** Returns true if this application process is the one that the user is
  13182. currently using.
  13183. */
  13184. static bool isForegroundProcess();
  13185. /** Raises the current process's privilege level.
  13186. Does nothing if this isn't supported by the current OS, or if process
  13187. privilege level is fixed.
  13188. */
  13189. static void raisePrivilege();
  13190. /** Lowers the current process's privilege level.
  13191. Does nothing if this isn't supported by the current OS, or if process
  13192. privilege level is fixed.
  13193. */
  13194. static void lowerPrivilege();
  13195. /** Returns true if this process is being hosted by a debugger.
  13196. */
  13197. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  13198. private:
  13199. Process();
  13200. Process (const Process&);
  13201. Process& operator= (const Process&);
  13202. };
  13203. #endif // __JUCE_PROCESS_JUCEHEADER__
  13204. /*** End of inlined file: juce_Process.h ***/
  13205. #endif
  13206. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13207. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  13208. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13209. #define __JUCE_READWRITELOCK_JUCEHEADER__
  13210. /*** Start of inlined file: juce_WaitableEvent.h ***/
  13211. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13212. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  13213. /**
  13214. Allows threads to wait for events triggered by other threads.
  13215. A thread can call wait() on a WaitableObject, and this will suspend the
  13216. calling thread until another thread wakes it up by calling the signal()
  13217. method.
  13218. */
  13219. class JUCE_API WaitableEvent
  13220. {
  13221. public:
  13222. /** Creates a WaitableEvent object.
  13223. @param manualReset If this is false, the event will be reset automatically when the wait()
  13224. method is called. If manualReset is true, then once the event is signalled,
  13225. the only way to reset it will be by calling the reset() method.
  13226. */
  13227. WaitableEvent (bool manualReset = false) throw();
  13228. /** Destructor.
  13229. If other threads are waiting on this object when it gets deleted, this
  13230. can cause nasty errors, so be careful!
  13231. */
  13232. ~WaitableEvent() throw();
  13233. /** Suspends the calling thread until the event has been signalled.
  13234. This will wait until the object's signal() method is called by another thread,
  13235. or until the timeout expires.
  13236. After the event has been signalled, this method will return true and if manualReset
  13237. was set to false in the WaitableEvent's constructor, then the event will be reset.
  13238. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  13239. value will cause it to wait forever.
  13240. @returns true if the object has been signalled, false if the timeout expires first.
  13241. @see signal, reset
  13242. */
  13243. bool wait (int timeOutMilliseconds = -1) const throw();
  13244. /** Wakes up any threads that are currently waiting on this object.
  13245. If signal() is called when nothing is waiting, the next thread to call wait()
  13246. will return immediately and reset the signal.
  13247. @see wait, reset
  13248. */
  13249. void signal() const throw();
  13250. /** Resets the event to an unsignalled state.
  13251. If it's not already signalled, this does nothing.
  13252. */
  13253. void reset() const throw();
  13254. juce_UseDebuggingNewOperator
  13255. private:
  13256. void* internal;
  13257. WaitableEvent (const WaitableEvent&);
  13258. WaitableEvent& operator= (const WaitableEvent&);
  13259. };
  13260. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  13261. /*** End of inlined file: juce_WaitableEvent.h ***/
  13262. /*** Start of inlined file: juce_Thread.h ***/
  13263. #ifndef __JUCE_THREAD_JUCEHEADER__
  13264. #define __JUCE_THREAD_JUCEHEADER__
  13265. /**
  13266. Encapsulates a thread.
  13267. Subclasses derive from Thread and implement the run() method, in which they
  13268. do their business. The thread can then be started with the startThread() method
  13269. and controlled with various other methods.
  13270. This class also contains some thread-related static methods, such
  13271. as sleep(), yield(), getCurrentThreadId() etc.
  13272. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  13273. MessageManagerLock
  13274. */
  13275. class JUCE_API Thread
  13276. {
  13277. public:
  13278. /**
  13279. Creates a thread.
  13280. When first created, the thread is not running. Use the startThread()
  13281. method to start it.
  13282. */
  13283. explicit Thread (const String& threadName);
  13284. /** Destructor.
  13285. Deleting a Thread object that is running will only give the thread a
  13286. brief opportunity to stop itself cleanly, so it's recommended that you
  13287. should always call stopThread() with a decent timeout before deleting,
  13288. to avoid the thread being forcibly killed (which is a Bad Thing).
  13289. */
  13290. virtual ~Thread();
  13291. /** Must be implemented to perform the thread's actual code.
  13292. Remember that the thread must regularly check the threadShouldExit()
  13293. method whilst running, and if this returns true it should return from
  13294. the run() method as soon as possible to avoid being forcibly killed.
  13295. @see threadShouldExit, startThread
  13296. */
  13297. virtual void run() = 0;
  13298. // Thread control functions..
  13299. /** Starts the thread running.
  13300. This will start the thread's run() method.
  13301. (if it's already started, startThread() won't do anything).
  13302. @see stopThread
  13303. */
  13304. void startThread();
  13305. /** Starts the thread with a given priority.
  13306. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  13307. If the thread is already running, its priority will be changed.
  13308. @see startThread, setPriority
  13309. */
  13310. void startThread (int priority);
  13311. /** Attempts to stop the thread running.
  13312. This method will cause the threadShouldExit() method to return true
  13313. and call notify() in case the thread is currently waiting.
  13314. Hopefully the thread will then respond to this by exiting cleanly, and
  13315. the stopThread method will wait for a given time-period for this to
  13316. happen.
  13317. If the thread is stuck and fails to respond after the time-out, it gets
  13318. forcibly killed, which is a very bad thing to happen, as it could still
  13319. be holding locks, etc. which are needed by other parts of your program.
  13320. @param timeOutMilliseconds The number of milliseconds to wait for the
  13321. thread to finish before killing it by force. A negative
  13322. value in here will wait forever.
  13323. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  13324. */
  13325. void stopThread (int timeOutMilliseconds);
  13326. /** Returns true if the thread is currently active */
  13327. bool isThreadRunning() const;
  13328. /** Sets a flag to tell the thread it should stop.
  13329. Calling this means that the threadShouldExit() method will then return true.
  13330. The thread should be regularly checking this to see whether it should exit.
  13331. If your thread makes use of wait(), you might want to call notify() after calling
  13332. this method, to interrupt any waits that might be in progress, and allow it
  13333. to reach a point where it can exit.
  13334. @see threadShouldExit
  13335. @see waitForThreadToExit
  13336. */
  13337. void signalThreadShouldExit();
  13338. /** Checks whether the thread has been told to stop running.
  13339. Threads need to check this regularly, and if it returns true, they should
  13340. return from their run() method at the first possible opportunity.
  13341. @see signalThreadShouldExit
  13342. */
  13343. inline bool threadShouldExit() const { return threadShouldExit_; }
  13344. /** Waits for the thread to stop.
  13345. This will waits until isThreadRunning() is false or until a timeout expires.
  13346. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  13347. is less than zero, it will wait forever.
  13348. @returns true if the thread exits, or false if the timeout expires first.
  13349. */
  13350. bool waitForThreadToExit (int timeOutMilliseconds) const;
  13351. /** Changes the thread's priority.
  13352. May return false if for some reason the priority can't be changed.
  13353. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  13354. of 5 is normal.
  13355. */
  13356. bool setPriority (int priority);
  13357. /** Changes the priority of the caller thread.
  13358. Similar to setPriority(), but this static method acts on the caller thread.
  13359. May return false if for some reason the priority can't be changed.
  13360. @see setPriority
  13361. */
  13362. static bool setCurrentThreadPriority (int priority);
  13363. /** Sets the affinity mask for the thread.
  13364. This will only have an effect next time the thread is started - i.e. if the
  13365. thread is already running when called, it'll have no effect.
  13366. @see setCurrentThreadAffinityMask
  13367. */
  13368. void setAffinityMask (uint32 affinityMask);
  13369. /** Changes the affinity mask for the caller thread.
  13370. This will change the affinity mask for the thread that calls this static method.
  13371. @see setAffinityMask
  13372. */
  13373. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  13374. // this can be called from any thread that needs to pause..
  13375. static void JUCE_CALLTYPE sleep (int milliseconds);
  13376. /** Yields the calling thread's current time-slot. */
  13377. static void JUCE_CALLTYPE yield();
  13378. /** Makes the thread wait for a notification.
  13379. This puts the thread to sleep until either the timeout period expires, or
  13380. another thread calls the notify() method to wake it up.
  13381. A negative time-out value means that the method will wait indefinitely.
  13382. @returns true if the event has been signalled, false if the timeout expires.
  13383. */
  13384. bool wait (int timeOutMilliseconds) const;
  13385. /** Wakes up the thread.
  13386. If the thread has called the wait() method, this will wake it up.
  13387. @see wait
  13388. */
  13389. void notify() const;
  13390. /** A value type used for thread IDs.
  13391. @see getCurrentThreadId(), getThreadId()
  13392. */
  13393. typedef void* ThreadID;
  13394. /** Returns an id that identifies the caller thread.
  13395. To find the ID of a particular thread object, use getThreadId().
  13396. @returns a unique identifier that identifies the calling thread.
  13397. @see getThreadId
  13398. */
  13399. static ThreadID getCurrentThreadId();
  13400. /** Finds the thread object that is currently running.
  13401. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  13402. object associated with them, so this will return 0.
  13403. */
  13404. static Thread* getCurrentThread();
  13405. /** Returns the ID of this thread.
  13406. That means the ID of this thread object - not of the thread that's calling the method.
  13407. This can change when the thread is started and stopped, and will be invalid if the
  13408. thread's not actually running.
  13409. @see getCurrentThreadId
  13410. */
  13411. ThreadID getThreadId() const throw() { return threadId_; }
  13412. /** Returns the name of the thread.
  13413. This is the name that gets set in the constructor.
  13414. */
  13415. const String getThreadName() const { return threadName_; }
  13416. /** Returns the number of currently-running threads.
  13417. @returns the number of Thread objects known to be currently running.
  13418. @see stopAllThreads
  13419. */
  13420. static int getNumRunningThreads();
  13421. /** Tries to stop all currently-running threads.
  13422. This will attempt to stop all the threads known to be running at the moment.
  13423. */
  13424. static void stopAllThreads (int timeoutInMillisecs);
  13425. juce_UseDebuggingNewOperator
  13426. private:
  13427. const String threadName_;
  13428. void* volatile threadHandle_;
  13429. CriticalSection startStopLock;
  13430. WaitableEvent startSuspensionEvent_, defaultEvent_;
  13431. int threadPriority_;
  13432. ThreadID threadId_;
  13433. uint32 affinityMask_;
  13434. bool volatile threadShouldExit_;
  13435. friend void JUCE_API juce_threadEntryPoint (void*);
  13436. static void threadEntryPoint (Thread* thread);
  13437. static Array<Thread*> runningThreads;
  13438. static CriticalSection runningThreadsLock;
  13439. Thread (const Thread&);
  13440. Thread& operator= (const Thread&);
  13441. };
  13442. #endif // __JUCE_THREAD_JUCEHEADER__
  13443. /*** End of inlined file: juce_Thread.h ***/
  13444. /**
  13445. A critical section that allows multiple simultaneous readers.
  13446. Features of this type of lock are:
  13447. - Multiple readers can hold the lock at the same time, but only one writer
  13448. can hold it at once.
  13449. - Writers trying to gain the lock will be blocked until all readers and writers
  13450. have released it
  13451. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  13452. blocked until the writer has obtained and released it
  13453. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  13454. there are no other readers
  13455. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  13456. - Recursive locking is supported.
  13457. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  13458. */
  13459. class JUCE_API ReadWriteLock
  13460. {
  13461. public:
  13462. /**
  13463. Creates a ReadWriteLock object.
  13464. */
  13465. ReadWriteLock() throw();
  13466. /** Destructor.
  13467. If the object is deleted whilst locked, any subsequent behaviour
  13468. is unpredictable.
  13469. */
  13470. ~ReadWriteLock() throw();
  13471. /** Locks this object for reading.
  13472. Multiple threads can simulaneously lock the object for reading, but if another
  13473. thread has it locked for writing, then this will block until it releases the
  13474. lock.
  13475. @see exitRead, ScopedReadLock
  13476. */
  13477. void enterRead() const throw();
  13478. /** Releases the read-lock.
  13479. If the caller thread hasn't got the lock, this can have unpredictable results.
  13480. If the enterRead() method has been called multiple times by the thread, each
  13481. call must be matched by a call to exitRead() before other threads will be allowed
  13482. to take over the lock.
  13483. @see enterRead, ScopedReadLock
  13484. */
  13485. void exitRead() const throw();
  13486. /** Locks this object for writing.
  13487. This will block until any other threads that have it locked for reading or
  13488. writing have released their lock.
  13489. @see exitWrite, ScopedWriteLock
  13490. */
  13491. void enterWrite() const throw();
  13492. /** Tries to lock this object for writing.
  13493. This is like enterWrite(), but doesn't block - it returns true if it manages
  13494. to obtain the lock.
  13495. @see enterWrite
  13496. */
  13497. bool tryEnterWrite() const throw();
  13498. /** Releases the write-lock.
  13499. If the caller thread hasn't got the lock, this can have unpredictable results.
  13500. If the enterWrite() method has been called multiple times by the thread, each
  13501. call must be matched by a call to exit() before other threads will be allowed
  13502. to take over the lock.
  13503. @see enterWrite, ScopedWriteLock
  13504. */
  13505. void exitWrite() const throw();
  13506. juce_UseDebuggingNewOperator
  13507. private:
  13508. CriticalSection accessLock;
  13509. WaitableEvent waitEvent;
  13510. mutable int numWaitingWriters, numWriters;
  13511. mutable Thread::ThreadID writerThreadId;
  13512. mutable Array <Thread::ThreadID> readerThreads;
  13513. ReadWriteLock (const ReadWriteLock&);
  13514. ReadWriteLock& operator= (const ReadWriteLock&);
  13515. };
  13516. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  13517. /*** End of inlined file: juce_ReadWriteLock.h ***/
  13518. #endif
  13519. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13520. #endif
  13521. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13522. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  13523. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13524. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13525. /**
  13526. Automatically locks and unlocks a ReadWriteLock object.
  13527. Use one of these as a local variable to control access to a ReadWriteLock.
  13528. e.g. @code
  13529. ReadWriteLock myLock;
  13530. for (;;)
  13531. {
  13532. const ScopedReadLock myScopedLock (myLock);
  13533. // myLock is now locked
  13534. ...do some stuff...
  13535. // myLock gets unlocked here.
  13536. }
  13537. @endcode
  13538. @see ReadWriteLock, ScopedWriteLock
  13539. */
  13540. class JUCE_API ScopedReadLock
  13541. {
  13542. public:
  13543. /** Creates a ScopedReadLock.
  13544. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  13545. when the ScopedReadLock object is deleted, the ReadWriteLock will
  13546. be unlocked.
  13547. Make sure this object is created and deleted by the same thread,
  13548. otherwise there are no guarantees what will happen! Best just to use it
  13549. as a local stack object, rather than creating one with the new() operator.
  13550. */
  13551. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  13552. /** Destructor.
  13553. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  13554. Make sure this object is created and deleted by the same thread,
  13555. otherwise there are no guarantees what will happen!
  13556. */
  13557. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  13558. private:
  13559. const ReadWriteLock& lock_;
  13560. ScopedReadLock (const ScopedReadLock&);
  13561. ScopedReadLock& operator= (const ScopedReadLock&);
  13562. };
  13563. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13564. /*** End of inlined file: juce_ScopedReadLock.h ***/
  13565. #endif
  13566. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13567. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  13568. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13569. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13570. /**
  13571. Automatically tries to lock and unlock a CriticalSection object.
  13572. Use one of these as a local variable to control access to a CriticalSection.
  13573. e.g. @code
  13574. CriticalSection myCriticalSection;
  13575. for (;;)
  13576. {
  13577. const ScopedTryLock myScopedTryLock (myCriticalSection);
  13578. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  13579. // should test this with the isLocked() method before doing your thread-unsafe
  13580. // action..
  13581. if (myScopedTryLock.isLocked())
  13582. {
  13583. ...do some stuff...
  13584. }
  13585. else
  13586. {
  13587. ..our attempt at locking failed because another thread had already locked it..
  13588. }
  13589. // myCriticalSection gets unlocked here (if it was locked)
  13590. }
  13591. @endcode
  13592. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  13593. */
  13594. class JUCE_API ScopedTryLock
  13595. {
  13596. public:
  13597. /** Creates a ScopedTryLock.
  13598. As soon as it is created, this will try to lock the CriticalSection, and
  13599. when the ScopedTryLock object is deleted, the CriticalSection will
  13600. be unlocked if the lock was successful.
  13601. Make sure this object is created and deleted by the same thread,
  13602. otherwise there are no guarantees what will happen! Best just to use it
  13603. as a local stack object, rather than creating one with the new() operator.
  13604. */
  13605. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  13606. /** Destructor.
  13607. The CriticalSection will be unlocked (if locked) when the destructor is called.
  13608. Make sure this object is created and deleted by the same thread,
  13609. otherwise there are no guarantees what will happen!
  13610. */
  13611. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  13612. /** Returns true if the CriticalSection was successfully locked. */
  13613. bool isLocked() const throw() { return lockWasSuccessful; }
  13614. private:
  13615. const CriticalSection& lock_;
  13616. const bool lockWasSuccessful;
  13617. ScopedTryLock (const ScopedTryLock&);
  13618. ScopedTryLock& operator= (const ScopedTryLock&);
  13619. };
  13620. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13621. /*** End of inlined file: juce_ScopedTryLock.h ***/
  13622. #endif
  13623. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13624. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  13625. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13626. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13627. /**
  13628. Automatically locks and unlocks a ReadWriteLock object.
  13629. Use one of these as a local variable to control access to a ReadWriteLock.
  13630. e.g. @code
  13631. ReadWriteLock myLock;
  13632. for (;;)
  13633. {
  13634. const ScopedWriteLock myScopedLock (myLock);
  13635. // myLock is now locked
  13636. ...do some stuff...
  13637. // myLock gets unlocked here.
  13638. }
  13639. @endcode
  13640. @see ReadWriteLock, ScopedReadLock
  13641. */
  13642. class JUCE_API ScopedWriteLock
  13643. {
  13644. public:
  13645. /** Creates a ScopedWriteLock.
  13646. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  13647. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  13648. be unlocked.
  13649. Make sure this object is created and deleted by the same thread,
  13650. otherwise there are no guarantees what will happen! Best just to use it
  13651. as a local stack object, rather than creating one with the new() operator.
  13652. */
  13653. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  13654. /** Destructor.
  13655. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  13656. Make sure this object is created and deleted by the same thread,
  13657. otherwise there are no guarantees what will happen!
  13658. */
  13659. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  13660. private:
  13661. const ReadWriteLock& lock_;
  13662. ScopedWriteLock (const ScopedWriteLock&);
  13663. ScopedWriteLock& operator= (const ScopedWriteLock&);
  13664. };
  13665. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13666. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  13667. #endif
  13668. #ifndef __JUCE_THREAD_JUCEHEADER__
  13669. #endif
  13670. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13671. /*** Start of inlined file: juce_ThreadPool.h ***/
  13672. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13673. #define __JUCE_THREADPOOL_JUCEHEADER__
  13674. class ThreadPool;
  13675. class ThreadPoolThread;
  13676. /**
  13677. A task that is executed by a ThreadPool object.
  13678. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  13679. its threads.
  13680. The runJob() method needs to be implemented to do the task, and if the code that
  13681. does the work takes a significant time to run, it must keep checking the shouldExit()
  13682. method to see if something is trying to interrupt the job. If shouldExit() returns
  13683. true, the runJob() method must return immediately.
  13684. @see ThreadPool, Thread
  13685. */
  13686. class JUCE_API ThreadPoolJob
  13687. {
  13688. public:
  13689. /** Creates a thread pool job object.
  13690. After creating your job, add it to a thread pool with ThreadPool::addJob().
  13691. */
  13692. explicit ThreadPoolJob (const String& name);
  13693. /** Destructor. */
  13694. virtual ~ThreadPoolJob();
  13695. /** Returns the name of this job.
  13696. @see setJobName
  13697. */
  13698. const String getJobName() const;
  13699. /** Changes the job's name.
  13700. @see getJobName
  13701. */
  13702. void setJobName (const String& newName);
  13703. /** These are the values that can be returned by the runJob() method.
  13704. */
  13705. enum JobStatus
  13706. {
  13707. jobHasFinished = 0, /**< indicates that the job has finished and can be
  13708. removed from the pool. */
  13709. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  13710. should be automatically deleted by the pool. */
  13711. jobNeedsRunningAgain /**< indicates that the job would like to be called
  13712. again when a thread is free. */
  13713. };
  13714. /** Peforms the actual work that this job needs to do.
  13715. Your subclass must implement this method, in which is does its work.
  13716. If the code in this method takes a significant time to run, it must repeatedly check
  13717. the shouldExit() method to see if something is trying to interrupt the job.
  13718. If shouldExit() ever returns true, the runJob() method must return immediately.
  13719. If this method returns jobHasFinished, then the job will be removed from the pool
  13720. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  13721. pool and will get a chance to run again as soon as a thread is free.
  13722. @see shouldExit()
  13723. */
  13724. virtual JobStatus runJob() = 0;
  13725. /** Returns true if this job is currently running its runJob() method. */
  13726. bool isRunning() const { return isActive; }
  13727. /** Returns true if something is trying to interrupt this job and make it stop.
  13728. Your runJob() method must call this whenever it gets a chance, and if it ever
  13729. returns true, the runJob() method must return immediately.
  13730. @see signalJobShouldExit()
  13731. */
  13732. bool shouldExit() const { return shouldStop; }
  13733. /** Calling this will cause the shouldExit() method to return true, and the job
  13734. should (if it's been implemented correctly) stop as soon as possible.
  13735. @see shouldExit()
  13736. */
  13737. void signalJobShouldExit();
  13738. juce_UseDebuggingNewOperator
  13739. private:
  13740. friend class ThreadPool;
  13741. friend class ThreadPoolThread;
  13742. String jobName;
  13743. ThreadPool* pool;
  13744. bool shouldStop, isActive, shouldBeDeleted;
  13745. ThreadPoolJob (const ThreadPoolJob&);
  13746. ThreadPoolJob& operator= (const ThreadPoolJob&);
  13747. };
  13748. /**
  13749. A set of threads that will run a list of jobs.
  13750. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  13751. will be called by the next pooled thread that becomes free.
  13752. @see ThreadPoolJob, Thread
  13753. */
  13754. class JUCE_API ThreadPool
  13755. {
  13756. public:
  13757. /** Creates a thread pool.
  13758. Once you've created a pool, you can give it some things to do with the addJob()
  13759. method.
  13760. @param numberOfThreads the maximum number of actual threads to run.
  13761. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  13762. until there are some jobs to run. If false, then
  13763. all the threads will be fired-up immediately so that
  13764. they're ready for action
  13765. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  13766. inactive for this length of time, they will automatically
  13767. be stopped until more jobs come along and they're needed
  13768. */
  13769. ThreadPool (int numberOfThreads,
  13770. bool startThreadsOnlyWhenNeeded = true,
  13771. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  13772. /** Destructor.
  13773. This will attempt to remove all the jobs before deleting, but if you want to
  13774. specify a timeout, you should call removeAllJobs() explicitly before deleting
  13775. the pool.
  13776. */
  13777. ~ThreadPool();
  13778. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  13779. for some kind of operation.
  13780. @see ThreadPool::removeAllJobs
  13781. */
  13782. class JUCE_API JobSelector
  13783. {
  13784. public:
  13785. virtual ~JobSelector() {}
  13786. /** Should return true if the specified thread matches your criteria for whatever
  13787. operation that this object is being used for.
  13788. Any implementation of this method must be extremely fast and thread-safe!
  13789. */
  13790. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  13791. };
  13792. /** Adds a job to the queue.
  13793. Once a job has been added, then the next time a thread is free, it will run
  13794. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  13795. runJob() method, the pool will either remove the job from the pool or add it to
  13796. the back of the queue to be run again.
  13797. */
  13798. void addJob (ThreadPoolJob* job);
  13799. /** Tries to remove a job from the pool.
  13800. If the job isn't yet running, this will simply remove it. If it is running, it
  13801. will wait for it to finish.
  13802. If the timeout period expires before the job finishes running, then the job will be
  13803. left in the pool and this will return false. It returns true if the job is sucessfully
  13804. stopped and removed.
  13805. @param job the job to remove
  13806. @param interruptIfRunning if true, then if the job is currently busy, its
  13807. ThreadPoolJob::signalJobShouldExit() method will be called to try
  13808. to interrupt it. If false, then if the job will be allowed to run
  13809. until it stops normally (or the timeout expires)
  13810. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  13811. before giving up and returning false
  13812. */
  13813. bool removeJob (ThreadPoolJob* job,
  13814. bool interruptIfRunning,
  13815. int timeOutMilliseconds);
  13816. /** Tries to remove all jobs from the pool.
  13817. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  13818. methods called to try to interrupt them
  13819. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  13820. before giving up and returning false
  13821. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  13822. they will simply be removed from the pool. Jobs that are already running when
  13823. this method is called can choose whether they should be deleted by
  13824. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  13825. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  13826. jobs should be removed. If it is zero, all jobs are removed
  13827. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  13828. expires while waiting for one or more jobs to stop
  13829. */
  13830. bool removeAllJobs (bool interruptRunningJobs,
  13831. int timeOutMilliseconds,
  13832. bool deleteInactiveJobs = false,
  13833. JobSelector* selectedJobsToRemove = 0);
  13834. /** Returns the number of jobs currently running or queued.
  13835. */
  13836. int getNumJobs() const;
  13837. /** Returns one of the jobs in the queue.
  13838. Note that this can be a very volatile list as jobs might be continuously getting shifted
  13839. around in the list, and this method may return 0 if the index is currently out-of-range.
  13840. */
  13841. ThreadPoolJob* getJob (int index) const;
  13842. /** Returns true if the given job is currently queued or running.
  13843. @see isJobRunning()
  13844. */
  13845. bool contains (const ThreadPoolJob* job) const;
  13846. /** Returns true if the given job is currently being run by a thread.
  13847. */
  13848. bool isJobRunning (const ThreadPoolJob* job) const;
  13849. /** Waits until a job has finished running and has been removed from the pool.
  13850. This will wait until the job is no longer in the pool - i.e. until its
  13851. runJob() method returns ThreadPoolJob::jobHasFinished.
  13852. If the timeout period expires before the job finishes, this will return false;
  13853. it returns true if the job has finished successfully.
  13854. */
  13855. bool waitForJobToFinish (const ThreadPoolJob* job,
  13856. int timeOutMilliseconds) const;
  13857. /** Returns a list of the names of all the jobs currently running or queued.
  13858. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  13859. */
  13860. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  13861. /** Changes the priority of all the threads.
  13862. This will call Thread::setPriority() for each thread in the pool.
  13863. May return false if for some reason the priority can't be changed.
  13864. */
  13865. bool setThreadPriorities (int newPriority);
  13866. juce_UseDebuggingNewOperator
  13867. private:
  13868. const int threadStopTimeout;
  13869. int priority;
  13870. class ThreadPoolThread;
  13871. OwnedArray <ThreadPoolThread> threads;
  13872. Array <ThreadPoolJob*> jobs;
  13873. CriticalSection lock;
  13874. uint32 lastJobEndTime;
  13875. WaitableEvent jobFinishedSignal;
  13876. friend class ThreadPoolThread;
  13877. bool runNextJob();
  13878. ThreadPool (const ThreadPool&);
  13879. ThreadPool& operator= (const ThreadPool&);
  13880. };
  13881. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  13882. /*** End of inlined file: juce_ThreadPool.h ***/
  13883. #endif
  13884. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13885. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  13886. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13887. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13888. /**
  13889. Used by the TimeSliceThread class.
  13890. To register your class with a TimeSliceThread, derive from this class and
  13891. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  13892. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  13893. deleting your client!
  13894. @see TimeSliceThread
  13895. */
  13896. class JUCE_API TimeSliceClient
  13897. {
  13898. public:
  13899. /** Destructor. */
  13900. virtual ~TimeSliceClient() {}
  13901. /** Called back by a TimeSliceThread.
  13902. When you register this class with it, a TimeSliceThread will repeatedly call
  13903. this method.
  13904. The implementation of this method should use its time-slice to do something that's
  13905. quick - never block for longer than absolutely necessary.
  13906. @returns Your method should return true if it needs more time, or false if it's
  13907. not too busy and doesn't need calling back urgently. If all the thread's
  13908. clients indicate that they're not busy, then it'll save CPU by sleeping for
  13909. up to half a second in between callbacks. You can force the TimeSliceThread
  13910. to wake up and poll again immediately by calling its notify() method.
  13911. */
  13912. virtual bool useTimeSlice() = 0;
  13913. };
  13914. /**
  13915. A thread that keeps a list of clients, and calls each one in turn, giving them
  13916. all a chance to run some sort of short task.
  13917. @see TimeSliceClient, Thread
  13918. */
  13919. class JUCE_API TimeSliceThread : public Thread
  13920. {
  13921. public:
  13922. /**
  13923. Creates a TimeSliceThread.
  13924. When first created, the thread is not running. Use the startThread()
  13925. method to start it.
  13926. */
  13927. explicit TimeSliceThread (const String& threadName);
  13928. /** Destructor.
  13929. Deleting a Thread object that is running will only give the thread a
  13930. brief opportunity to stop itself cleanly, so it's recommended that you
  13931. should always call stopThread() with a decent timeout before deleting,
  13932. to avoid the thread being forcibly killed (which is a Bad Thing).
  13933. */
  13934. ~TimeSliceThread();
  13935. /** Adds a client to the list.
  13936. The client's callbacks will start immediately (possibly before the method
  13937. has returned).
  13938. */
  13939. void addTimeSliceClient (TimeSliceClient* client);
  13940. /** Removes a client from the list.
  13941. This method will make sure that all callbacks to the client have completely
  13942. finished before the method returns.
  13943. */
  13944. void removeTimeSliceClient (TimeSliceClient* client);
  13945. /** Returns the number of registered clients. */
  13946. int getNumClients() const;
  13947. /** Returns one of the registered clients. */
  13948. TimeSliceClient* getClient (int index) const;
  13949. /** @internal */
  13950. void run();
  13951. juce_UseDebuggingNewOperator
  13952. private:
  13953. CriticalSection callbackLock, listLock;
  13954. Array <TimeSliceClient*> clients;
  13955. int index;
  13956. TimeSliceClient* clientBeingCalled;
  13957. bool clientsChanged;
  13958. TimeSliceThread (const TimeSliceThread&);
  13959. TimeSliceThread& operator= (const TimeSliceThread&);
  13960. };
  13961. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13962. /*** End of inlined file: juce_TimeSliceThread.h ***/
  13963. #endif
  13964. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13965. #endif
  13966. #endif
  13967. /*** End of inlined file: juce_core_includes.h ***/
  13968. // if you're compiling a command-line app, you might want to just include the core headers,
  13969. // so you can set this macro before including juce.h
  13970. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  13971. /*** Start of inlined file: juce_app_includes.h ***/
  13972. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  13973. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  13974. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  13975. /*** Start of inlined file: juce_Application.h ***/
  13976. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  13977. #define __JUCE_APPLICATION_JUCEHEADER__
  13978. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  13979. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  13980. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  13981. /*** Start of inlined file: juce_Component.h ***/
  13982. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  13983. #define __JUCE_COMPONENT_JUCEHEADER__
  13984. /*** Start of inlined file: juce_MouseCursor.h ***/
  13985. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  13986. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  13987. class Image;
  13988. class ComponentPeer;
  13989. class Component;
  13990. /**
  13991. Represents a mouse cursor image.
  13992. This object can either be used to represent one of the standard mouse
  13993. cursor shapes, or a custom one generated from an image.
  13994. */
  13995. class JUCE_API MouseCursor
  13996. {
  13997. public:
  13998. /** The set of available standard mouse cursors. */
  13999. enum StandardCursorType
  14000. {
  14001. NoCursor = 0, /**< An invisible cursor. */
  14002. NormalCursor, /**< The stardard arrow cursor. */
  14003. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  14004. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  14005. CrosshairCursor, /**< A pair of crosshairs. */
  14006. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  14007. that you're dragging a copy of something. */
  14008. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  14009. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  14010. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  14011. UpDownResizeCursor, /**< an arrow pointing up and down. */
  14012. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  14013. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  14014. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  14015. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  14016. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  14017. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  14018. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  14019. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  14020. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  14021. };
  14022. /** Creates the standard arrow cursor. */
  14023. MouseCursor();
  14024. /** Creates one of the standard mouse cursor */
  14025. MouseCursor (StandardCursorType type);
  14026. /** Creates a custom cursor from an image.
  14027. @param image the image to use for the cursor - if this is bigger than the
  14028. system can manage, it might get scaled down first, and might
  14029. also have to be turned to black-and-white if it can't do colour
  14030. cursors.
  14031. @param hotSpotX the x position of the cursor's hotspot within the image
  14032. @param hotSpotY the y position of the cursor's hotspot within the image
  14033. */
  14034. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  14035. /** Creates a copy of another cursor object. */
  14036. MouseCursor (const MouseCursor& other);
  14037. /** Copies this cursor from another object. */
  14038. MouseCursor& operator= (const MouseCursor& other);
  14039. /** Destructor. */
  14040. ~MouseCursor();
  14041. /** Checks whether two mouse cursors are the same.
  14042. For custom cursors, two cursors created from the same image won't be
  14043. recognised as the same, only MouseCursor objects that have been
  14044. copied from the same object.
  14045. */
  14046. bool operator== (const MouseCursor& other) const throw();
  14047. /** Checks whether two mouse cursors are the same.
  14048. For custom cursors, two cursors created from the same image won't be
  14049. recognised as the same, only MouseCursor objects that have been
  14050. copied from the same object.
  14051. */
  14052. bool operator!= (const MouseCursor& other) const throw();
  14053. /** Makes the system show its default 'busy' cursor.
  14054. This will turn the system cursor to an hourglass or spinning beachball
  14055. until the next time the mouse is moved, or hideWaitCursor() is called.
  14056. This is handy if the message loop is about to block for a couple of
  14057. seconds while busy and you want to give the user feedback about this.
  14058. @see MessageManager::setTimeBeforeShowingWaitCursor
  14059. */
  14060. static void showWaitCursor();
  14061. /** If showWaitCursor has been called, this will return the mouse to its
  14062. normal state.
  14063. This will look at what component is under the mouse, and update the
  14064. cursor to be the correct one for that component.
  14065. @see showWaitCursor
  14066. */
  14067. static void hideWaitCursor();
  14068. juce_UseDebuggingNewOperator
  14069. private:
  14070. class SharedCursorHandle;
  14071. friend class SharedCursorHandle;
  14072. SharedCursorHandle* cursorHandle;
  14073. friend class MouseInputSourceInternal;
  14074. void showInWindow (ComponentPeer* window) const;
  14075. void showInAllWindows() const;
  14076. void* getHandle() const throw();
  14077. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  14078. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  14079. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  14080. };
  14081. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  14082. /*** End of inlined file: juce_MouseCursor.h ***/
  14083. /*** Start of inlined file: juce_MouseListener.h ***/
  14084. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  14085. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  14086. class MouseEvent;
  14087. /**
  14088. A MouseListener can be registered with a component to receive callbacks
  14089. about mouse events that happen to that component.
  14090. @see Component::addMouseListener, Component::removeMouseListener
  14091. */
  14092. class JUCE_API MouseListener
  14093. {
  14094. public:
  14095. /** Destructor. */
  14096. virtual ~MouseListener() {}
  14097. /** Called when the mouse moves inside a component.
  14098. If the mouse button isn't pressed and the mouse moves over a component,
  14099. this will be called to let the component react to this.
  14100. A component will always get a mouseEnter callback before a mouseMove.
  14101. @param e details about the position and status of the mouse event, including
  14102. the source component in which it occurred
  14103. @see mouseEnter, mouseExit, mouseDrag, contains
  14104. */
  14105. virtual void mouseMove (const MouseEvent& e);
  14106. /** Called when the mouse first enters a component.
  14107. If the mouse button isn't pressed and the mouse moves into a component,
  14108. this will be called to let the component react to this.
  14109. When the mouse button is pressed and held down while being moved in
  14110. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  14111. mouseDrag messages are sent to the component that the mouse was originally
  14112. clicked on, until the button is released.
  14113. @param e details about the position and status of the mouse event, including
  14114. the source component in which it occurred
  14115. @see mouseExit, mouseDrag, mouseMove, contains
  14116. */
  14117. virtual void mouseEnter (const MouseEvent& e);
  14118. /** Called when the mouse moves out of a component.
  14119. This will be called when the mouse moves off the edge of this
  14120. component.
  14121. If the mouse button was pressed, and it was then dragged off the
  14122. edge of the component and released, then this callback will happen
  14123. when the button is released, after the mouseUp callback.
  14124. @param e details about the position and status of the mouse event, including
  14125. the source component in which it occurred
  14126. @see mouseEnter, mouseDrag, mouseMove, contains
  14127. */
  14128. virtual void mouseExit (const MouseEvent& e);
  14129. /** Called when a mouse button is pressed.
  14130. The MouseEvent object passed in contains lots of methods for finding out
  14131. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14132. were held down at the time.
  14133. Once a button is held down, the mouseDrag method will be called when the
  14134. mouse moves, until the button is released.
  14135. @param e details about the position and status of the mouse event, including
  14136. the source component in which it occurred
  14137. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  14138. */
  14139. virtual void mouseDown (const MouseEvent& e);
  14140. /** Called when the mouse is moved while a button is held down.
  14141. When a mouse button is pressed inside a component, that component
  14142. receives mouseDrag callbacks each time the mouse moves, even if the
  14143. mouse strays outside the component's bounds.
  14144. @param e details about the position and status of the mouse event, including
  14145. the source component in which it occurred
  14146. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  14147. */
  14148. virtual void mouseDrag (const MouseEvent& e);
  14149. /** Called when a mouse button is released.
  14150. A mouseUp callback is sent to the component in which a button was pressed
  14151. even if the mouse is actually over a different component when the
  14152. button is released.
  14153. The MouseEvent object passed in contains lots of methods for finding out
  14154. which buttons were down just before they were released.
  14155. @param e details about the position and status of the mouse event, including
  14156. the source component in which it occurred
  14157. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  14158. */
  14159. virtual void mouseUp (const MouseEvent& e);
  14160. /** Called when a mouse button has been double-clicked on a component.
  14161. The MouseEvent object passed in contains lots of methods for finding out
  14162. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14163. were held down at the time.
  14164. @param e details about the position and status of the mouse event, including
  14165. the source component in which it occurred
  14166. @see mouseDown, mouseUp
  14167. */
  14168. virtual void mouseDoubleClick (const MouseEvent& e);
  14169. /** Called when the mouse-wheel is moved.
  14170. This callback is sent to the component that the mouse is over when the
  14171. wheel is moved.
  14172. If not overridden, the component will forward this message to its parent, so
  14173. that parent components can collect mouse-wheel messages that happen to
  14174. child components which aren't interested in them.
  14175. @param e details about the position and status of the mouse event, including
  14176. the source component in which it occurred
  14177. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  14178. value means the wheel has been pushed to the right, negative means it
  14179. was pushed to the left
  14180. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  14181. value means the wheel has been pushed upwards, negative means it
  14182. was pushed downwards
  14183. */
  14184. virtual void mouseWheelMove (const MouseEvent& e,
  14185. float wheelIncrementX,
  14186. float wheelIncrementY);
  14187. };
  14188. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  14189. /*** End of inlined file: juce_MouseListener.h ***/
  14190. /*** Start of inlined file: juce_MouseEvent.h ***/
  14191. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  14192. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  14193. class Component;
  14194. class MouseInputSource;
  14195. /*** Start of inlined file: juce_ModifierKeys.h ***/
  14196. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  14197. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  14198. /**
  14199. Represents the state of the mouse buttons and modifier keys.
  14200. This is used both by mouse events and by KeyPress objects to describe
  14201. the state of keys such as shift, control, alt, etc.
  14202. @see KeyPress, MouseEvent::mods
  14203. */
  14204. class JUCE_API ModifierKeys
  14205. {
  14206. public:
  14207. /** Creates a ModifierKeys object from a raw set of flags.
  14208. @param flags to represent the keys that are down
  14209. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  14210. rightButtonModifier, commandModifier, popupMenuClickModifier
  14211. */
  14212. ModifierKeys (int flags = 0) throw();
  14213. /** Creates a copy of another object. */
  14214. ModifierKeys (const ModifierKeys& other) throw();
  14215. /** Copies this object from another one. */
  14216. ModifierKeys& operator= (const ModifierKeys& other) throw();
  14217. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  14218. This is a platform-agnostic way of checking for the operating system's
  14219. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  14220. Windows/Linux, it's actually checking for the CTRL key.
  14221. */
  14222. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  14223. /** Checks whether the user is trying to launch a pop-up menu.
  14224. This checks for platform-specific modifiers that might indicate that the user
  14225. is following the operating system's normal method of showing a pop-up menu.
  14226. So on Windows/Linux, this method is really testing for a right-click.
  14227. On the Mac, it tests for either the CTRL key being down, or a right-click.
  14228. */
  14229. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  14230. /** Checks whether the flag is set for the left mouse-button. */
  14231. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  14232. /** Checks whether the flag is set for the right mouse-button.
  14233. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  14234. this is platform-independent (and makes your code more explanatory too).
  14235. */
  14236. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  14237. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  14238. /** Tests for any of the mouse-button flags. */
  14239. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  14240. /** Tests for any of the modifier key flags. */
  14241. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  14242. /** Checks whether the shift key's flag is set. */
  14243. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  14244. /** Checks whether the CTRL key's flag is set.
  14245. Remember that it's better to use the platform-agnostic routines to test for command-key and
  14246. popup-menu modifiers.
  14247. @see isCommandDown, isPopupMenu
  14248. */
  14249. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  14250. /** Checks whether the shift key's flag is set. */
  14251. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  14252. /** Flags that represent the different keys. */
  14253. enum Flags
  14254. {
  14255. /** Shift key flag. */
  14256. shiftModifier = 1,
  14257. /** CTRL key flag. */
  14258. ctrlModifier = 2,
  14259. /** ALT key flag. */
  14260. altModifier = 4,
  14261. /** Left mouse button flag. */
  14262. leftButtonModifier = 16,
  14263. /** Right mouse button flag. */
  14264. rightButtonModifier = 32,
  14265. /** Middle mouse button flag. */
  14266. middleButtonModifier = 64,
  14267. #if JUCE_MAC
  14268. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14269. commandModifier = 8,
  14270. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14271. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14272. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  14273. #else
  14274. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14275. commandModifier = ctrlModifier,
  14276. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14277. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14278. popupMenuClickModifier = rightButtonModifier,
  14279. #endif
  14280. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  14281. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  14282. /** Represents a combination of all the mouse buttons at once. */
  14283. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  14284. };
  14285. /** Returns a copy of only the mouse-button flags */
  14286. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  14287. /** Returns a copy of only the non-mouse flags */
  14288. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  14289. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  14290. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  14291. /** Returns the raw flags for direct testing. */
  14292. inline int getRawFlags() const throw() { return flags; }
  14293. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  14294. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  14295. /** Tests a combination of flags and returns true if any of them are set. */
  14296. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14297. /** Returns the total number of mouse buttons that are down. */
  14298. int getNumMouseButtonsDown() const throw();
  14299. /** Creates a ModifierKeys object to represent the last-known state of the
  14300. keyboard and mouse buttons.
  14301. @see getCurrentModifiersRealtime
  14302. */
  14303. static const ModifierKeys getCurrentModifiers() throw();
  14304. /** Creates a ModifierKeys object to represent the current state of the
  14305. keyboard and mouse buttons.
  14306. This isn't often needed and isn't recommended, but will actively check all the
  14307. mouse and key states rather than just returning their last-known state like
  14308. getCurrentModifiers() does.
  14309. This is only needed in special circumstances for up-to-date modifier information
  14310. at times when the app's event loop isn't running normally.
  14311. */
  14312. static const ModifierKeys getCurrentModifiersRealtime() throw();
  14313. private:
  14314. int flags;
  14315. static ModifierKeys currentModifiers;
  14316. friend class ComponentPeer;
  14317. friend class MouseInputSource;
  14318. friend class MouseInputSourceInternal;
  14319. static void updateCurrentModifiers() throw();
  14320. };
  14321. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  14322. /*** End of inlined file: juce_ModifierKeys.h ***/
  14323. /*** Start of inlined file: juce_Point.h ***/
  14324. #ifndef __JUCE_POINT_JUCEHEADER__
  14325. #define __JUCE_POINT_JUCEHEADER__
  14326. /*** Start of inlined file: juce_AffineTransform.h ***/
  14327. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14328. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14329. /**
  14330. Represents a 2D affine-transformation matrix.
  14331. An affine transformation is a transformation such as a rotation, scale, shear,
  14332. resize or translation.
  14333. These are used for various 2D transformation tasks, e.g. with Path objects.
  14334. @see Path, Point, Line
  14335. */
  14336. class JUCE_API AffineTransform
  14337. {
  14338. public:
  14339. /** Creates an identity transform. */
  14340. AffineTransform() throw();
  14341. /** Creates a copy of another transform. */
  14342. AffineTransform (const AffineTransform& other) throw();
  14343. /** Creates a transform from a set of raw matrix values.
  14344. The resulting matrix is:
  14345. (mat00 mat01 mat02)
  14346. (mat10 mat11 mat12)
  14347. ( 0 0 1 )
  14348. */
  14349. AffineTransform (float mat00, float mat01, float mat02,
  14350. float mat10, float mat11, float mat12) throw();
  14351. /** Copies from another AffineTransform object */
  14352. AffineTransform& operator= (const AffineTransform& other) throw();
  14353. /** Compares two transforms. */
  14354. bool operator== (const AffineTransform& other) const throw();
  14355. /** Compares two transforms. */
  14356. bool operator!= (const AffineTransform& other) const throw();
  14357. /** A ready-to-use identity transform, which you can use to append other
  14358. transformations to.
  14359. e.g. @code
  14360. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  14361. .scaled (2.0f);
  14362. @endcode
  14363. */
  14364. static const AffineTransform identity;
  14365. /** Transforms a 2D co-ordinate using this matrix. */
  14366. template <typename ValueType>
  14367. void transformPoint (ValueType& x, ValueType& y) const throw()
  14368. {
  14369. const ValueType oldX = x;
  14370. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  14371. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  14372. }
  14373. /** Transforms two 2D co-ordinates using this matrix.
  14374. This is just a shortcut for calling transformPoint() on each of these pairs of
  14375. coordinates in turn. (And putting all the calculations into one function hopefully
  14376. also gives the compiler a bit more scope for pipelining it).
  14377. */
  14378. template <typename ValueType>
  14379. void transformPoints (ValueType& x1, ValueType& y1,
  14380. ValueType& x2, ValueType& y2) const throw()
  14381. {
  14382. const ValueType oldX1 = x1, oldX2 = x2;
  14383. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  14384. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  14385. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  14386. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  14387. }
  14388. /** Transforms three 2D co-ordinates using this matrix.
  14389. This is just a shortcut for calling transformPoint() on each of these pairs of
  14390. coordinates in turn. (And putting all the calculations into one function hopefully
  14391. also gives the compiler a bit more scope for pipelining it).
  14392. */
  14393. template <typename ValueType>
  14394. void transformPoints (ValueType& x1, ValueType& y1,
  14395. ValueType& x2, ValueType& y2,
  14396. ValueType& x3, ValueType& y3) const throw()
  14397. {
  14398. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  14399. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  14400. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  14401. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  14402. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  14403. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  14404. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  14405. }
  14406. /** Returns a new transform which is the same as this one followed by a translation. */
  14407. const AffineTransform translated (float deltaX,
  14408. float deltaY) const throw();
  14409. /** Returns a new transform which is a translation. */
  14410. static const AffineTransform translation (float deltaX,
  14411. float deltaY) throw();
  14412. /** Returns a transform which is the same as this one followed by a rotation.
  14413. The rotation is specified by a number of radians to rotate clockwise, centred around
  14414. the origin (0, 0).
  14415. */
  14416. const AffineTransform rotated (float angleInRadians) const throw();
  14417. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  14418. The rotation is specified by a number of radians to rotate clockwise, centred around
  14419. the co-ordinates passed in.
  14420. */
  14421. const AffineTransform rotated (float angleInRadians,
  14422. float pivotX,
  14423. float pivotY) const throw();
  14424. /** Returns a new transform which is a rotation about (0, 0). */
  14425. static const AffineTransform rotation (float angleInRadians) throw();
  14426. /** Returns a new transform which is a rotation about a given point. */
  14427. static const AffineTransform rotation (float angleInRadians,
  14428. float pivotX,
  14429. float pivotY) throw();
  14430. /** Returns a transform which is the same as this one followed by a re-scaling.
  14431. The scaling is centred around the origin (0, 0).
  14432. */
  14433. const AffineTransform scaled (float factorX,
  14434. float factorY) const throw();
  14435. /** Returns a new transform which is a re-scale about the origin. */
  14436. static const AffineTransform scale (float factorX,
  14437. float factorY) throw();
  14438. /** Returns a transform which is the same as this one followed by a shear.
  14439. The shear is centred around the origin (0, 0).
  14440. */
  14441. const AffineTransform sheared (float shearX,
  14442. float shearY) const throw();
  14443. /** Returns a matrix which is the inverse operation of this one.
  14444. Some matrices don't have an inverse - in this case, the method will just return
  14445. an identity transform.
  14446. */
  14447. const AffineTransform inverted() const throw();
  14448. /** Returns the transform that will map three known points onto three coordinates
  14449. that are supplied.
  14450. This returns the transform that will transform (0, 0) into (x00, y00),
  14451. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  14452. */
  14453. static const AffineTransform fromTargetPoints (float x00, float y00,
  14454. float x10, float y10,
  14455. float x01, float y01) throw();
  14456. /** Returns the transform that will map three specified points onto three target points.
  14457. */
  14458. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  14459. float sourceX2, float sourceY2, float targetX2, float targetY2,
  14460. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  14461. /** Returns the result of concatenating another transformation after this one. */
  14462. const AffineTransform followedBy (const AffineTransform& other) const throw();
  14463. /** Returns true if this transform has no effect on points. */
  14464. bool isIdentity() const throw();
  14465. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  14466. bool isSingularity() const throw();
  14467. /** Returns true if the transform only translates, and doesn't scale or rotate the
  14468. points. */
  14469. bool isOnlyTranslation() const throw();
  14470. /** If this transform is only a translation, this returns the X offset.
  14471. @see isOnlyTranslation
  14472. */
  14473. float getTranslationX() const throw() { return mat02; }
  14474. /** If this transform is only a translation, this returns the X offset.
  14475. @see isOnlyTranslation
  14476. */
  14477. float getTranslationY() const throw() { return mat12; }
  14478. /* The transform matrix is:
  14479. (mat00 mat01 mat02)
  14480. (mat10 mat11 mat12)
  14481. ( 0 0 1 )
  14482. */
  14483. float mat00, mat01, mat02;
  14484. float mat10, mat11, mat12;
  14485. juce_UseDebuggingNewOperator
  14486. private:
  14487. const AffineTransform followedBy (float mat00, float mat01, float mat02,
  14488. float mat10, float mat11, float mat12) const throw();
  14489. };
  14490. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14491. /*** End of inlined file: juce_AffineTransform.h ***/
  14492. /**
  14493. A pair of (x, y) co-ordinates.
  14494. The ValueType template should be a primitive type such as int, float, double,
  14495. rather than a class.
  14496. @see Line, Path, AffineTransform
  14497. */
  14498. template <typename ValueType>
  14499. class Point
  14500. {
  14501. public:
  14502. /** Creates a point with co-ordinates (0, 0). */
  14503. Point() throw() : x (0), y (0) {}
  14504. /** Creates a copy of another point. */
  14505. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  14506. /** Creates a point from an (x, y) position. */
  14507. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  14508. /** Destructor. */
  14509. ~Point() throw() {}
  14510. /** Copies this point from another one. */
  14511. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  14512. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  14513. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  14514. /** Returns true if the point is (0, 0). */
  14515. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  14516. /** Returns the point's x co-ordinate. */
  14517. inline ValueType getX() const throw() { return x; }
  14518. /** Returns the point's y co-ordinate. */
  14519. inline ValueType getY() const throw() { return y; }
  14520. /** Sets the point's x co-ordinate. */
  14521. inline void setX (const ValueType newX) throw() { x = newX; }
  14522. /** Sets the point's y co-ordinate. */
  14523. inline void setY (const ValueType newY) throw() { y = newY; }
  14524. /** Returns a point which has the same Y position as this one, but a new X. */
  14525. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  14526. /** Returns a point which has the same X position as this one, but a new Y. */
  14527. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  14528. /** Changes the point's x and y co-ordinates. */
  14529. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  14530. /** Adds a pair of co-ordinates to this value. */
  14531. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  14532. /** Returns a point with a given offset from this one. */
  14533. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  14534. /** Adds two points together. */
  14535. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  14536. /** Adds another point's co-ordinates to this one. */
  14537. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  14538. /** Subtracts one points from another. */
  14539. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  14540. /** Subtracts another point's co-ordinates to this one. */
  14541. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  14542. /** Returns a point whose coordinates are multiplied by a given value. */
  14543. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  14544. /** Multiplies the point's co-ordinates by a value. */
  14545. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  14546. /** Returns a point whose coordinates are divided by a given value. */
  14547. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  14548. /** Divides the point's co-ordinates by a value. */
  14549. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  14550. /** Returns the inverse of this point. */
  14551. const Point operator-() const throw() { return Point (-x, -y); }
  14552. /** Returns the straight-line distance between this point and another one. */
  14553. ValueType getDistanceFromOrigin() const throw() { return (ValueType) juce_hypot (x, y); }
  14554. /** Returns the straight-line distance between this point and another one. */
  14555. ValueType getDistanceFrom (const Point& other) const throw() { return (ValueType) juce_hypot (x - other.x, y - other.y); }
  14556. /** Returns the angle from this point to another one.
  14557. The return value is the number of radians clockwise from the 3 o'clock direction,
  14558. where this point is the centre and the other point is on the circumference.
  14559. */
  14560. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  14561. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  14562. @param radius the radius of the circle.
  14563. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14564. */
  14565. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  14566. y - radius * std::cos (angle)); }
  14567. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  14568. @param radiusX the horizontal radius of the circle.
  14569. @param radiusY the vertical radius of the circle.
  14570. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14571. */
  14572. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  14573. y - radiusY * std::cos (angle)); }
  14574. /** Uses a transform to change the point's co-ordinates.
  14575. This will only compile if ValueType = float!
  14576. @see AffineTransform::transformPoint
  14577. */
  14578. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  14579. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  14580. const Point transformedBy (const AffineTransform& transform) const throw() { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  14581. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  14582. /** Casts this point to a Point<float> object. */
  14583. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  14584. /** Returns the point as a string in the form "x, y". */
  14585. const String toString() const { return String (x) + ", " + String (y); }
  14586. juce_UseDebuggingNewOperator
  14587. private:
  14588. ValueType x, y;
  14589. };
  14590. #endif // __JUCE_POINT_JUCEHEADER__
  14591. /*** End of inlined file: juce_Point.h ***/
  14592. /**
  14593. Contains position and status information about a mouse event.
  14594. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  14595. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  14596. */
  14597. class JUCE_API MouseEvent
  14598. {
  14599. public:
  14600. /** Creates a MouseEvent.
  14601. Normally an application will never need to use this.
  14602. @param source the source that's invoking the event
  14603. @param position the position of the mouse, relative to the component that is passed-in
  14604. @param modifiers the key modifiers at the time of the event
  14605. @param eventComponent the component that the mouse event applies to
  14606. @param originator the component that originally received the event
  14607. @param eventTime the time the event happened
  14608. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  14609. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14610. the same as the current mouse-x position.
  14611. @param mouseDownTime the time at which the corresponding mouse-down event happened
  14612. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14613. the same as the current mouse-event time.
  14614. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  14615. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  14616. */
  14617. MouseEvent (MouseInputSource& source,
  14618. const Point<int>& position,
  14619. const ModifierKeys& modifiers,
  14620. Component* eventComponent,
  14621. Component* originator,
  14622. const Time& eventTime,
  14623. const Point<int> mouseDownPos,
  14624. const Time& mouseDownTime,
  14625. int numberOfClicks,
  14626. bool mouseWasDragged) throw();
  14627. /** Destructor. */
  14628. ~MouseEvent() throw();
  14629. /** The x-position of the mouse when the event occurred.
  14630. This value is relative to the top-left of the component to which the
  14631. event applies (as indicated by the MouseEvent::eventComponent field).
  14632. */
  14633. const int x;
  14634. /** The y-position of the mouse when the event occurred.
  14635. This value is relative to the top-left of the component to which the
  14636. event applies (as indicated by the MouseEvent::eventComponent field).
  14637. */
  14638. const int y;
  14639. /** The key modifiers associated with the event.
  14640. This will let you find out which mouse buttons were down, as well as which
  14641. modifier keys were held down.
  14642. When used for mouse-up events, this will indicate the state of the mouse buttons
  14643. just before they were released, so that you can tell which button they let go of.
  14644. */
  14645. const ModifierKeys mods;
  14646. /** The component that this event applies to.
  14647. This is usually the component that the mouse was over at the time, but for mouse-drag
  14648. events the mouse could actually be over a different component and the events are
  14649. still sent to the component that the button was originally pressed on.
  14650. The x and y member variables are relative to this component's position.
  14651. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14652. component, this pointer will be updated, but originalComponent remains unchanged.
  14653. @see originalComponent
  14654. */
  14655. Component* const eventComponent;
  14656. /** The component that the event first occurred on.
  14657. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14658. component, this value remains unchanged to indicate the first component that received it.
  14659. @see eventComponent
  14660. */
  14661. Component* const originalComponent;
  14662. /** The time that this mouse-event occurred.
  14663. */
  14664. const Time eventTime;
  14665. /** The source device that generated this event.
  14666. */
  14667. MouseInputSource& source;
  14668. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  14669. The co-ordinate is relative to the component specified in MouseEvent::component.
  14670. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14671. */
  14672. int getMouseDownX() const throw();
  14673. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  14674. The co-ordinate is relative to the component specified in MouseEvent::component.
  14675. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14676. */
  14677. int getMouseDownY() const throw();
  14678. /** Returns the co-ordinates of the last place that a mouse was pressed.
  14679. The co-ordinates are relative to the component specified in MouseEvent::component.
  14680. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14681. */
  14682. const Point<int> getMouseDownPosition() const throw();
  14683. /** Returns the straight-line distance between where the mouse is now and where it
  14684. was the last time the button was pressed.
  14685. This is quite handy for things like deciding whether the user has moved far enough
  14686. for it to be considered a drag operation.
  14687. @see getDistanceFromDragStartX
  14688. */
  14689. int getDistanceFromDragStart() const throw();
  14690. /** Returns the difference between the mouse's current x postion and where it was
  14691. when the button was last pressed.
  14692. @see getDistanceFromDragStart
  14693. */
  14694. int getDistanceFromDragStartX() const throw();
  14695. /** Returns the difference between the mouse's current y postion and where it was
  14696. when the button was last pressed.
  14697. @see getDistanceFromDragStart
  14698. */
  14699. int getDistanceFromDragStartY() const throw();
  14700. /** Returns the difference between the mouse's current postion and where it was
  14701. when the button was last pressed.
  14702. @see getDistanceFromDragStart
  14703. */
  14704. const Point<int> getOffsetFromDragStart() const throw();
  14705. /** Returns true if the mouse has just been clicked.
  14706. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  14707. the user has dragged the mouse more than a few pixels from the place where the
  14708. mouse-down occurred.
  14709. Once they have dragged it far enough for this method to return false, it will continue
  14710. to return false until the mouse-up, even if they move the mouse back to the same
  14711. position where they originally pressed it. This means that it's very handy for
  14712. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  14713. callback to ignore any small movements they might make while clicking.
  14714. @returns true if the mouse wasn't dragged by more than a few pixels between
  14715. the last time the button was pressed and released.
  14716. */
  14717. bool mouseWasClicked() const throw();
  14718. /** For a click event, the number of times the mouse was clicked in succession.
  14719. So for example a double-click event will return 2, a triple-click 3, etc.
  14720. */
  14721. int getNumberOfClicks() const throw() { return numberOfClicks; }
  14722. /** Returns the time that the mouse button has been held down for.
  14723. If called from a mouseDrag or mouseUp callback, this will return the
  14724. number of milliseconds since the corresponding mouseDown event occurred.
  14725. If called in other contexts, e.g. a mouseMove, then the returned value
  14726. may be 0 or an undefined value.
  14727. */
  14728. int getLengthOfMousePress() const throw();
  14729. /** The position of the mouse when the event occurred.
  14730. This position is relative to the top-left of the component to which the
  14731. event applies (as indicated by the MouseEvent::eventComponent field).
  14732. */
  14733. const Point<int> getPosition() const throw();
  14734. /** Returns the mouse x position of this event, in global screen co-ordinates.
  14735. The co-ordinates are relative to the top-left of the main monitor.
  14736. @see getScreenPosition
  14737. */
  14738. int getScreenX() const;
  14739. /** Returns the mouse y position of this event, in global screen co-ordinates.
  14740. The co-ordinates are relative to the top-left of the main monitor.
  14741. @see getScreenPosition
  14742. */
  14743. int getScreenY() const;
  14744. /** Returns the mouse position of this event, in global screen co-ordinates.
  14745. The co-ordinates are relative to the top-left of the main monitor.
  14746. @see getMouseDownScreenPosition
  14747. */
  14748. const Point<int> getScreenPosition() const;
  14749. /** Returns the x co-ordinate at which the mouse button was last pressed.
  14750. The co-ordinates are relative to the top-left of the main monitor.
  14751. @see getMouseDownScreenPosition
  14752. */
  14753. int getMouseDownScreenX() const;
  14754. /** Returns the y co-ordinate at which the mouse button was last pressed.
  14755. The co-ordinates are relative to the top-left of the main monitor.
  14756. @see getMouseDownScreenPosition
  14757. */
  14758. int getMouseDownScreenY() const;
  14759. /** Returns the co-ordinates at which the mouse button was last pressed.
  14760. The co-ordinates are relative to the top-left of the main monitor.
  14761. @see getScreenPosition
  14762. */
  14763. const Point<int> getMouseDownScreenPosition() const;
  14764. /** Creates a version of this event that is relative to a different component.
  14765. The x and y positions of the event that is returned will have been
  14766. adjusted to be relative to the new component.
  14767. */
  14768. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  14769. /** Creates a copy of this event with a different position.
  14770. All other members of the event object are the same, but the x and y are
  14771. replaced with these new values.
  14772. */
  14773. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  14774. /** Changes the application-wide setting for the double-click time limit.
  14775. This is the maximum length of time between mouse-clicks for it to be
  14776. considered a double-click. It's used by the Component class.
  14777. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  14778. */
  14779. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  14780. /** Returns the application-wide setting for the double-click time limit.
  14781. This is the maximum length of time between mouse-clicks for it to be
  14782. considered a double-click. It's used by the Component class.
  14783. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  14784. */
  14785. static int getDoubleClickTimeout() throw();
  14786. juce_UseDebuggingNewOperator
  14787. private:
  14788. const Point<int> mouseDownPos;
  14789. const Time mouseDownTime;
  14790. const int numberOfClicks;
  14791. const bool wasMovedSinceMouseDown;
  14792. static int doubleClickTimeOutMs;
  14793. MouseEvent& operator= (const MouseEvent&);
  14794. };
  14795. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  14796. /*** End of inlined file: juce_MouseEvent.h ***/
  14797. /*** Start of inlined file: juce_ComponentListener.h ***/
  14798. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14799. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14800. class Component;
  14801. /**
  14802. Gets informed about changes to a component's hierarchy or position.
  14803. To monitor a component for changes, register a subclass of ComponentListener
  14804. with the component using Component::addComponentListener().
  14805. Be sure to deregister listeners before you delete them!
  14806. @see Component::addComponentListener, Component::removeComponentListener
  14807. */
  14808. class JUCE_API ComponentListener
  14809. {
  14810. public:
  14811. /** Destructor. */
  14812. virtual ~ComponentListener() {}
  14813. /** Called when the component's position or size changes.
  14814. @param component the component that was moved or resized
  14815. @param wasMoved true if the component's top-left corner has just moved
  14816. @param wasResized true if the component's width or height has just changed
  14817. @see Component::setBounds, Component::resized, Component::moved
  14818. */
  14819. virtual void componentMovedOrResized (Component& component,
  14820. bool wasMoved,
  14821. bool wasResized);
  14822. /** Called when the component is brought to the top of the z-order.
  14823. @param component the component that was moved
  14824. @see Component::toFront, Component::broughtToFront
  14825. */
  14826. virtual void componentBroughtToFront (Component& component);
  14827. /** Called when the component is made visible or invisible.
  14828. @param component the component that changed
  14829. @see Component::setVisible
  14830. */
  14831. virtual void componentVisibilityChanged (Component& component);
  14832. /** Called when the component has children added or removed.
  14833. @param component the component whose children were changed
  14834. @see Component::childrenChanged, Component::addChildComponent,
  14835. Component::removeChildComponent
  14836. */
  14837. virtual void componentChildrenChanged (Component& component);
  14838. /** Called to indicate that the component's parents have changed.
  14839. When a component is added or removed from its parent, all of its children
  14840. will produce this notification (recursively - so all children of its
  14841. children will also be called as well).
  14842. @param component the component that this listener is registered with
  14843. @see Component::parentHierarchyChanged
  14844. */
  14845. virtual void componentParentHierarchyChanged (Component& component);
  14846. /** Called when the component's name is changed.
  14847. @see Component::setName, Component::getName
  14848. */
  14849. virtual void componentNameChanged (Component& component);
  14850. /** Called when the component is in the process of being deleted.
  14851. This callback is made from inside the destructor, so be very, very cautious
  14852. about what you do inside the callback.
  14853. It will be called before the component has been removed from its parent, and
  14854. before any child components have been removed.
  14855. */
  14856. virtual void componentBeingDeleted (Component& component);
  14857. };
  14858. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14859. /*** End of inlined file: juce_ComponentListener.h ***/
  14860. /*** Start of inlined file: juce_KeyListener.h ***/
  14861. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  14862. #define __JUCE_KEYLISTENER_JUCEHEADER__
  14863. /*** Start of inlined file: juce_KeyPress.h ***/
  14864. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  14865. #define __JUCE_KEYPRESS_JUCEHEADER__
  14866. /**
  14867. Represents a key press, including any modifier keys that are needed.
  14868. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  14869. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  14870. */
  14871. class JUCE_API KeyPress
  14872. {
  14873. public:
  14874. /** Creates an (invalid) KeyPress.
  14875. @see isValid
  14876. */
  14877. KeyPress() throw();
  14878. /** Creates a KeyPress for a key and some modifiers.
  14879. e.g.
  14880. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  14881. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  14882. @param keyCode a code that represents the key - this value must be
  14883. one of special constants listed in this class, or an
  14884. 8-bit character code such as a letter (case is ignored),
  14885. digit or a simple key like "," or ".". Note that this
  14886. isn't the same as the textCharacter parameter, so for example
  14887. a keyCode of 'a' and a shift-key modifier should have a
  14888. textCharacter value of 'A'.
  14889. @param modifiers the modifiers to associate with the keystroke
  14890. @param textCharacter the character that would be printed if someone typed
  14891. this keypress into a text editor. This value may be
  14892. null if the keypress is a non-printing character
  14893. @see getKeyCode, isKeyCode, getModifiers
  14894. */
  14895. KeyPress (int keyCode,
  14896. const ModifierKeys& modifiers,
  14897. juce_wchar textCharacter) throw();
  14898. /** Creates a keypress with a keyCode but no modifiers or text character.
  14899. */
  14900. KeyPress (int keyCode) throw();
  14901. /** Creates a copy of another KeyPress. */
  14902. KeyPress (const KeyPress& other) throw();
  14903. /** Copies this KeyPress from another one. */
  14904. KeyPress& operator= (const KeyPress& other) throw();
  14905. /** Compares two KeyPress objects. */
  14906. bool operator== (const KeyPress& other) const throw();
  14907. /** Compares two KeyPress objects. */
  14908. bool operator!= (const KeyPress& other) const throw();
  14909. /** Returns true if this is a valid KeyPress.
  14910. A null keypress can be created by the default constructor, in case it's
  14911. needed.
  14912. */
  14913. bool isValid() const throw() { return keyCode != 0; }
  14914. /** Returns the key code itself.
  14915. This will either be one of the special constants defined in this class,
  14916. or an 8-bit character code.
  14917. */
  14918. int getKeyCode() const throw() { return keyCode; }
  14919. /** Returns the key modifiers.
  14920. @see ModifierKeys
  14921. */
  14922. const ModifierKeys getModifiers() const throw() { return mods; }
  14923. /** Returns the character that is associated with this keypress.
  14924. This is the character that you'd expect to see printed if you press this
  14925. keypress in a text editor or similar component.
  14926. */
  14927. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  14928. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  14929. the modifiers.
  14930. The values for key codes can either be one of the special constants defined in
  14931. this class, or an 8-bit character code.
  14932. @see getKeyCode
  14933. */
  14934. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  14935. /** Converts a textual key description to a KeyPress.
  14936. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  14937. This isn't designed to cope with any kind of input, but should be given the
  14938. strings that are created by the getTextDescription() method.
  14939. If the string can't be parsed, the object returned will be invalid.
  14940. @see getTextDescription
  14941. */
  14942. static const KeyPress createFromDescription (const String& textVersion);
  14943. /** Creates a textual description of the key combination.
  14944. e.g. "CTRL + C" or "DELETE".
  14945. To store a keypress in a file, use this method, along with createFromDescription()
  14946. to retrieve it later.
  14947. */
  14948. const String getTextDescription() const;
  14949. /** Checks whether the user is currently holding down the keys that make up this
  14950. KeyPress.
  14951. Note that this will return false if any extra modifier keys are
  14952. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  14953. then it will be false.
  14954. */
  14955. bool isCurrentlyDown() const;
  14956. /** Checks whether a particular key is held down, irrespective of modifiers.
  14957. The values for key codes can either be one of the special constants defined in
  14958. this class, or an 8-bit character code.
  14959. */
  14960. static bool isKeyCurrentlyDown (int keyCode);
  14961. // Key codes
  14962. //
  14963. // Note that the actual values of these are platform-specific and may change
  14964. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  14965. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  14966. //
  14967. static const int spaceKey; /**< key-code for the space bar */
  14968. static const int escapeKey; /**< key-code for the escape key */
  14969. static const int returnKey; /**< key-code for the return key*/
  14970. static const int tabKey; /**< key-code for the tab key*/
  14971. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  14972. static const int backspaceKey; /**< key-code for the backspace key */
  14973. static const int insertKey; /**< key-code for the insert key */
  14974. static const int upKey; /**< key-code for the cursor-up key */
  14975. static const int downKey; /**< key-code for the cursor-down key */
  14976. static const int leftKey; /**< key-code for the cursor-left key */
  14977. static const int rightKey; /**< key-code for the cursor-right key */
  14978. static const int pageUpKey; /**< key-code for the page-up key */
  14979. static const int pageDownKey; /**< key-code for the page-down key */
  14980. static const int homeKey; /**< key-code for the home key */
  14981. static const int endKey; /**< key-code for the end key */
  14982. static const int F1Key; /**< key-code for the F1 key */
  14983. static const int F2Key; /**< key-code for the F2 key */
  14984. static const int F3Key; /**< key-code for the F3 key */
  14985. static const int F4Key; /**< key-code for the F4 key */
  14986. static const int F5Key; /**< key-code for the F5 key */
  14987. static const int F6Key; /**< key-code for the F6 key */
  14988. static const int F7Key; /**< key-code for the F7 key */
  14989. static const int F8Key; /**< key-code for the F8 key */
  14990. static const int F9Key; /**< key-code for the F9 key */
  14991. static const int F10Key; /**< key-code for the F10 key */
  14992. static const int F11Key; /**< key-code for the F11 key */
  14993. static const int F12Key; /**< key-code for the F12 key */
  14994. static const int F13Key; /**< key-code for the F13 key */
  14995. static const int F14Key; /**< key-code for the F14 key */
  14996. static const int F15Key; /**< key-code for the F15 key */
  14997. static const int F16Key; /**< key-code for the F16 key */
  14998. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  14999. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  15000. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  15001. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  15002. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  15003. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  15004. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  15005. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  15006. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  15007. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  15008. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  15009. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  15010. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  15011. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  15012. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  15013. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  15014. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  15015. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  15016. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  15017. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  15018. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  15019. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  15020. juce_UseDebuggingNewOperator
  15021. private:
  15022. int keyCode;
  15023. ModifierKeys mods;
  15024. juce_wchar textCharacter;
  15025. };
  15026. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  15027. /*** End of inlined file: juce_KeyPress.h ***/
  15028. class Component;
  15029. /**
  15030. Receives callbacks when keys are pressed.
  15031. You can add a key listener to a component to be informed when that component
  15032. gets key events. See the Component::addListener method for more details.
  15033. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  15034. */
  15035. class JUCE_API KeyListener
  15036. {
  15037. public:
  15038. /** Destructor. */
  15039. virtual ~KeyListener() {}
  15040. /** Called to indicate that a key has been pressed.
  15041. If your implementation returns true, then the key event is considered to have
  15042. been consumed, and will not be passed on to any other components. If it returns
  15043. false, then the key will be passed to other components that might want to use it.
  15044. @param key the keystroke, including modifier keys
  15045. @param originatingComponent the component that received the key event
  15046. @see keyStateChanged, Component::keyPressed
  15047. */
  15048. virtual bool keyPressed (const KeyPress& key,
  15049. Component* originatingComponent) = 0;
  15050. /** Called when any key is pressed or released.
  15051. When this is called, classes that might be interested in
  15052. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  15053. check whether their key has changed.
  15054. If your implementation returns true, then the key event is considered to have
  15055. been consumed, and will not be passed on to any other components. If it returns
  15056. false, then the key will be passed to other components that might want to use it.
  15057. @param originatingComponent the component that received the key event
  15058. @param isKeyDown true if a key is being pressed, false if one is being released
  15059. @see KeyPress, Component::keyStateChanged
  15060. */
  15061. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  15062. };
  15063. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  15064. /*** End of inlined file: juce_KeyListener.h ***/
  15065. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  15066. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15067. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15068. class Component;
  15069. /**
  15070. Controls the order in which focus moves between components.
  15071. The default algorithm used by this class to work out the order of traversal
  15072. is as follows:
  15073. - if two components both have an explicit focus order specified, then the
  15074. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  15075. method).
  15076. - any component with an explicit focus order greater than 0 comes before ones
  15077. that don't have an order specified.
  15078. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  15079. order.
  15080. If you need traversal in a more customised way, you can create a subclass
  15081. of KeyboardFocusTraverser that uses your own algorithm, and use
  15082. Component::createFocusTraverser() to create it.
  15083. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  15084. */
  15085. class JUCE_API KeyboardFocusTraverser
  15086. {
  15087. public:
  15088. KeyboardFocusTraverser();
  15089. /** Destructor. */
  15090. virtual ~KeyboardFocusTraverser();
  15091. /** Returns the component that should be given focus after the specified one
  15092. when moving "forwards".
  15093. The default implementation will return the next component which is to the
  15094. right of or below this one.
  15095. This may return 0 if there's no suitable candidate.
  15096. */
  15097. virtual Component* getNextComponent (Component* current);
  15098. /** Returns the component that should be given focus after the specified one
  15099. when moving "backwards".
  15100. The default implementation will return the next component which is to the
  15101. left of or above this one.
  15102. This may return 0 if there's no suitable candidate.
  15103. */
  15104. virtual Component* getPreviousComponent (Component* current);
  15105. /** Returns the component that should receive focus be default within the given
  15106. parent component.
  15107. The default implementation will just return the foremost child component that
  15108. wants focus.
  15109. This may return 0 if there's no suitable candidate.
  15110. */
  15111. virtual Component* getDefaultComponent (Component* parentComponent);
  15112. };
  15113. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15114. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  15115. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  15116. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15117. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15118. /*** Start of inlined file: juce_Graphics.h ***/
  15119. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  15120. #define __JUCE_GRAPHICS_JUCEHEADER__
  15121. /*** Start of inlined file: juce_Font.h ***/
  15122. #ifndef __JUCE_FONT_JUCEHEADER__
  15123. #define __JUCE_FONT_JUCEHEADER__
  15124. /*** Start of inlined file: juce_Typeface.h ***/
  15125. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  15126. #define __JUCE_TYPEFACE_JUCEHEADER__
  15127. /*** Start of inlined file: juce_Path.h ***/
  15128. #ifndef __JUCE_PATH_JUCEHEADER__
  15129. #define __JUCE_PATH_JUCEHEADER__
  15130. /*** Start of inlined file: juce_Line.h ***/
  15131. #ifndef __JUCE_LINE_JUCEHEADER__
  15132. #define __JUCE_LINE_JUCEHEADER__
  15133. /**
  15134. Represents a line.
  15135. This class contains a bunch of useful methods for various geometric
  15136. tasks.
  15137. The ValueType template parameter should be a primitive type - float or double
  15138. are what it's designed for. Integer types will work in a basic way, but some methods
  15139. that perform mathematical operations may not compile, or they may not produce
  15140. sensible results.
  15141. @see Point, Rectangle, Path, Graphics::drawLine
  15142. */
  15143. template <typename ValueType>
  15144. class Line
  15145. {
  15146. public:
  15147. /** Creates a line, using (0, 0) as its start and end points. */
  15148. Line() throw() {}
  15149. /** Creates a copy of another line. */
  15150. Line (const Line& other) throw()
  15151. : start (other.start),
  15152. end (other.end)
  15153. {
  15154. }
  15155. /** Creates a line based on the co-ordinates of its start and end points. */
  15156. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  15157. : start (startX, startY),
  15158. end (endX, endY)
  15159. {
  15160. }
  15161. /** Creates a line from its start and end points. */
  15162. Line (const Point<ValueType>& startPoint,
  15163. const Point<ValueType>& endPoint) throw()
  15164. : start (startPoint),
  15165. end (endPoint)
  15166. {
  15167. }
  15168. /** Copies a line from another one. */
  15169. Line& operator= (const Line& other) throw()
  15170. {
  15171. start = other.start;
  15172. end = other.end;
  15173. return *this;
  15174. }
  15175. /** Destructor. */
  15176. ~Line() throw() {}
  15177. /** Returns the x co-ordinate of the line's start point. */
  15178. inline ValueType getStartX() const throw() { return start.getX(); }
  15179. /** Returns the y co-ordinate of the line's start point. */
  15180. inline ValueType getStartY() const throw() { return start.getY(); }
  15181. /** Returns the x co-ordinate of the line's end point. */
  15182. inline ValueType getEndX() const throw() { return end.getX(); }
  15183. /** Returns the y co-ordinate of the line's end point. */
  15184. inline ValueType getEndY() const throw() { return end.getY(); }
  15185. /** Returns the line's start point. */
  15186. inline const Point<ValueType>& getStart() const throw() { return start; }
  15187. /** Returns the line's end point. */
  15188. inline const Point<ValueType>& getEnd() const throw() { return end; }
  15189. /** Changes this line's start point */
  15190. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  15191. /** Changes this line's end point */
  15192. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  15193. /** Changes this line's start point */
  15194. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  15195. /** Changes this line's end point */
  15196. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  15197. /** Returns a line that is the same as this one, but with the start and end reversed, */
  15198. const Line reversed() const throw() { return Line (end, start); }
  15199. /** Applies an affine transform to the line's start and end points. */
  15200. void applyTransform (const AffineTransform& transform) throw()
  15201. {
  15202. start.applyTransform (transform);
  15203. end.applyTransform (transform);
  15204. }
  15205. /** Returns the length of the line. */
  15206. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  15207. /** Returns true if the line's start and end x co-ordinates are the same. */
  15208. bool isVertical() const throw() { return start.getX() == end.getX(); }
  15209. /** Returns true if the line's start and end y co-ordinates are the same. */
  15210. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  15211. /** Returns the line's angle.
  15212. This value is the number of radians clockwise from the 3 o'clock direction,
  15213. where the line's start point is considered to be at the centre.
  15214. */
  15215. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  15216. /** Compares two lines. */
  15217. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  15218. /** Compares two lines. */
  15219. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  15220. /** Finds the intersection between two lines.
  15221. @param line the other line
  15222. @param intersection the position of the point where the lines meet (or
  15223. where they would meet if they were infinitely long)
  15224. the intersection (if the lines intersect). If the lines
  15225. are parallel, this will just be set to the position
  15226. of one of the line's endpoints.
  15227. @returns true if the line segments intersect; false if they dont. Even if they
  15228. don't intersect, the intersection co-ordinates returned will still
  15229. be valid
  15230. */
  15231. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  15232. {
  15233. return findIntersection (start, end, line.start, line.end, intersection);
  15234. }
  15235. /** Finds the intersection between two lines.
  15236. @param line the line to intersect with
  15237. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  15238. */
  15239. const Point<ValueType> getIntersection (const Line& line) const throw()
  15240. {
  15241. Point<ValueType> p;
  15242. findIntersection (start, end, line.start, line.end, p);
  15243. return p;
  15244. }
  15245. /** Returns the location of the point which is a given distance along this line.
  15246. @param distanceFromStart the distance to move along the line from its
  15247. start point. This value can be negative or longer
  15248. than the line itself
  15249. @see getPointAlongLineProportionally
  15250. */
  15251. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  15252. {
  15253. return start + (end - start) * (distanceFromStart / getLength());
  15254. }
  15255. /** Returns a point which is a certain distance along and to the side of this line.
  15256. This effectively moves a given distance along the line, then another distance
  15257. perpendicularly to this, and returns the resulting position.
  15258. @param distanceFromStart the distance to move along the line from its
  15259. start point. This value can be negative or longer
  15260. than the line itself
  15261. @param perpendicularDistance how far to move sideways from the line. If you're
  15262. looking along the line from its start towards its
  15263. end, then a positive value here will move to the
  15264. right, negative value move to the left.
  15265. */
  15266. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  15267. ValueType perpendicularDistance) const throw()
  15268. {
  15269. const Point<ValueType> delta (end - start);
  15270. const double length = juce_hypot (delta.getX(), delta.getY());
  15271. if (length == 0)
  15272. return start;
  15273. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  15274. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  15275. }
  15276. /** Returns the location of the point which is a given distance along this line
  15277. proportional to the line's length.
  15278. @param proportionOfLength the distance to move along the line from its
  15279. start point, in multiples of the line's length.
  15280. So a value of 0.0 will return the line's start point
  15281. and a value of 1.0 will return its end point. (This value
  15282. can be negative or greater than 1.0).
  15283. @see getPointAlongLine
  15284. */
  15285. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  15286. {
  15287. return start + (end - start) * proportionOfLength;
  15288. }
  15289. /** Returns the smallest distance between this line segment and a given point.
  15290. So if the point is close to the line, this will return the perpendicular
  15291. distance from the line; if the point is a long way beyond one of the line's
  15292. end-point's, it'll return the straight-line distance to the nearest end-point.
  15293. pointOnLine receives the position of the point that is found.
  15294. @returns the point's distance from the line
  15295. @see getPositionAlongLineOfNearestPoint
  15296. */
  15297. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  15298. Point<ValueType>& pointOnLine) const throw()
  15299. {
  15300. const Point<ValueType> delta (end - start);
  15301. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15302. if (length > 0)
  15303. {
  15304. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  15305. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  15306. if (prop >= 0 && prop <= 1.0)
  15307. {
  15308. pointOnLine = start + delta * (ValueType) prop;
  15309. return targetPoint.getDistanceFrom (pointOnLine);
  15310. }
  15311. }
  15312. const float fromStart = targetPoint.getDistanceFrom (start);
  15313. const float fromEnd = targetPoint.getDistanceFrom (end);
  15314. if (fromStart < fromEnd)
  15315. {
  15316. pointOnLine = start;
  15317. return fromStart;
  15318. }
  15319. else
  15320. {
  15321. pointOnLine = end;
  15322. return fromEnd;
  15323. }
  15324. }
  15325. /** Finds the point on this line which is nearest to a given point, and
  15326. returns its position as a proportional position along the line.
  15327. @returns a value 0 to 1.0 which is the distance along this line from the
  15328. line's start to the point which is nearest to the point passed-in. To
  15329. turn this number into a position, use getPointAlongLineProportionally().
  15330. @see getDistanceFromPoint, getPointAlongLineProportionally
  15331. */
  15332. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  15333. {
  15334. const Point<ValueType> delta (end - start);
  15335. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15336. return length <= 0 ? 0
  15337. : jlimit ((ValueType) 0, (ValueType) 1,
  15338. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  15339. + (point.getY() - start.getY()) * delta.getY()) / length));
  15340. }
  15341. /** Finds the point on this line which is nearest to a given point.
  15342. @see getDistanceFromPoint, findNearestProportionalPositionTo
  15343. */
  15344. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  15345. {
  15346. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  15347. }
  15348. /** Returns true if the given point lies above this line.
  15349. The return value is true if the point's y coordinate is less than the y
  15350. coordinate of this line at the given x (assuming the line extends infinitely
  15351. in both directions).
  15352. */
  15353. bool isPointAbove (const Point<ValueType>& point) const throw()
  15354. {
  15355. return start.getX() != end.getX()
  15356. && point.getY() < ((end.getY() - start.getY())
  15357. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  15358. }
  15359. /** Returns a shortened copy of this line.
  15360. This will chop off part of the start of this line by a certain amount, (leaving the
  15361. end-point the same), and return the new line.
  15362. */
  15363. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  15364. {
  15365. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  15366. }
  15367. /** Returns a shortened copy of this line.
  15368. This will chop off part of the end of this line by a certain amount, (leaving the
  15369. start-point the same), and return the new line.
  15370. */
  15371. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  15372. {
  15373. const ValueType length = getLength();
  15374. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  15375. }
  15376. juce_UseDebuggingNewOperator
  15377. private:
  15378. Point<ValueType> start, end;
  15379. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  15380. const Point<ValueType>& p3, const Point<ValueType>& p4,
  15381. Point<ValueType>& intersection) throw()
  15382. {
  15383. if (p2 == p3)
  15384. {
  15385. intersection = p2;
  15386. return true;
  15387. }
  15388. const Point<ValueType> d1 (p2 - p1);
  15389. const Point<ValueType> d2 (p4 - p3);
  15390. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  15391. if (divisor == 0)
  15392. {
  15393. if (! (d1.isOrigin() || d2.isOrigin()))
  15394. {
  15395. if (d1.getY() == 0 && d2.getY() != 0)
  15396. {
  15397. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  15398. intersection = p1.withX (p3.getX() + along * d2.getX());
  15399. return along >= 0 && along <= (ValueType) 1;
  15400. }
  15401. else if (d2.getY() == 0 && d1.getY() != 0)
  15402. {
  15403. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  15404. intersection = p3.withX (p1.getX() + along * d1.getX());
  15405. return along >= 0 && along <= (ValueType) 1;
  15406. }
  15407. else if (d1.getX() == 0 && d2.getX() != 0)
  15408. {
  15409. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  15410. intersection = p1.withY (p3.getY() + along * d2.getY());
  15411. return along >= 0 && along <= (ValueType) 1;
  15412. }
  15413. else if (d2.getX() == 0 && d1.getX() != 0)
  15414. {
  15415. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  15416. intersection = p3.withY (p1.getY() + along * d1.getY());
  15417. return along >= 0 && along <= (ValueType) 1;
  15418. }
  15419. }
  15420. intersection = (p2 + p3) / (ValueType) 2;
  15421. return false;
  15422. }
  15423. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  15424. intersection = p1 + d1 * along1;
  15425. if (along1 < 0 || along1 > (ValueType) 1)
  15426. return false;
  15427. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  15428. return along2 >= 0 && along2 <= (ValueType) 1;
  15429. }
  15430. };
  15431. #endif // __JUCE_LINE_JUCEHEADER__
  15432. /*** End of inlined file: juce_Line.h ***/
  15433. /*** Start of inlined file: juce_Rectangle.h ***/
  15434. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  15435. #define __JUCE_RECTANGLE_JUCEHEADER__
  15436. class RectangleList;
  15437. /**
  15438. Manages a rectangle and allows geometric operations to be performed on it.
  15439. @see RectangleList, Path, Line, Point
  15440. */
  15441. template <typename ValueType>
  15442. class Rectangle
  15443. {
  15444. public:
  15445. /** Creates a rectangle of zero size.
  15446. The default co-ordinates will be (0, 0, 0, 0).
  15447. */
  15448. Rectangle() throw()
  15449. : x (0), y (0), w (0), h (0)
  15450. {
  15451. }
  15452. /** Creates a copy of another rectangle. */
  15453. Rectangle (const Rectangle& other) throw()
  15454. : x (other.x), y (other.y),
  15455. w (other.w), h (other.h)
  15456. {
  15457. }
  15458. /** Creates a rectangle with a given position and size. */
  15459. Rectangle (const ValueType initialX, const ValueType initialY,
  15460. const ValueType width, const ValueType height) throw()
  15461. : x (initialX), y (initialY),
  15462. w (width), h (height)
  15463. {
  15464. }
  15465. /** Creates a rectangle with a given size, and a position of (0, 0). */
  15466. Rectangle (const ValueType width, const ValueType height) throw()
  15467. : x (0), y (0), w (width), h (height)
  15468. {
  15469. }
  15470. /** Creates a Rectangle from the positions of two opposite corners. */
  15471. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  15472. : x (jmin (corner1.getX(), corner2.getX())),
  15473. y (jmin (corner1.getY(), corner2.getY())),
  15474. w (corner1.getX() - corner2.getX()),
  15475. h (corner1.getY() - corner2.getY())
  15476. {
  15477. if (w < 0) w = -w;
  15478. if (h < 0) h = -h;
  15479. }
  15480. Rectangle& operator= (const Rectangle& other) throw()
  15481. {
  15482. x = other.x; y = other.y;
  15483. w = other.w; h = other.h;
  15484. return *this;
  15485. }
  15486. /** Destructor. */
  15487. ~Rectangle() throw() {}
  15488. /** Returns true if the rectangle's width and height are both zero or less */
  15489. bool isEmpty() const throw() { return w <= 0 || h <= 0; }
  15490. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  15491. inline ValueType getX() const throw() { return x; }
  15492. /** Returns the y co-ordinate of the rectangle's top edge. */
  15493. inline ValueType getY() const throw() { return y; }
  15494. /** Returns the width of the rectangle. */
  15495. inline ValueType getWidth() const throw() { return w; }
  15496. /** Returns the height of the rectangle. */
  15497. inline ValueType getHeight() const throw() { return h; }
  15498. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  15499. inline ValueType getRight() const throw() { return x + w; }
  15500. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  15501. inline ValueType getBottom() const throw() { return y + h; }
  15502. /** Returns the x co-ordinate of the rectangle's centre. */
  15503. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  15504. /** Returns the y co-ordinate of the rectangle's centre. */
  15505. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  15506. /** Returns the centre point of the rectangle. */
  15507. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  15508. /** Returns the aspect ratio of the rectangle's width / height.
  15509. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  15510. it returns height / width. */
  15511. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  15512. /** Returns the rectangle's top-left position as a Point. */
  15513. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  15514. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15515. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  15516. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15517. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  15518. /** Returns a rectangle with the same size as this one, but a new position. */
  15519. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  15520. /** Returns the rectangle's top-left position as a Point. */
  15521. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  15522. /** Returns the rectangle's top-right position as a Point. */
  15523. const Point<ValueType> getTopRight() const throw() { return Point<float> (x + w, y); }
  15524. /** Returns the rectangle's bottom-left position as a Point. */
  15525. const Point<ValueType> getBottomLeft() const throw() { return Point<float> (x, y + h); }
  15526. /** Returns the rectangle's bottom-right position as a Point. */
  15527. const Point<ValueType> getBottomRight() const throw() { return Point<float> (x + w, y + h); }
  15528. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  15529. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  15530. /** Returns a rectangle with the same position as this one, but a new size. */
  15531. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  15532. /** Changes all the rectangle's co-ordinates. */
  15533. void setBounds (const ValueType newX, const ValueType newY,
  15534. const ValueType newWidth, const ValueType newHeight) throw()
  15535. {
  15536. x = newX; y = newY; w = newWidth; h = newHeight;
  15537. }
  15538. /** Changes the rectangle's width */
  15539. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  15540. /** Changes the rectangle's height */
  15541. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  15542. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  15543. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  15544. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  15545. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  15546. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  15547. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  15548. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  15549. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  15550. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  15551. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  15552. */
  15553. void setLeft (const ValueType newLeft) throw()
  15554. {
  15555. w = jmax (ValueType(), x + w - newLeft);
  15556. x = newLeft;
  15557. }
  15558. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  15559. If the y is moved to be below the current bottom edge, the height will be set to zero.
  15560. */
  15561. void setTop (const ValueType newTop) throw()
  15562. {
  15563. h = jmax (ValueType(), y + h - newTop);
  15564. y = newTop;
  15565. }
  15566. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  15567. If the new right is below the current X value, the X will be pushed down to match it.
  15568. @see getRight
  15569. */
  15570. void setRight (const ValueType newRight) throw()
  15571. {
  15572. x = jmin (x, newRight);
  15573. w = newRight - x;
  15574. }
  15575. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  15576. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  15577. @see getBottom
  15578. */
  15579. void setBottom (const ValueType newBottom) throw()
  15580. {
  15581. y = jmin (y, newBottom);
  15582. h = newBottom - y;
  15583. }
  15584. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  15585. void translate (const ValueType deltaX,
  15586. const ValueType deltaY) throw()
  15587. {
  15588. x += deltaX;
  15589. y += deltaY;
  15590. }
  15591. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15592. const Rectangle translated (const ValueType deltaX,
  15593. const ValueType deltaY) const throw()
  15594. {
  15595. return Rectangle (x + deltaX, y + deltaY, w, h);
  15596. }
  15597. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15598. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  15599. {
  15600. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  15601. }
  15602. /** Moves this rectangle by a given amount. */
  15603. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  15604. {
  15605. x += deltaPosition.getX(); y += deltaPosition.getY();
  15606. return *this;
  15607. }
  15608. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15609. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  15610. {
  15611. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  15612. }
  15613. /** Moves this rectangle by a given amount. */
  15614. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  15615. {
  15616. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  15617. return *this;
  15618. }
  15619. /** Expands the rectangle by a given amount.
  15620. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15621. @see expanded, reduce, reduced
  15622. */
  15623. void expand (const ValueType deltaX,
  15624. const ValueType deltaY) throw()
  15625. {
  15626. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15627. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15628. setBounds (x - deltaX, y - deltaY, nw, nh);
  15629. }
  15630. /** Returns a rectangle that is larger than this one by a given amount.
  15631. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15632. @see expand, reduce, reduced
  15633. */
  15634. const Rectangle expanded (const ValueType deltaX,
  15635. const ValueType deltaY) const throw()
  15636. {
  15637. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15638. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15639. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  15640. }
  15641. /** Shrinks the rectangle by a given amount.
  15642. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15643. @see reduced, expand, expanded
  15644. */
  15645. void reduce (const ValueType deltaX,
  15646. const ValueType deltaY) throw()
  15647. {
  15648. expand (-deltaX, -deltaY);
  15649. }
  15650. /** Returns a rectangle that is smaller than this one by a given amount.
  15651. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15652. @see reduce, expand, expanded
  15653. */
  15654. const Rectangle reduced (const ValueType deltaX,
  15655. const ValueType deltaY) const throw()
  15656. {
  15657. return expanded (-deltaX, -deltaY);
  15658. }
  15659. /** Removes a strip from the top of this rectangle, reducing this rectangle
  15660. by the specified amount and returning the section that was removed.
  15661. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15662. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  15663. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  15664. that value.
  15665. */
  15666. const Rectangle removeFromTop (const ValueType amountToRemove) throw()
  15667. {
  15668. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  15669. y += r.h; h -= r.h;
  15670. return r;
  15671. }
  15672. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  15673. by the specified amount and returning the section that was removed.
  15674. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15675. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  15676. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  15677. that value.
  15678. */
  15679. const Rectangle removeFromLeft (const ValueType amountToRemove) throw()
  15680. {
  15681. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  15682. x += r.w; w -= r.w;
  15683. return r;
  15684. }
  15685. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  15686. by the specified amount and returning the section that was removed.
  15687. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15688. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  15689. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  15690. that value.
  15691. */
  15692. const Rectangle removeFromRight (ValueType amountToRemove) throw()
  15693. {
  15694. amountToRemove = jmin (amountToRemove, w);
  15695. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  15696. w -= amountToRemove;
  15697. return r;
  15698. }
  15699. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  15700. by the specified amount and returning the section that was removed.
  15701. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15702. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  15703. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  15704. that value.
  15705. */
  15706. const Rectangle removeFromBottom (ValueType amountToRemove) throw()
  15707. {
  15708. amountToRemove = jmin (amountToRemove, h);
  15709. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  15710. h -= amountToRemove;
  15711. return r;
  15712. }
  15713. /** Returns true if the two rectangles are identical. */
  15714. bool operator== (const Rectangle& other) const throw()
  15715. {
  15716. return x == other.x && y == other.y
  15717. && w == other.w && h == other.h;
  15718. }
  15719. /** Returns true if the two rectangles are not identical. */
  15720. bool operator!= (const Rectangle& other) const throw()
  15721. {
  15722. return x != other.x || y != other.y
  15723. || w != other.w || h != other.h;
  15724. }
  15725. /** Returns true if this co-ordinate is inside the rectangle. */
  15726. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  15727. {
  15728. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  15729. }
  15730. /** Returns true if this co-ordinate is inside the rectangle. */
  15731. bool contains (const Point<ValueType>& point) const throw()
  15732. {
  15733. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  15734. }
  15735. /** Returns true if this other rectangle is completely inside this one. */
  15736. bool contains (const Rectangle& other) const throw()
  15737. {
  15738. return x <= other.x && y <= other.y
  15739. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  15740. }
  15741. /** Returns the nearest point to the specified point that lies within this rectangle. */
  15742. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  15743. {
  15744. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  15745. jlimit (y, y + h, point.getY()));
  15746. }
  15747. /** Returns true if any part of another rectangle overlaps this one. */
  15748. bool intersects (const Rectangle& other) const throw()
  15749. {
  15750. return x + w > other.x
  15751. && y + h > other.y
  15752. && x < other.x + other.w
  15753. && y < other.y + other.h
  15754. && w > ValueType() && h > ValueType();
  15755. }
  15756. /** Returns the region that is the overlap between this and another rectangle.
  15757. If the two rectangles don't overlap, the rectangle returned will be empty.
  15758. */
  15759. const Rectangle getIntersection (const Rectangle& other) const throw()
  15760. {
  15761. const ValueType nx = jmax (x, other.x);
  15762. const ValueType ny = jmax (y, other.y);
  15763. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  15764. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  15765. if (nw >= ValueType() && nh >= ValueType())
  15766. return Rectangle (nx, ny, nw, nh);
  15767. return Rectangle();
  15768. }
  15769. /** Clips a rectangle so that it lies only within this one.
  15770. This is a non-static version of intersectRectangles().
  15771. Returns false if the two regions didn't overlap.
  15772. */
  15773. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  15774. {
  15775. const int maxX = jmax (otherX, x);
  15776. otherW = jmin (otherX + otherW, x + w) - maxX;
  15777. if (otherW > 0)
  15778. {
  15779. const int maxY = jmax (otherY, y);
  15780. otherH = jmin (otherY + otherH, y + h) - maxY;
  15781. if (otherH > 0)
  15782. {
  15783. otherX = maxX; otherY = maxY;
  15784. return true;
  15785. }
  15786. }
  15787. return false;
  15788. }
  15789. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  15790. If either this or the other rectangle are empty, they will not be counted as
  15791. part of the resulting region.
  15792. */
  15793. const Rectangle getUnion (const Rectangle& other) const throw()
  15794. {
  15795. if (other.isEmpty()) return *this;
  15796. if (isEmpty()) return other;
  15797. const ValueType newX = jmin (x, other.x);
  15798. const ValueType newY = jmin (y, other.y);
  15799. return Rectangle (newX, newY,
  15800. jmax (x + w, other.x + other.w) - newX,
  15801. jmax (y + h, other.y + other.h) - newY);
  15802. }
  15803. /** If this rectangle merged with another one results in a simple rectangle, this
  15804. will set this rectangle to the result, and return true.
  15805. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15806. or if they form a complex region.
  15807. */
  15808. bool enlargeIfAdjacent (const Rectangle& other) throw()
  15809. {
  15810. if (x == other.x && getRight() == other.getRight()
  15811. && (other.getBottom() >= y && other.y <= getBottom()))
  15812. {
  15813. const ValueType newY = jmin (y, other.y);
  15814. h = jmax (getBottom(), other.getBottom()) - newY;
  15815. y = newY;
  15816. return true;
  15817. }
  15818. else if (y == other.y && getBottom() == other.getBottom()
  15819. && (other.getRight() >= x && other.x <= getRight()))
  15820. {
  15821. const ValueType newX = jmin (x, other.x);
  15822. w = jmax (getRight(), other.getRight()) - newX;
  15823. x = newX;
  15824. return true;
  15825. }
  15826. return false;
  15827. }
  15828. /** If after removing another rectangle from this one the result is a simple rectangle,
  15829. this will set this object's bounds to be the result, and return true.
  15830. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15831. or if removing the other one would form a complex region.
  15832. */
  15833. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  15834. {
  15835. int inside = 0;
  15836. const int otherR = other.getRight();
  15837. if (x >= other.x && x < otherR) inside = 1;
  15838. const int otherB = other.getBottom();
  15839. if (y >= other.y && y < otherB) inside |= 2;
  15840. const int r = x + w;
  15841. if (r >= other.x && r < otherR) inside |= 4;
  15842. const int b = y + h;
  15843. if (b >= other.y && b < otherB) inside |= 8;
  15844. switch (inside)
  15845. {
  15846. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  15847. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  15848. case 2 + 4 + 8: w = other.x - x; return true;
  15849. case 1 + 4 + 8: h = other.y - y; return true;
  15850. }
  15851. return false;
  15852. }
  15853. /** Returns the smallest rectangle that can contain the shape created by applying
  15854. a transform to this rectangle.
  15855. This should only be used on floating point rectangles.
  15856. */
  15857. const Rectangle<ValueType> transformed (const AffineTransform& transform) const throw()
  15858. {
  15859. float x1 = x, y1 = y;
  15860. float x2 = x + w, y2 = y;
  15861. float x3 = x, y3 = y + h;
  15862. float x4 = x2, y4 = y3;
  15863. transform.transformPoints (x1, y1, x2, y2);
  15864. transform.transformPoints (x3, y3, x4, y4);
  15865. const float rx = jmin (x1, x2, x3, x4);
  15866. const float ry = jmin (y1, y2, y3, y4);
  15867. return Rectangle (rx, ry,
  15868. jmax (x1, x2, x3, x4) - rx,
  15869. jmax (y1, y2, y3, y4) - ry);
  15870. }
  15871. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  15872. This is only relevent for floating-point rectangles, of course.
  15873. @see toFloat()
  15874. */
  15875. const Rectangle<int> getSmallestIntegerContainer() const throw()
  15876. {
  15877. const int x1 = (int) std::floor (static_cast<float> (x));
  15878. const int y1 = (int) std::floor (static_cast<float> (y));
  15879. const int x2 = (int) std::floor (static_cast<float> (x + w + 0.9999f));
  15880. const int y2 = (int) std::floor (static_cast<float> (y + h + 0.9999f));
  15881. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  15882. }
  15883. /** Returns the smallest Rectangle that can contain a set of points. */
  15884. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  15885. {
  15886. if (numPoints == 0)
  15887. return Rectangle();
  15888. ValueType minX (points[0].getX());
  15889. ValueType maxX (minX);
  15890. ValueType minY (points[0].getY());
  15891. ValueType maxY (minY);
  15892. for (int i = 1; i < numPoints; ++i)
  15893. {
  15894. minX = jmin (minX, points[i].getX());
  15895. maxX = jmax (maxX, points[i].getX());
  15896. minY = jmin (minY, points[i].getY());
  15897. maxY = jmax (maxY, points[i].getY());
  15898. }
  15899. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  15900. }
  15901. /** Casts this rectangle to a Rectangle<float>.
  15902. Obviously this is mainly useful for rectangles that use integer types.
  15903. @see getSmallestIntegerContainer
  15904. */
  15905. const Rectangle<float> toFloat() const throw()
  15906. {
  15907. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  15908. static_cast<float> (w), static_cast<float> (h));
  15909. }
  15910. /** Static utility to intersect two sets of rectangular co-ordinates.
  15911. Returns false if the two regions didn't overlap.
  15912. @see intersectRectangle
  15913. */
  15914. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  15915. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  15916. {
  15917. const ValueType x = jmax (x1, x2);
  15918. w1 = jmin (x1 + w1, x2 + w2) - x;
  15919. if (w1 > 0)
  15920. {
  15921. const ValueType y = jmax (y1, y2);
  15922. h1 = jmin (y1 + h1, y2 + h2) - y;
  15923. if (h1 > 0)
  15924. {
  15925. x1 = x; y1 = y;
  15926. return true;
  15927. }
  15928. }
  15929. return false;
  15930. }
  15931. /** Creates a string describing this rectangle.
  15932. The string will be of the form "x y width height", e.g. "100 100 400 200".
  15933. Coupled with the fromString() method, this is very handy for things like
  15934. storing rectangles (particularly component positions) in XML attributes.
  15935. @see fromString
  15936. */
  15937. const String toString() const
  15938. {
  15939. String s;
  15940. s.preallocateStorage (16);
  15941. s << x << ' ' << y << ' ' << w << ' ' << h;
  15942. return s;
  15943. }
  15944. /** Parses a string containing a rectangle's details.
  15945. The string should contain 4 integer tokens, in the form "x y width height". They
  15946. can be comma or whitespace separated.
  15947. This method is intended to go with the toString() method, to form an easy way
  15948. of saving/loading rectangles as strings.
  15949. @see toString
  15950. */
  15951. static const Rectangle fromString (const String& stringVersion)
  15952. {
  15953. StringArray toks;
  15954. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  15955. return Rectangle (toks[0].trim().getIntValue(),
  15956. toks[1].trim().getIntValue(),
  15957. toks[2].trim().getIntValue(),
  15958. toks[3].trim().getIntValue());
  15959. }
  15960. juce_UseDebuggingNewOperator
  15961. private:
  15962. friend class RectangleList;
  15963. ValueType x, y, w, h;
  15964. };
  15965. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  15966. /*** End of inlined file: juce_Rectangle.h ***/
  15967. /*** Start of inlined file: juce_Justification.h ***/
  15968. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  15969. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  15970. /**
  15971. Represents a type of justification to be used when positioning graphical items.
  15972. e.g. it indicates whether something should be placed top-left, top-right,
  15973. centred, etc.
  15974. It is used in various places wherever this kind of information is needed.
  15975. */
  15976. class JUCE_API Justification
  15977. {
  15978. public:
  15979. /** Creates a Justification object using a combination of flags. */
  15980. inline Justification (int flags_) throw() : flags (flags_) {}
  15981. /** Creates a copy of another Justification object. */
  15982. Justification (const Justification& other) throw();
  15983. /** Copies another Justification object. */
  15984. Justification& operator= (const Justification& other) throw();
  15985. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  15986. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  15987. /** Returns the raw flags that are set for this Justification object. */
  15988. inline int getFlags() const throw() { return flags; }
  15989. /** Tests a set of flags for this object.
  15990. @returns true if any of the flags passed in are set on this object.
  15991. */
  15992. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  15993. /** Returns just the flags from this object that deal with vertical layout. */
  15994. int getOnlyVerticalFlags() const throw();
  15995. /** Returns just the flags from this object that deal with horizontal layout. */
  15996. int getOnlyHorizontalFlags() const throw();
  15997. /** Adjusts the position of a rectangle to fit it into a space.
  15998. The (x, y) position of the rectangle will be updated to position it inside the
  15999. given space according to the justification flags.
  16000. */
  16001. void applyToRectangle (int& x, int& y, int w, int h,
  16002. int spaceX, int spaceY, int spaceW, int spaceH) const throw();
  16003. /** Flag values that can be combined and used in the constructor. */
  16004. enum
  16005. {
  16006. /** Indicates that the item should be aligned against the left edge of the available space. */
  16007. left = 1,
  16008. /** Indicates that the item should be aligned against the right edge of the available space. */
  16009. right = 2,
  16010. /** Indicates that the item should be placed in the centre between the left and right
  16011. sides of the available space. */
  16012. horizontallyCentred = 4,
  16013. /** Indicates that the item should be aligned against the top edge of the available space. */
  16014. top = 8,
  16015. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  16016. bottom = 16,
  16017. /** Indicates that the item should be placed in the centre between the top and bottom
  16018. sides of the available space. */
  16019. verticallyCentred = 32,
  16020. /** Indicates that lines of text should be spread out to fill the maximum width
  16021. available, so that both margins are aligned vertically.
  16022. */
  16023. horizontallyJustified = 64,
  16024. /** Indicates that the item should be centred vertically and horizontally.
  16025. This is equivalent to (horizontallyCentred | verticallyCentred)
  16026. */
  16027. centred = 36,
  16028. /** Indicates that the item should be centred vertically but placed on the left hand side.
  16029. This is equivalent to (left | verticallyCentred)
  16030. */
  16031. centredLeft = 33,
  16032. /** Indicates that the item should be centred vertically but placed on the right hand side.
  16033. This is equivalent to (right | verticallyCentred)
  16034. */
  16035. centredRight = 34,
  16036. /** Indicates that the item should be centred horizontally and placed at the top.
  16037. This is equivalent to (horizontallyCentred | top)
  16038. */
  16039. centredTop = 12,
  16040. /** Indicates that the item should be centred horizontally and placed at the bottom.
  16041. This is equivalent to (horizontallyCentred | bottom)
  16042. */
  16043. centredBottom = 20,
  16044. /** Indicates that the item should be placed in the top-left corner.
  16045. This is equivalent to (left | top)
  16046. */
  16047. topLeft = 9,
  16048. /** Indicates that the item should be placed in the top-right corner.
  16049. This is equivalent to (right | top)
  16050. */
  16051. topRight = 10,
  16052. /** Indicates that the item should be placed in the bottom-left corner.
  16053. This is equivalent to (left | bottom)
  16054. */
  16055. bottomLeft = 17,
  16056. /** Indicates that the item should be placed in the bottom-left corner.
  16057. This is equivalent to (right | bottom)
  16058. */
  16059. bottomRight = 18
  16060. };
  16061. private:
  16062. int flags;
  16063. };
  16064. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  16065. /*** End of inlined file: juce_Justification.h ***/
  16066. class Image;
  16067. /**
  16068. A path is a sequence of lines and curves that may either form a closed shape
  16069. or be open-ended.
  16070. To use a path, you can create an empty one, then add lines and curves to it
  16071. to create shapes, then it can be rendered by a Graphics context or used
  16072. for geometric operations.
  16073. e.g. @code
  16074. Path myPath;
  16075. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  16076. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  16077. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  16078. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  16079. // add an ellipse as well, which will form a second sub-path within the path..
  16080. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  16081. // double the width of the whole thing..
  16082. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  16083. // and draw it to a graphics context with a 5-pixel thick outline.
  16084. g.strokePath (myPath, PathStrokeType (5.0f));
  16085. @endcode
  16086. A path object can actually contain multiple sub-paths, which may themselves
  16087. be open or closed.
  16088. @see PathFlatteningIterator, PathStrokeType, Graphics
  16089. */
  16090. class JUCE_API Path
  16091. {
  16092. public:
  16093. /** Creates an empty path. */
  16094. Path();
  16095. /** Creates a copy of another path. */
  16096. Path (const Path& other);
  16097. /** Destructor. */
  16098. ~Path();
  16099. /** Copies this path from another one. */
  16100. Path& operator= (const Path& other);
  16101. bool operator== (const Path& other) const throw();
  16102. bool operator!= (const Path& other) const throw();
  16103. /** Returns true if the path doesn't contain any lines or curves. */
  16104. bool isEmpty() const throw();
  16105. /** Returns the smallest rectangle that contains all points within the path.
  16106. */
  16107. const Rectangle<float> getBounds() const throw();
  16108. /** Returns the smallest rectangle that contains all points within the path
  16109. after it's been transformed with the given tranasform matrix.
  16110. */
  16111. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  16112. /** Checks whether a point lies within the path.
  16113. This is only relevent for closed paths (see closeSubPath()), and
  16114. may produce false results if used on a path which has open sub-paths.
  16115. The path's winding rule is taken into account by this method.
  16116. The tolerence parameter is passed to the PathFlatteningIterator that
  16117. is used to trace the path - for more info about it, see the notes for
  16118. the PathFlatteningIterator constructor.
  16119. @see closeSubPath, setUsingNonZeroWinding
  16120. */
  16121. bool contains (float x, float y,
  16122. float tolerence = 10.0f) const;
  16123. /** Checks whether a point lies within the path.
  16124. This is only relevent for closed paths (see closeSubPath()), and
  16125. may produce false results if used on a path which has open sub-paths.
  16126. The path's winding rule is taken into account by this method.
  16127. The tolerence parameter is passed to the PathFlatteningIterator that
  16128. is used to trace the path - for more info about it, see the notes for
  16129. the PathFlatteningIterator constructor.
  16130. @see closeSubPath, setUsingNonZeroWinding
  16131. */
  16132. bool contains (const Point<float>& point,
  16133. float tolerence = 10.0f) const;
  16134. /** Checks whether a line crosses the path.
  16135. This will return positive if the line crosses any of the paths constituent
  16136. lines or curves. It doesn't take into account whether the line is inside
  16137. or outside the path, or whether the path is open or closed.
  16138. The tolerence parameter is passed to the PathFlatteningIterator that
  16139. is used to trace the path - for more info about it, see the notes for
  16140. the PathFlatteningIterator constructor.
  16141. */
  16142. bool intersectsLine (const Line<float>& line,
  16143. float tolerence = 10.0f);
  16144. /** Cuts off parts of a line to keep the parts that are either inside or
  16145. outside this path.
  16146. Note that this isn't smart enough to cope with situations where the
  16147. line would need to be cut into multiple pieces to correctly clip against
  16148. a re-entrant shape.
  16149. @param line the line to clip
  16150. @param keepSectionOutsidePath if true, it's the section outside the path
  16151. that will be kept; if false its the section inside
  16152. the path
  16153. */
  16154. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  16155. /** Returns the length of the path.
  16156. @see getPointAlongPath
  16157. */
  16158. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  16159. /** Returns a point that is the specified distance along the path.
  16160. If the distance is greater than the total length of the path, this will return the
  16161. end point.
  16162. @see getLength
  16163. */
  16164. const Point<float> getPointAlongPath (float distanceFromStart,
  16165. const AffineTransform& transform = AffineTransform::identity) const;
  16166. /** Finds the point along the path which is nearest to a given position.
  16167. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  16168. of the path.
  16169. */
  16170. float getNearestPoint (const Point<float>& targetPoint,
  16171. Point<float>& pointOnPath,
  16172. const AffineTransform& transform = AffineTransform::identity) const;
  16173. /** Removes all lines and curves, resetting the path completely. */
  16174. void clear() throw();
  16175. /** Begins a new subpath with a given starting position.
  16176. This will move the path's current position to the co-ordinates passed in and
  16177. make it ready to draw lines or curves starting from this position.
  16178. After adding whatever lines and curves are needed, you can either
  16179. close the current sub-path using closeSubPath() or call startNewSubPath()
  16180. to move to a new sub-path, leaving the old one open-ended.
  16181. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16182. */
  16183. void startNewSubPath (float startX, float startY);
  16184. /** Begins a new subpath with a given starting position.
  16185. This will move the path's current position to the co-ordinates passed in and
  16186. make it ready to draw lines or curves starting from this position.
  16187. After adding whatever lines and curves are needed, you can either
  16188. close the current sub-path using closeSubPath() or call startNewSubPath()
  16189. to move to a new sub-path, leaving the old one open-ended.
  16190. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16191. */
  16192. void startNewSubPath (const Point<float>& start);
  16193. /** Closes a the current sub-path with a line back to its start-point.
  16194. When creating a closed shape such as a triangle, don't use 3 lineTo()
  16195. calls - instead use two lineTo() calls, followed by a closeSubPath()
  16196. to join the final point back to the start.
  16197. This ensures that closes shapes are recognised as such, and this is
  16198. important for tasks like drawing strokes, which needs to know whether to
  16199. draw end-caps or not.
  16200. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  16201. */
  16202. void closeSubPath();
  16203. /** Adds a line from the shape's last position to a new end-point.
  16204. This will connect the end-point of the last line or curve that was added
  16205. to a new point, using a straight line.
  16206. See the class description for an example of how to add lines and curves to a path.
  16207. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16208. */
  16209. void lineTo (float endX, float endY);
  16210. /** Adds a line from the shape's last position to a new end-point.
  16211. This will connect the end-point of the last line or curve that was added
  16212. to a new point, using a straight line.
  16213. See the class description for an example of how to add lines and curves to a path.
  16214. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16215. */
  16216. void lineTo (const Point<float>& end);
  16217. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16218. This will connect the end-point of the last line or curve that was added
  16219. to a new point, using a quadratic spline with one control-point.
  16220. See the class description for an example of how to add lines and curves to a path.
  16221. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16222. */
  16223. void quadraticTo (float controlPointX,
  16224. float controlPointY,
  16225. float endPointX,
  16226. float endPointY);
  16227. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16228. This will connect the end-point of the last line or curve that was added
  16229. to a new point, using a quadratic spline with one control-point.
  16230. See the class description for an example of how to add lines and curves to a path.
  16231. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16232. */
  16233. void quadraticTo (const Point<float>& controlPoint,
  16234. const Point<float>& endPoint);
  16235. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16236. This will connect the end-point of the last line or curve that was added
  16237. to a new point, using a cubic spline with two control-points.
  16238. See the class description for an example of how to add lines and curves to a path.
  16239. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16240. */
  16241. void cubicTo (float controlPoint1X,
  16242. float controlPoint1Y,
  16243. float controlPoint2X,
  16244. float controlPoint2Y,
  16245. float endPointX,
  16246. float endPointY);
  16247. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16248. This will connect the end-point of the last line or curve that was added
  16249. to a new point, using a cubic spline with two control-points.
  16250. See the class description for an example of how to add lines and curves to a path.
  16251. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16252. */
  16253. void cubicTo (const Point<float>& controlPoint1,
  16254. const Point<float>& controlPoint2,
  16255. const Point<float>& endPoint);
  16256. /** Returns the last point that was added to the path by one of the drawing methods.
  16257. */
  16258. const Point<float> getCurrentPosition() const;
  16259. /** Adds a rectangle to the path.
  16260. The rectangle is added as a new sub-path. (Any currently open paths will be
  16261. left open).
  16262. @see addRoundedRectangle, addTriangle
  16263. */
  16264. void addRectangle (float x, float y, float width, float height);
  16265. /** Adds a rectangle to the path.
  16266. The rectangle is added as a new sub-path. (Any currently open paths will be
  16267. left open).
  16268. @see addRoundedRectangle, addTriangle
  16269. */
  16270. void addRectangle (const Rectangle<int>& rectangle);
  16271. /** Adds a rectangle with rounded corners to the path.
  16272. The rectangle is added as a new sub-path. (Any currently open paths will be
  16273. left open).
  16274. @see addRectangle, addTriangle
  16275. */
  16276. void addRoundedRectangle (float x, float y, float width, float height,
  16277. float cornerSize);
  16278. /** Adds a rectangle with rounded corners to the path.
  16279. The rectangle is added as a new sub-path. (Any currently open paths will be
  16280. left open).
  16281. @see addRectangle, addTriangle
  16282. */
  16283. void addRoundedRectangle (float x, float y, float width, float height,
  16284. float cornerSizeX,
  16285. float cornerSizeY);
  16286. /** Adds a triangle to the path.
  16287. The triangle is added as a new closed sub-path. (Any currently open paths will be
  16288. left open).
  16289. Note that whether the vertices are specified in clockwise or anticlockwise
  16290. order will affect how the triangle is filled when it overlaps other
  16291. shapes (the winding order setting will affect this of course).
  16292. */
  16293. void addTriangle (float x1, float y1,
  16294. float x2, float y2,
  16295. float x3, float y3);
  16296. /** Adds a quadrilateral to the path.
  16297. The quad is added as a new closed sub-path. (Any currently open paths will be
  16298. left open).
  16299. Note that whether the vertices are specified in clockwise or anticlockwise
  16300. order will affect how the quad is filled when it overlaps other
  16301. shapes (the winding order setting will affect this of course).
  16302. */
  16303. void addQuadrilateral (float x1, float y1,
  16304. float x2, float y2,
  16305. float x3, float y3,
  16306. float x4, float y4);
  16307. /** Adds an ellipse to the path.
  16308. The shape is added as a new sub-path. (Any currently open paths will be
  16309. left open).
  16310. @see addArc
  16311. */
  16312. void addEllipse (float x, float y, float width, float height);
  16313. /** Adds an elliptical arc to the current path.
  16314. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16315. or anti-clockwise according to whether the end angle is greater than the start. This means
  16316. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16317. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16318. @param y the top edge of the rectangle in which the elliptical outline fits
  16319. @param width the width of the rectangle in which the elliptical outline fits
  16320. @param height the height of the rectangle in which the elliptical outline fits
  16321. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16322. top-centre of the ellipse)
  16323. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16324. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16325. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16326. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16327. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16328. it will be added to the current sub-path, continuing from the current postition
  16329. @see addCentredArc, arcTo, addPieSegment, addEllipse
  16330. */
  16331. void addArc (float x, float y, float width, float height,
  16332. float fromRadians,
  16333. float toRadians,
  16334. bool startAsNewSubPath = false);
  16335. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  16336. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16337. or anti-clockwise according to whether the end angle is greater than the start. This means
  16338. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16339. @param centreX the centre x of the ellipse
  16340. @param centreY the centre y of the ellipse
  16341. @param radiusX the horizontal radius of the ellipse
  16342. @param radiusY the vertical radius of the ellipse
  16343. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  16344. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16345. top-centre of the ellipse)
  16346. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16347. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16348. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16349. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16350. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16351. it will be added to the current sub-path, continuing from the current postition
  16352. @see addArc, arcTo
  16353. */
  16354. void addCentredArc (float centreX, float centreY,
  16355. float radiusX, float radiusY,
  16356. float rotationOfEllipse,
  16357. float fromRadians,
  16358. float toRadians,
  16359. bool startAsNewSubPath = false);
  16360. /** Adds a "pie-chart" shape to the path.
  16361. The shape is added as a new sub-path. (Any currently open paths will be
  16362. left open).
  16363. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16364. or anti-clockwise according to whether the end angle is greater than the start. This means
  16365. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16366. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16367. @param y the top edge of the rectangle in which the elliptical outline fits
  16368. @param width the width of the rectangle in which the elliptical outline fits
  16369. @param height the height of the rectangle in which the elliptical outline fits
  16370. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16371. top-centre of the ellipse)
  16372. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16373. top-centre of the ellipse)
  16374. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  16375. ellipse at its centre, where this value indicates the inner ellipse's size with
  16376. respect to the outer one.
  16377. @see addArc
  16378. */
  16379. void addPieSegment (float x, float y,
  16380. float width, float height,
  16381. float fromRadians,
  16382. float toRadians,
  16383. float innerCircleProportionalSize);
  16384. /** Adds a line with a specified thickness.
  16385. The line is added as a new closed sub-path. (Any currently open paths will be
  16386. left open).
  16387. @see addArrow
  16388. */
  16389. void addLineSegment (const Line<float>& line, float lineThickness);
  16390. /** Adds a line with an arrowhead on the end.
  16391. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  16392. @see PathStrokeType::createStrokeWithArrowheads
  16393. */
  16394. void addArrow (const Line<float>& line,
  16395. float lineThickness,
  16396. float arrowheadWidth,
  16397. float arrowheadLength);
  16398. /** Adds a polygon shape to the path.
  16399. @see addStar
  16400. */
  16401. void addPolygon (const Point<float>& centre,
  16402. int numberOfSides,
  16403. float radius,
  16404. float startAngle = 0.0f);
  16405. /** Adds a star shape to the path.
  16406. @see addPolygon
  16407. */
  16408. void addStar (const Point<float>& centre,
  16409. int numberOfPoints,
  16410. float innerRadius,
  16411. float outerRadius,
  16412. float startAngle = 0.0f);
  16413. /** Adds a speech-bubble shape to the path.
  16414. @param bodyX the left of the main body area of the bubble
  16415. @param bodyY the top of the main body area of the bubble
  16416. @param bodyW the width of the main body area of the bubble
  16417. @param bodyH the height of the main body area of the bubble
  16418. @param cornerSize the amount by which to round off the corners of the main body rectangle
  16419. @param arrowTipX the x position that the tip of the arrow should connect to
  16420. @param arrowTipY the y position that the tip of the arrow should connect to
  16421. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  16422. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  16423. arrow's base should be - this is a proportional distance between 0 and 1.0
  16424. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  16425. */
  16426. void addBubble (float bodyX, float bodyY,
  16427. float bodyW, float bodyH,
  16428. float cornerSize,
  16429. float arrowTipX,
  16430. float arrowTipY,
  16431. int whichSide,
  16432. float arrowPositionAlongEdgeProportional,
  16433. float arrowWidth);
  16434. /** Adds another path to this one.
  16435. The new path is added as a new sub-path. (Any currently open paths in this
  16436. path will be left open).
  16437. @param pathToAppend the path to add
  16438. */
  16439. void addPath (const Path& pathToAppend);
  16440. /** Adds another path to this one, transforming it on the way in.
  16441. The new path is added as a new sub-path, its points being transformed by the given
  16442. matrix before being added.
  16443. @param pathToAppend the path to add
  16444. @param transformToApply an optional transform to apply to the incoming vertices
  16445. */
  16446. void addPath (const Path& pathToAppend,
  16447. const AffineTransform& transformToApply);
  16448. /** Swaps the contents of this path with another one.
  16449. The internal data of the two paths is swapped over, so this is much faster than
  16450. copying it to a temp variable and back.
  16451. */
  16452. void swapWithPath (Path& other) throw();
  16453. /** Applies a 2D transform to all the vertices in the path.
  16454. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  16455. */
  16456. void applyTransform (const AffineTransform& transform) throw();
  16457. /** Rescales this path to make it fit neatly into a given space.
  16458. This is effectively a quick way of calling
  16459. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  16460. @param x the x position of the rectangle to fit the path inside
  16461. @param y the y position of the rectangle to fit the path inside
  16462. @param width the width of the rectangle to fit the path inside
  16463. @param height the height of the rectangle to fit the path inside
  16464. @param preserveProportions if true, it will fit the path into the space without altering its
  16465. horizontal/vertical scale ratio; if false, it will distort the
  16466. path to fill the specified ratio both horizontally and vertically
  16467. @see applyTransform, getTransformToScaleToFit
  16468. */
  16469. void scaleToFit (float x, float y, float width, float height,
  16470. bool preserveProportions) throw();
  16471. /** Returns a transform that can be used to rescale the path to fit into a given space.
  16472. @param x the x position of the rectangle to fit the path inside
  16473. @param y the y position of the rectangle to fit the path inside
  16474. @param width the width of the rectangle to fit the path inside
  16475. @param height the height of the rectangle to fit the path inside
  16476. @param preserveProportions if true, it will fit the path into the space without altering its
  16477. horizontal/vertical scale ratio; if false, it will distort the
  16478. path to fill the specified ratio both horizontally and vertically
  16479. @param justificationType if the proportions are preseved, the resultant path may be smaller
  16480. than the available rectangle, so this describes how it should be
  16481. positioned within the space.
  16482. @returns an appropriate transformation
  16483. @see applyTransform, scaleToFit
  16484. */
  16485. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  16486. bool preserveProportions,
  16487. const Justification& justificationType = Justification::centred) const;
  16488. /** Creates a version of this path where all sharp corners have been replaced by curves.
  16489. Wherever two lines meet at an angle, this will replace the corner with a curve
  16490. of the given radius.
  16491. */
  16492. const Path createPathWithRoundedCorners (float cornerRadius) const;
  16493. /** Changes the winding-rule to be used when filling the path.
  16494. If set to true (which is the default), then the path uses a non-zero-winding rule
  16495. to determine which points are inside the path. If set to false, it uses an
  16496. alternate-winding rule.
  16497. The winding-rule comes into play when areas of the shape overlap other
  16498. areas, and determines whether the overlapping regions are considered to be
  16499. inside or outside.
  16500. Changing this value just sets a flag - it doesn't affect the contents of the
  16501. path.
  16502. @see isUsingNonZeroWinding
  16503. */
  16504. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  16505. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  16506. The default for a new path is true.
  16507. @see setUsingNonZeroWinding
  16508. */
  16509. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  16510. /** Iterates the lines and curves that a path contains.
  16511. @see Path, PathFlatteningIterator
  16512. */
  16513. class JUCE_API Iterator
  16514. {
  16515. public:
  16516. Iterator (const Path& path);
  16517. ~Iterator();
  16518. /** Moves onto the next element in the path.
  16519. If this returns false, there are no more elements. If it returns true,
  16520. the elementType variable will be set to the type of the current element,
  16521. and some of the x and y variables will be filled in with values.
  16522. */
  16523. bool next();
  16524. enum PathElementType
  16525. {
  16526. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  16527. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  16528. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  16529. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  16530. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  16531. };
  16532. PathElementType elementType;
  16533. float x1, y1, x2, y2, x3, y3;
  16534. private:
  16535. const Path& path;
  16536. size_t index;
  16537. Iterator (const Iterator&);
  16538. Iterator& operator= (const Iterator&);
  16539. };
  16540. /** Loads a stored path from a data stream.
  16541. The data in the stream must have been written using writePathToStream().
  16542. Note that this will append the stored path to whatever is currently in
  16543. this path, so you might need to call clear() beforehand.
  16544. @see loadPathFromData, writePathToStream
  16545. */
  16546. void loadPathFromStream (InputStream& source);
  16547. /** Loads a stored path from a block of data.
  16548. This is similar to loadPathFromStream(), but just reads from a block
  16549. of data. Useful if you're including stored shapes in your code as a
  16550. block of static data.
  16551. @see loadPathFromStream, writePathToStream
  16552. */
  16553. void loadPathFromData (const void* data, int numberOfBytes);
  16554. /** Stores the path by writing it out to a stream.
  16555. After writing out a path, you can reload it using loadPathFromStream().
  16556. @see loadPathFromStream, loadPathFromData
  16557. */
  16558. void writePathToStream (OutputStream& destination) const;
  16559. /** Creates a string containing a textual representation of this path.
  16560. @see restoreFromString
  16561. */
  16562. const String toString() const;
  16563. /** Restores this path from a string that was created with the toString() method.
  16564. @see toString()
  16565. */
  16566. void restoreFromString (const String& stringVersion);
  16567. juce_UseDebuggingNewOperator
  16568. private:
  16569. friend class PathFlatteningIterator;
  16570. friend class Path::Iterator;
  16571. ArrayAllocationBase <float, DummyCriticalSection> data;
  16572. size_t numElements;
  16573. float pathXMin, pathXMax, pathYMin, pathYMax;
  16574. bool useNonZeroWinding;
  16575. static const float lineMarker;
  16576. static const float moveMarker;
  16577. static const float quadMarker;
  16578. static const float cubicMarker;
  16579. static const float closeSubPathMarker;
  16580. };
  16581. #endif // __JUCE_PATH_JUCEHEADER__
  16582. /*** End of inlined file: juce_Path.h ***/
  16583. class Font;
  16584. /** A typeface represents a size-independent font.
  16585. This base class is abstract, but calling createSystemTypefaceFor() will return
  16586. a platform-specific subclass that can be used.
  16587. The CustomTypeface subclass allow you to build your own typeface, and to
  16588. load and save it in the Juce typeface format.
  16589. Normally you should never need to deal directly with Typeface objects - the Font
  16590. class does everything you typically need for rendering text.
  16591. @see CustomTypeface, Font
  16592. */
  16593. class JUCE_API Typeface : public ReferenceCountedObject
  16594. {
  16595. public:
  16596. /** A handy typedef for a pointer to a typeface. */
  16597. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  16598. /** Returns the name of the typeface.
  16599. @see Font::getTypefaceName
  16600. */
  16601. const String getName() const throw() { return name; }
  16602. /** Creates a new system typeface. */
  16603. static const Ptr createSystemTypefaceFor (const Font& font);
  16604. /** Destructor. */
  16605. virtual ~Typeface();
  16606. /** Returns the ascent of the font, as a proportion of its height.
  16607. The height is considered to always be normalised as 1.0, so this will be a
  16608. value less that 1.0, indicating the proportion of the font that lies above
  16609. its baseline.
  16610. */
  16611. virtual float getAscent() const = 0;
  16612. /** Returns the descent of the font, as a proportion of its height.
  16613. The height is considered to always be normalised as 1.0, so this will be a
  16614. value less that 1.0, indicating the proportion of the font that lies below
  16615. its baseline.
  16616. */
  16617. virtual float getDescent() const = 0;
  16618. /** Measures the width of a line of text.
  16619. The distance returned is based on the font having an normalised height of 1.0.
  16620. You should never need to call this directly! Use Font::getStringWidth() instead!
  16621. */
  16622. virtual float getStringWidth (const String& text) = 0;
  16623. /** Converts a line of text into its glyph numbers and their positions.
  16624. The distances returned are based on the font having an normalised height of 1.0.
  16625. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  16626. */
  16627. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  16628. /** Returns the outline for a glyph.
  16629. The path returned will be normalised to a font height of 1.0.
  16630. */
  16631. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  16632. juce_UseDebuggingNewOperator
  16633. protected:
  16634. String name;
  16635. explicit Typeface (const String& name) throw();
  16636. private:
  16637. Typeface (const Typeface&);
  16638. Typeface& operator= (const Typeface&);
  16639. };
  16640. /** A typeface that can be populated with custom glyphs.
  16641. You can create a CustomTypeface if you need one that contains your own glyphs,
  16642. or if you need to load a typeface from a Juce-formatted binary stream.
  16643. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  16644. to copy glyphs into this face.
  16645. @see Typeface, Font
  16646. */
  16647. class JUCE_API CustomTypeface : public Typeface
  16648. {
  16649. public:
  16650. /** Creates a new, empty typeface. */
  16651. CustomTypeface();
  16652. /** Loads a typeface from a previously saved stream.
  16653. The stream must have been created by writeToStream().
  16654. @see writeToStream
  16655. */
  16656. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  16657. /** Destructor. */
  16658. ~CustomTypeface();
  16659. /** Resets this typeface, deleting all its glyphs and settings. */
  16660. void clear();
  16661. /** Sets the vital statistics for the typeface.
  16662. @param name the typeface's name
  16663. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  16664. the value that will be returned by Typeface::getAscent(). The
  16665. descent is assumed to be (1.0 - ascent)
  16666. @param isBold should be true if the typeface is bold
  16667. @param isItalic should be true if the typeface is italic
  16668. @param defaultCharacter the character to be used as a replacement if there's
  16669. no glyph available for the character that's being drawn
  16670. */
  16671. void setCharacteristics (const String& name, float ascent,
  16672. bool isBold, bool isItalic,
  16673. juce_wchar defaultCharacter) throw();
  16674. /** Adds a glyph to the typeface.
  16675. The path that is passed in is normalised so that the font height is 1.0, and its
  16676. origin is the anchor point of the character on its baseline.
  16677. The width is the nominal width of the character, and any extra kerning values that
  16678. are specified will be added to this width.
  16679. */
  16680. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  16681. /** Specifies an extra kerning amount to be used between a pair of characters.
  16682. The amount will be added to the nominal width of the first character when laying out a string.
  16683. */
  16684. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  16685. /** Adds a range of glyphs from another typeface.
  16686. This will attempt to pull in the paths and kerning information from another typeface and
  16687. add it to this one.
  16688. */
  16689. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  16690. /** Saves this typeface as a Juce-formatted font file.
  16691. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  16692. constructor.
  16693. */
  16694. bool writeToStream (OutputStream& outputStream);
  16695. // The following methods implement the basic Typeface behaviour.
  16696. float getAscent() const;
  16697. float getDescent() const;
  16698. float getStringWidth (const String& text);
  16699. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  16700. bool getOutlineForGlyph (int glyphNumber, Path& path);
  16701. int getGlyphForCharacter (juce_wchar character);
  16702. juce_UseDebuggingNewOperator
  16703. protected:
  16704. juce_wchar defaultCharacter;
  16705. float ascent;
  16706. bool isBold, isItalic;
  16707. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  16708. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  16709. particular character and there's no corresponding glyph, they'll call this
  16710. method so that a subclass can try to add that glyph, returning true if it
  16711. manages to do so.
  16712. */
  16713. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  16714. private:
  16715. class GlyphInfo;
  16716. friend class OwnedArray<GlyphInfo>;
  16717. OwnedArray <GlyphInfo> glyphs;
  16718. short lookupTable [128];
  16719. CustomTypeface (const CustomTypeface&);
  16720. CustomTypeface& operator= (const CustomTypeface&);
  16721. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  16722. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  16723. };
  16724. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  16725. /*** End of inlined file: juce_Typeface.h ***/
  16726. class LowLevelGraphicsContext;
  16727. /**
  16728. Represents a particular font, including its size, style, etc.
  16729. Apart from the typeface to be used, a Font object also dictates whether
  16730. the font is bold, italic, underlined, how big it is, and its kerning and
  16731. horizontal scale factor.
  16732. @see Typeface
  16733. */
  16734. class JUCE_API Font
  16735. {
  16736. public:
  16737. /** A combination of these values is used by the constructor to specify the
  16738. style of font to use.
  16739. */
  16740. enum FontStyleFlags
  16741. {
  16742. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  16743. bold = 1, /**< boldens the font. @see setStyleFlags */
  16744. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  16745. underlined = 4 /**< underlines the font. @see setStyleFlags */
  16746. };
  16747. /** Creates a sans-serif font in a given size.
  16748. @param fontHeight the height in pixels (can be fractional)
  16749. @param styleFlags the style to use - this can be a combination of the
  16750. Font::bold, Font::italic and Font::underlined, or
  16751. just Font::plain for the normal style.
  16752. @see FontStyleFlags, getDefaultSansSerifFontName
  16753. */
  16754. Font (float fontHeight,
  16755. int styleFlags = plain) throw();
  16756. /** Creates a font with a given typeface and parameters.
  16757. @param typefaceName the name of the typeface to use
  16758. @param fontHeight the height in pixels (can be fractional)
  16759. @param styleFlags the style to use - this can be a combination of the
  16760. Font::bold, Font::italic and Font::underlined, or
  16761. just Font::plain for the normal style.
  16762. @see FontStyleFlags, getDefaultSansSerifFontName
  16763. */
  16764. Font (const String& typefaceName,
  16765. float fontHeight,
  16766. int styleFlags) throw();
  16767. /** Creates a copy of another Font object. */
  16768. Font (const Font& other) throw();
  16769. /** Creates a font for a typeface. */
  16770. Font (const Typeface::Ptr& typeface) throw();
  16771. /** Creates a basic sans-serif font at a default height.
  16772. You should use one of the other constructors for creating a font that you're planning
  16773. on drawing with - this constructor is here to help initialise objects before changing
  16774. the font's settings later.
  16775. */
  16776. Font() throw();
  16777. /** Copies this font from another one. */
  16778. Font& operator= (const Font& other) throw();
  16779. bool operator== (const Font& other) const throw();
  16780. bool operator!= (const Font& other) const throw();
  16781. /** Destructor. */
  16782. ~Font() throw();
  16783. /** Changes the name of the typeface family.
  16784. e.g. "Arial", "Courier", etc.
  16785. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16786. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16787. but are generic names that are used to represent the various default fonts.
  16788. If you need to know the exact typeface name being used, you can call
  16789. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16790. If a suitable font isn't found on the machine, it'll just use a default instead.
  16791. */
  16792. void setTypefaceName (const String& faceName) throw();
  16793. /** Returns the name of the typeface family that this font uses.
  16794. e.g. "Arial", "Courier", etc.
  16795. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16796. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16797. but are generic names that are used to represent the various default fonts.
  16798. If you need to know the exact typeface name being used, you can call
  16799. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16800. */
  16801. const String& getTypefaceName() const throw() { return font->typefaceName; }
  16802. /** Returns a typeface name that represents the default sans-serif font.
  16803. This is also the typeface that will be used when a font is created without
  16804. specifying any typeface details.
  16805. Note that this method just returns a generic placeholder string that means "the default
  16806. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  16807. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16808. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  16809. */
  16810. static const String getDefaultSansSerifFontName() throw();
  16811. /** Returns a typeface name that represents the default sans-serif font.
  16812. Note that this method just returns a generic placeholder string that means "the default
  16813. serif font" - it's not the actual name of this font. To get the actual name, use
  16814. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16815. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  16816. */
  16817. static const String getDefaultSerifFontName() throw();
  16818. /** Returns a typeface name that represents the default sans-serif font.
  16819. Note that this method just returns a generic placeholder string that means "the default
  16820. monospaced font" - it's not the actual name of this font. To get the actual name, use
  16821. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16822. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  16823. */
  16824. static const String getDefaultMonospacedFontName() throw();
  16825. /** Returns the typeface names of the default fonts on the current platform. */
  16826. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed);
  16827. /** Returns the total height of this font.
  16828. This is the maximum height, from the top of the ascent to the bottom of the
  16829. descenders.
  16830. @see setHeight, setHeightWithoutChangingWidth, getAscent
  16831. */
  16832. float getHeight() const throw() { return font->height; }
  16833. /** Changes the font's height.
  16834. @see getHeight, setHeightWithoutChangingWidth
  16835. */
  16836. void setHeight (float newHeight) throw();
  16837. /** Changes the font's height without changing its width.
  16838. This alters the horizontal scale to compensate for the change in height.
  16839. */
  16840. void setHeightWithoutChangingWidth (float newHeight) throw();
  16841. /** Returns the height of the font above its baseline.
  16842. This is the maximum height from the baseline to the top.
  16843. @see getHeight, getDescent
  16844. */
  16845. float getAscent() const throw();
  16846. /** Returns the amount that the font descends below its baseline.
  16847. This is calculated as (getHeight() - getAscent()).
  16848. @see getAscent, getHeight
  16849. */
  16850. float getDescent() const throw();
  16851. /** Returns the font's style flags.
  16852. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  16853. enum, to describe whether the font is bold, italic, etc.
  16854. @see FontStyleFlags
  16855. */
  16856. int getStyleFlags() const throw() { return font->styleFlags; }
  16857. /** Changes the font's style.
  16858. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  16859. enum, to set the font's properties
  16860. @see FontStyleFlags
  16861. */
  16862. void setStyleFlags (int newFlags) throw();
  16863. /** Makes the font bold or non-bold. */
  16864. void setBold (bool shouldBeBold) throw();
  16865. /** Returns true if the font is bold. */
  16866. bool isBold() const throw();
  16867. /** Makes the font italic or non-italic. */
  16868. void setItalic (bool shouldBeItalic) throw();
  16869. /** Returns true if the font is italic. */
  16870. bool isItalic() const throw();
  16871. /** Makes the font underlined or non-underlined. */
  16872. void setUnderline (bool shouldBeUnderlined) throw();
  16873. /** Returns true if the font is underlined. */
  16874. bool isUnderlined() const throw();
  16875. /** Changes the font's horizontal scale factor.
  16876. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  16877. narrower, greater than 1.0 will be stretched out.
  16878. */
  16879. void setHorizontalScale (float scaleFactor) throw();
  16880. /** Returns the font's horizontal scale.
  16881. A value of 1.0 is the normal scale, less than this will be narrower, greater
  16882. than 1.0 will be stretched out.
  16883. @see setHorizontalScale
  16884. */
  16885. float getHorizontalScale() const throw() { return font->horizontalScale; }
  16886. /** Changes the font's kerning.
  16887. @param extraKerning a multiple of the font's height that will be added
  16888. to space between the characters. So a value of zero is
  16889. normal spacing, positive values spread the letters out,
  16890. negative values make them closer together.
  16891. */
  16892. void setExtraKerningFactor (float extraKerning) throw();
  16893. /** Returns the font's kerning.
  16894. This is the extra space added between adjacent characters, as a proportion
  16895. of the font's height.
  16896. A value of zero is normal spacing, positive values will spread the letters
  16897. out more, and negative values make them closer together.
  16898. */
  16899. float getExtraKerningFactor() const throw() { return font->kerning; }
  16900. /** Changes all the font's characteristics with one call. */
  16901. void setSizeAndStyle (float newHeight,
  16902. int newStyleFlags,
  16903. float newHorizontalScale,
  16904. float newKerningAmount) throw();
  16905. /** Returns the total width of a string as it would be drawn using this font.
  16906. For a more accurate floating-point result, use getStringWidthFloat().
  16907. */
  16908. int getStringWidth (const String& text) const throw();
  16909. /** Returns the total width of a string as it would be drawn using this font.
  16910. @see getStringWidth
  16911. */
  16912. float getStringWidthFloat (const String& text) const throw();
  16913. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  16914. An extra x offset is added at the end of the run, to indicate where the right hand
  16915. edge of the last character is.
  16916. */
  16917. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  16918. /** Returns the typeface used by this font.
  16919. Note that the object returned may go out of scope if this font is deleted
  16920. or has its style changed.
  16921. */
  16922. Typeface* getTypeface() const throw();
  16923. /** Creates an array of Font objects to represent all the fonts on the system.
  16924. If you just need the names of the typefaces, you can also use
  16925. findAllTypefaceNames() instead.
  16926. @param results the array to which new Font objects will be added.
  16927. */
  16928. static void findFonts (Array<Font>& results) throw();
  16929. /** Returns a list of all the available typeface names.
  16930. The names returned can be passed into setTypefaceName().
  16931. You can use this instead of findFonts() if you only need their names, and not
  16932. font objects.
  16933. */
  16934. static const StringArray findAllTypefaceNames();
  16935. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  16936. in the requested typeface.
  16937. */
  16938. static const String getFallbackFontName() throw();
  16939. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  16940. available in whatever font you're trying to use.
  16941. */
  16942. static void setFallbackFontName (const String& name) throw();
  16943. /** Creates a string to describe this font.
  16944. The string will contain information to describe the font's typeface, size, and
  16945. style. To recreate the font from this string, use fromString().
  16946. */
  16947. const String toString() const;
  16948. /** Recreates a font from its stringified encoding.
  16949. This method takes a string that was created by toString(), and recreates the
  16950. original font.
  16951. */
  16952. static const Font fromString (const String& fontDescription);
  16953. juce_UseDebuggingNewOperator
  16954. private:
  16955. friend class FontGlyphAlphaMap;
  16956. friend class TypefaceCache;
  16957. class SharedFontInternal : public ReferenceCountedObject
  16958. {
  16959. public:
  16960. SharedFontInternal (const String& typefaceName, float height, float horizontalScale,
  16961. float kerning, float ascent, int styleFlags,
  16962. Typeface* typeface) throw();
  16963. SharedFontInternal (const SharedFontInternal& other) throw();
  16964. String typefaceName;
  16965. float height, horizontalScale, kerning, ascent;
  16966. int styleFlags;
  16967. Typeface::Ptr typeface;
  16968. };
  16969. ReferenceCountedObjectPtr <SharedFontInternal> font;
  16970. void dupeInternalIfShared() throw();
  16971. };
  16972. #endif // __JUCE_FONT_JUCEHEADER__
  16973. /*** End of inlined file: juce_Font.h ***/
  16974. /*** Start of inlined file: juce_PathStrokeType.h ***/
  16975. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16976. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16977. /**
  16978. Describes a type of stroke used to render a solid outline along a path.
  16979. A PathStrokeType object can be used directly to create the shape of an outline
  16980. around a path, and is used by Graphics::strokePath to specify the type of
  16981. stroke to draw.
  16982. @see Path, Graphics::strokePath
  16983. */
  16984. class JUCE_API PathStrokeType
  16985. {
  16986. public:
  16987. /** The type of shape to use for the corners between two adjacent line segments. */
  16988. enum JointStyle
  16989. {
  16990. mitered, /**< Indicates that corners should be drawn with sharp joints.
  16991. Note that for angles that curve back on themselves, drawing a
  16992. mitre could require extending the point too far away from the
  16993. path, so a mitre limit is imposed and any corners that exceed it
  16994. are drawn as bevelled instead. */
  16995. curved, /**< Indicates that corners should be drawn as rounded-off. */
  16996. beveled /**< Indicates that corners should be drawn with a line flattening their
  16997. outside edge. */
  16998. };
  16999. /** The type shape to use for the ends of lines. */
  17000. enum EndCapStyle
  17001. {
  17002. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  17003. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  17004. the thickness of the stroke. */
  17005. rounded /**< Ends of lines are rounded-off with a circular shape. */
  17006. };
  17007. /** Creates a stroke type.
  17008. @param strokeThickness the width of the line to use
  17009. @param jointStyle the type of joints to use for corners
  17010. @param endStyle the type of end-caps to use for the ends of open paths.
  17011. */
  17012. PathStrokeType (float strokeThickness,
  17013. JointStyle jointStyle = mitered,
  17014. EndCapStyle endStyle = butt) throw();
  17015. /** Createes a copy of another stroke type. */
  17016. PathStrokeType (const PathStrokeType& other) throw();
  17017. /** Copies another stroke onto this one. */
  17018. PathStrokeType& operator= (const PathStrokeType& other) throw();
  17019. /** Destructor. */
  17020. ~PathStrokeType() throw();
  17021. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  17022. @param destPath the resultant stroked outline shape will be copied into this path.
  17023. Note that it's ok for the source and destination Paths to be
  17024. the same object, so you can easily turn a path into a stroked version
  17025. of itself.
  17026. @param sourcePath the path to use as the source
  17027. @param transform an optional transform to apply to the points from the source path
  17028. as they are being used
  17029. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17030. a higher resolution, which improved the quality if you'll later want
  17031. to enlarge the stroked path
  17032. @see createDashedStroke
  17033. */
  17034. void createStrokedPath (Path& destPath,
  17035. const Path& sourcePath,
  17036. const AffineTransform& transform = AffineTransform::identity,
  17037. float extraAccuracy = 1.0f) const;
  17038. /** Applies this stroke type to a path, creating a dashed line.
  17039. This is similar to createStrokedPath, but uses the array passed in to
  17040. break the stroke up into a series of dashes.
  17041. @param destPath the resultant stroked outline shape will be copied into this path.
  17042. Note that it's ok for the source and destination Paths to be
  17043. the same object, so you can easily turn a path into a stroked version
  17044. of itself.
  17045. @param sourcePath the path to use as the source
  17046. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  17047. a line of length 2, then skip a length of 3, then add a line of length 4,
  17048. skip 5, and keep repeating this pattern.
  17049. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  17050. an even number, otherwise the pattern will get out of step as it
  17051. repeats.
  17052. @param transform an optional transform to apply to the points from the source path
  17053. as they are being used
  17054. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17055. a higher resolution, which improved the quality if you'll later want
  17056. to enlarge the stroked path
  17057. */
  17058. void createDashedStroke (Path& destPath,
  17059. const Path& sourcePath,
  17060. const float* dashLengths,
  17061. int numDashLengths,
  17062. const AffineTransform& transform = AffineTransform::identity,
  17063. float extraAccuracy = 1.0f) const;
  17064. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  17065. @param destPath the resultant stroked outline shape will be copied into this path.
  17066. Note that it's ok for the source and destination Paths to be
  17067. the same object, so you can easily turn a path into a stroked version
  17068. of itself.
  17069. @param sourcePath the path to use as the source
  17070. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  17071. @param arrowheadStartLength the length of the arrowhead at the start of the path
  17072. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  17073. @param arrowheadEndLength the length of the arrowhead at the end of the path
  17074. @param transform an optional transform to apply to the points from the source path
  17075. as they are being used
  17076. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17077. a higher resolution, which improved the quality if you'll later want
  17078. to enlarge the stroked path
  17079. @see createDashedStroke
  17080. */
  17081. void createStrokeWithArrowheads (Path& destPath,
  17082. const Path& sourcePath,
  17083. float arrowheadStartWidth, float arrowheadStartLength,
  17084. float arrowheadEndWidth, float arrowheadEndLength,
  17085. const AffineTransform& transform = AffineTransform::identity,
  17086. float extraAccuracy = 1.0f) const;
  17087. /** Returns the stroke thickness. */
  17088. float getStrokeThickness() const throw() { return thickness; }
  17089. /** Sets the stroke thickness. */
  17090. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  17091. /** Returns the joint style. */
  17092. JointStyle getJointStyle() const throw() { return jointStyle; }
  17093. /** Sets the joint style. */
  17094. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  17095. /** Returns the end-cap style. */
  17096. EndCapStyle getEndStyle() const throw() { return endStyle; }
  17097. /** Sets the end-cap style. */
  17098. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  17099. juce_UseDebuggingNewOperator
  17100. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  17101. bool operator== (const PathStrokeType& other) const throw();
  17102. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  17103. bool operator!= (const PathStrokeType& other) const throw();
  17104. private:
  17105. float thickness;
  17106. JointStyle jointStyle;
  17107. EndCapStyle endStyle;
  17108. };
  17109. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  17110. /*** End of inlined file: juce_PathStrokeType.h ***/
  17111. /*** Start of inlined file: juce_Colours.h ***/
  17112. #ifndef __JUCE_COLOURS_JUCEHEADER__
  17113. #define __JUCE_COLOURS_JUCEHEADER__
  17114. /*** Start of inlined file: juce_Colour.h ***/
  17115. #ifndef __JUCE_COLOUR_JUCEHEADER__
  17116. #define __JUCE_COLOUR_JUCEHEADER__
  17117. /*** Start of inlined file: juce_PixelFormats.h ***/
  17118. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  17119. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  17120. #if JUCE_MSVC
  17121. #pragma pack (push, 1)
  17122. #define PACKED
  17123. #elif JUCE_GCC
  17124. #define PACKED __attribute__((packed))
  17125. #else
  17126. #define PACKED
  17127. #endif
  17128. class PixelRGB;
  17129. class PixelAlpha;
  17130. /**
  17131. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  17132. operations with it.
  17133. This is used internally by the imaging classes.
  17134. @see PixelRGB
  17135. */
  17136. class JUCE_API PixelARGB
  17137. {
  17138. public:
  17139. /** Creates a pixel without defining its colour. */
  17140. PixelARGB() throw() {}
  17141. ~PixelARGB() throw() {}
  17142. /** Creates a pixel from a 32-bit argb value.
  17143. */
  17144. PixelARGB (const uint32 argb_) throw()
  17145. : argb (argb_)
  17146. {
  17147. }
  17148. forcedinline uint32 getARGB() const throw() { return argb; }
  17149. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  17150. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  17151. forcedinline uint8 getAlpha() const throw() { return components.a; }
  17152. forcedinline uint8 getRed() const throw() { return components.r; }
  17153. forcedinline uint8 getGreen() const throw() { return components.g; }
  17154. forcedinline uint8 getBlue() const throw() { return components.b; }
  17155. /** Blends another pixel onto this one.
  17156. This takes into account the opacity of the pixel being overlaid, and blends
  17157. it accordingly.
  17158. */
  17159. forcedinline void blend (const PixelARGB& src) throw()
  17160. {
  17161. uint32 sargb = src.getARGB();
  17162. const uint32 alpha = 0x100 - (sargb >> 24);
  17163. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17164. sargb += 0xff00ff00 & (getAG() * alpha);
  17165. argb = sargb;
  17166. }
  17167. /** Blends another pixel onto this one.
  17168. This takes into account the opacity of the pixel being overlaid, and blends
  17169. it accordingly.
  17170. */
  17171. forcedinline void blend (const PixelAlpha& src) throw();
  17172. /** Blends another pixel onto this one.
  17173. This takes into account the opacity of the pixel being overlaid, and blends
  17174. it accordingly.
  17175. */
  17176. forcedinline void blend (const PixelRGB& src) throw();
  17177. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17178. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17179. being used, so this can blend semi-transparently from a PixelRGB argument.
  17180. */
  17181. template <class Pixel>
  17182. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17183. {
  17184. ++extraAlpha;
  17185. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  17186. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  17187. const uint32 alpha = 0x100 - (sargb >> 24);
  17188. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17189. sargb += 0xff00ff00 & (getAG() * alpha);
  17190. argb = sargb;
  17191. }
  17192. /** Blends another pixel with this one, creating a colour that is somewhere
  17193. between the two, as specified by the amount.
  17194. */
  17195. template <class Pixel>
  17196. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17197. {
  17198. uint32 drb = getRB();
  17199. drb += (((src.getRB() - drb) * amount) >> 8);
  17200. drb &= 0x00ff00ff;
  17201. uint32 dag = getAG();
  17202. dag += (((src.getAG() - dag) * amount) >> 8);
  17203. dag &= 0x00ff00ff;
  17204. dag <<= 8;
  17205. dag |= drb;
  17206. argb = dag;
  17207. }
  17208. /** Copies another pixel colour over this one.
  17209. This doesn't blend it - this colour is simply replaced by the other one.
  17210. */
  17211. template <class Pixel>
  17212. forcedinline void set (const Pixel& src) throw()
  17213. {
  17214. argb = src.getARGB();
  17215. }
  17216. /** Replaces the colour's alpha value with another one. */
  17217. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17218. {
  17219. components.a = newAlpha;
  17220. }
  17221. /** Multiplies the colour's alpha value with another one. */
  17222. forcedinline void multiplyAlpha (int multiplier) throw()
  17223. {
  17224. ++multiplier;
  17225. argb = ((multiplier * getAG()) & 0xff00ff00)
  17226. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  17227. }
  17228. forcedinline void multiplyAlpha (const float multiplier) throw()
  17229. {
  17230. multiplyAlpha ((int) (multiplier * 256.0f));
  17231. }
  17232. /** Sets the pixel's colour from individual components. */
  17233. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  17234. {
  17235. components.b = b;
  17236. components.g = g;
  17237. components.r = r;
  17238. components.a = a;
  17239. }
  17240. /** Premultiplies the pixel's RGB values by its alpha. */
  17241. forcedinline void premultiply() throw()
  17242. {
  17243. const uint32 alpha = components.a;
  17244. if (alpha < 0xff)
  17245. {
  17246. if (alpha == 0)
  17247. {
  17248. components.b = 0;
  17249. components.g = 0;
  17250. components.r = 0;
  17251. }
  17252. else
  17253. {
  17254. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  17255. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  17256. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  17257. }
  17258. }
  17259. }
  17260. /** Unpremultiplies the pixel's RGB values. */
  17261. forcedinline void unpremultiply() throw()
  17262. {
  17263. const uint32 alpha = components.a;
  17264. if (alpha < 0xff)
  17265. {
  17266. if (alpha == 0)
  17267. {
  17268. components.b = 0;
  17269. components.g = 0;
  17270. components.r = 0;
  17271. }
  17272. else
  17273. {
  17274. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  17275. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  17276. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  17277. }
  17278. }
  17279. }
  17280. forcedinline void desaturate() throw()
  17281. {
  17282. if (components.a < 0xff && components.a > 0)
  17283. {
  17284. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  17285. components.r = components.g = components.b
  17286. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  17287. }
  17288. else
  17289. {
  17290. components.r = components.g = components.b
  17291. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  17292. }
  17293. }
  17294. /** The indexes of the different components in the byte layout of this type of colour. */
  17295. #if JUCE_BIG_ENDIAN
  17296. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  17297. #else
  17298. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  17299. #endif
  17300. private:
  17301. union
  17302. {
  17303. uint32 argb;
  17304. struct
  17305. {
  17306. #if JUCE_BIG_ENDIAN
  17307. uint8 a : 8, r : 8, g : 8, b : 8;
  17308. #else
  17309. uint8 b, g, r, a;
  17310. #endif
  17311. } PACKED components;
  17312. };
  17313. } PACKED;
  17314. /**
  17315. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  17316. This is used internally by the imaging classes.
  17317. @see PixelARGB
  17318. */
  17319. class JUCE_API PixelRGB
  17320. {
  17321. public:
  17322. /** Creates a pixel without defining its colour. */
  17323. PixelRGB() throw() {}
  17324. ~PixelRGB() throw() {}
  17325. /** Creates a pixel from a 32-bit argb value.
  17326. (The argb format is that used by PixelARGB)
  17327. */
  17328. PixelRGB (const uint32 argb) throw()
  17329. {
  17330. r = (uint8) (argb >> 16);
  17331. g = (uint8) (argb >> 8);
  17332. b = (uint8) (argb);
  17333. }
  17334. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  17335. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  17336. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  17337. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  17338. forcedinline uint8 getRed() const throw() { return r; }
  17339. forcedinline uint8 getGreen() const throw() { return g; }
  17340. forcedinline uint8 getBlue() const throw() { return b; }
  17341. /** Blends another pixel onto this one.
  17342. This takes into account the opacity of the pixel being overlaid, and blends
  17343. it accordingly.
  17344. */
  17345. forcedinline void blend (const PixelARGB& src) throw()
  17346. {
  17347. uint32 sargb = src.getARGB();
  17348. const uint32 alpha = 0x100 - (sargb >> 24);
  17349. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17350. sargb += 0x0000ff00 & (g * alpha);
  17351. r = (uint8) (sargb >> 16);
  17352. g = (uint8) (sargb >> 8);
  17353. b = (uint8) sargb;
  17354. }
  17355. forcedinline void blend (const PixelRGB& src) throw()
  17356. {
  17357. set (src);
  17358. }
  17359. forcedinline void blend (const PixelAlpha& src) throw();
  17360. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17361. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17362. being used, so this can blend semi-transparently from a PixelRGB argument.
  17363. */
  17364. template <class Pixel>
  17365. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17366. {
  17367. ++extraAlpha;
  17368. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  17369. const uint32 sag = extraAlpha * src.getAG();
  17370. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  17371. const uint32 alpha = 0x100 - (sargb >> 24);
  17372. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17373. sargb += 0x0000ff00 & (g * alpha);
  17374. b = (uint8) sargb;
  17375. g = (uint8) (sargb >> 8);
  17376. r = (uint8) (sargb >> 16);
  17377. }
  17378. /** Blends another pixel with this one, creating a colour that is somewhere
  17379. between the two, as specified by the amount.
  17380. */
  17381. template <class Pixel>
  17382. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17383. {
  17384. uint32 drb = getRB();
  17385. drb += (((src.getRB() - drb) * amount) >> 8);
  17386. uint32 dag = getAG();
  17387. dag += (((src.getAG() - dag) * amount) >> 8);
  17388. b = (uint8) drb;
  17389. g = (uint8) dag;
  17390. r = (uint8) (drb >> 16);
  17391. }
  17392. /** Copies another pixel colour over this one.
  17393. This doesn't blend it - this colour is simply replaced by the other one.
  17394. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  17395. is thrown away.
  17396. */
  17397. template <class Pixel>
  17398. forcedinline void set (const Pixel& src) throw()
  17399. {
  17400. b = src.getBlue();
  17401. g = src.getGreen();
  17402. r = src.getRed();
  17403. }
  17404. /** This method is included for compatibility with the PixelARGB class. */
  17405. forcedinline void setAlpha (const uint8) throw() {}
  17406. /** Multiplies the colour's alpha value with another one. */
  17407. forcedinline void multiplyAlpha (int) throw() {}
  17408. /** Sets the pixel's colour from individual components. */
  17409. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  17410. {
  17411. r = r_;
  17412. g = g_;
  17413. b = b_;
  17414. }
  17415. /** Premultiplies the pixel's RGB values by its alpha. */
  17416. forcedinline void premultiply() throw() {}
  17417. /** Unpremultiplies the pixel's RGB values. */
  17418. forcedinline void unpremultiply() throw() {}
  17419. forcedinline void desaturate() throw()
  17420. {
  17421. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  17422. }
  17423. /** The indexes of the different components in the byte layout of this type of colour. */
  17424. #if JUCE_MAC
  17425. enum { indexR = 0, indexG = 1, indexB = 2 };
  17426. #else
  17427. enum { indexR = 2, indexG = 1, indexB = 0 };
  17428. #endif
  17429. private:
  17430. #if JUCE_MAC
  17431. uint8 r, g, b;
  17432. #else
  17433. uint8 b, g, r;
  17434. #endif
  17435. } PACKED;
  17436. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  17437. {
  17438. set (src);
  17439. }
  17440. /**
  17441. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  17442. This is used internally by the imaging classes.
  17443. @see PixelARGB, PixelRGB
  17444. */
  17445. class JUCE_API PixelAlpha
  17446. {
  17447. public:
  17448. /** Creates a pixel without defining its colour. */
  17449. PixelAlpha() throw() {}
  17450. ~PixelAlpha() throw() {}
  17451. /** Creates a pixel from a 32-bit argb value.
  17452. (The argb format is that used by PixelARGB)
  17453. */
  17454. PixelAlpha (const uint32 argb) throw()
  17455. {
  17456. a = (uint8) (argb >> 24);
  17457. }
  17458. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  17459. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  17460. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  17461. forcedinline uint8 getAlpha() const throw() { return a; }
  17462. forcedinline uint8 getRed() const throw() { return 0; }
  17463. forcedinline uint8 getGreen() const throw() { return 0; }
  17464. forcedinline uint8 getBlue() const throw() { return 0; }
  17465. /** Blends another pixel onto this one.
  17466. This takes into account the opacity of the pixel being overlaid, and blends
  17467. it accordingly.
  17468. */
  17469. template <class Pixel>
  17470. forcedinline void blend (const Pixel& src) throw()
  17471. {
  17472. const int srcA = src.getAlpha();
  17473. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  17474. }
  17475. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17476. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17477. being used, so this can blend semi-transparently from a PixelRGB argument.
  17478. */
  17479. template <class Pixel>
  17480. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17481. {
  17482. ++extraAlpha;
  17483. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  17484. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  17485. }
  17486. /** Blends another pixel with this one, creating a colour that is somewhere
  17487. between the two, as specified by the amount.
  17488. */
  17489. template <class Pixel>
  17490. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17491. {
  17492. a += ((src,getAlpha() - a) * amount) >> 8;
  17493. }
  17494. /** Copies another pixel colour over this one.
  17495. This doesn't blend it - this colour is simply replaced by the other one.
  17496. */
  17497. template <class Pixel>
  17498. forcedinline void set (const Pixel& src) throw()
  17499. {
  17500. a = src.getAlpha();
  17501. }
  17502. /** Replaces the colour's alpha value with another one. */
  17503. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17504. {
  17505. a = newAlpha;
  17506. }
  17507. /** Multiplies the colour's alpha value with another one. */
  17508. forcedinline void multiplyAlpha (int multiplier) throw()
  17509. {
  17510. ++multiplier;
  17511. a = (uint8) ((a * multiplier) >> 8);
  17512. }
  17513. forcedinline void multiplyAlpha (const float multiplier) throw()
  17514. {
  17515. a = (uint8) (a * multiplier);
  17516. }
  17517. /** Sets the pixel's colour from individual components. */
  17518. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  17519. {
  17520. a = a_;
  17521. }
  17522. /** Premultiplies the pixel's RGB values by its alpha. */
  17523. forcedinline void premultiply() throw()
  17524. {
  17525. }
  17526. /** Unpremultiplies the pixel's RGB values. */
  17527. forcedinline void unpremultiply() throw()
  17528. {
  17529. }
  17530. forcedinline void desaturate() throw()
  17531. {
  17532. }
  17533. /** The indexes of the different components in the byte layout of this type of colour. */
  17534. enum { indexA = 0 };
  17535. private:
  17536. uint8 a : 8;
  17537. } PACKED;
  17538. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  17539. {
  17540. blend (PixelARGB (src.getARGB()));
  17541. }
  17542. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  17543. {
  17544. uint32 sargb = src.getARGB();
  17545. const uint32 alpha = 0x100 - (sargb >> 24);
  17546. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17547. sargb += 0xff00ff00 & (getAG() * alpha);
  17548. argb = sargb;
  17549. }
  17550. #if JUCE_MSVC
  17551. #pragma pack (pop)
  17552. #endif
  17553. #undef PACKED
  17554. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  17555. /*** End of inlined file: juce_PixelFormats.h ***/
  17556. /**
  17557. Represents a colour, also including a transparency value.
  17558. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  17559. */
  17560. class JUCE_API Colour
  17561. {
  17562. public:
  17563. /** Creates a transparent black colour. */
  17564. Colour() throw();
  17565. /** Creates a copy of another Colour object. */
  17566. Colour (const Colour& other) throw();
  17567. /** Creates a colour from a 32-bit ARGB value.
  17568. The format of this number is:
  17569. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  17570. All components in the range 0x00 to 0xff.
  17571. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17572. @see getPixelARGB
  17573. */
  17574. explicit Colour (uint32 argb) throw();
  17575. /** Creates an opaque colour using 8-bit red, green and blue values */
  17576. Colour (uint8 red,
  17577. uint8 green,
  17578. uint8 blue) throw();
  17579. /** Creates an opaque colour using 8-bit red, green and blue values */
  17580. static const Colour fromRGB (uint8 red,
  17581. uint8 green,
  17582. uint8 blue) throw();
  17583. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17584. Colour (uint8 red,
  17585. uint8 green,
  17586. uint8 blue,
  17587. uint8 alpha) throw();
  17588. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17589. static const Colour fromRGBA (uint8 red,
  17590. uint8 green,
  17591. uint8 blue,
  17592. uint8 alpha) throw();
  17593. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  17594. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  17595. Values outside the valid range will be clipped.
  17596. */
  17597. Colour (uint8 red,
  17598. uint8 green,
  17599. uint8 blue,
  17600. float alpha) throw();
  17601. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  17602. static const Colour fromRGBAFloat (uint8 red,
  17603. uint8 green,
  17604. uint8 blue,
  17605. float alpha) throw();
  17606. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17607. The floating point values must be between 0.0 and 1.0.
  17608. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17609. Values outside the valid range will be clipped.
  17610. */
  17611. Colour (float hue,
  17612. float saturation,
  17613. float brightness,
  17614. uint8 alpha) throw();
  17615. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  17616. All values must be between 0.0 and 1.0.
  17617. Numbers outside the valid range will be clipped.
  17618. */
  17619. Colour (float hue,
  17620. float saturation,
  17621. float brightness,
  17622. float alpha) throw();
  17623. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17624. The floating point values must be between 0.0 and 1.0.
  17625. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17626. Values outside the valid range will be clipped.
  17627. */
  17628. static const Colour fromHSV (float hue,
  17629. float saturation,
  17630. float brightness,
  17631. float alpha) throw();
  17632. /** Destructor. */
  17633. ~Colour() throw();
  17634. /** Copies another Colour object. */
  17635. Colour& operator= (const Colour& other) throw();
  17636. /** Compares two colours. */
  17637. bool operator== (const Colour& other) const throw();
  17638. /** Compares two colours. */
  17639. bool operator!= (const Colour& other) const throw();
  17640. /** Returns the red component of this colour.
  17641. @returns a value between 0x00 and 0xff.
  17642. */
  17643. uint8 getRed() const throw() { return argb.getRed(); }
  17644. /** Returns the green component of this colour.
  17645. @returns a value between 0x00 and 0xff.
  17646. */
  17647. uint8 getGreen() const throw() { return argb.getGreen(); }
  17648. /** Returns the blue component of this colour.
  17649. @returns a value between 0x00 and 0xff.
  17650. */
  17651. uint8 getBlue() const throw() { return argb.getBlue(); }
  17652. /** Returns the red component of this colour as a floating point value.
  17653. @returns a value between 0.0 and 1.0
  17654. */
  17655. float getFloatRed() const throw();
  17656. /** Returns the green component of this colour as a floating point value.
  17657. @returns a value between 0.0 and 1.0
  17658. */
  17659. float getFloatGreen() const throw();
  17660. /** Returns the blue component of this colour as a floating point value.
  17661. @returns a value between 0.0 and 1.0
  17662. */
  17663. float getFloatBlue() const throw();
  17664. /** Returns a premultiplied ARGB pixel object that represents this colour.
  17665. */
  17666. const PixelARGB getPixelARGB() const throw();
  17667. /** Returns a 32-bit integer that represents this colour.
  17668. The format of this number is:
  17669. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  17670. */
  17671. uint32 getARGB() const throw();
  17672. /** Returns the colour's alpha (opacity).
  17673. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  17674. */
  17675. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  17676. /** Returns the colour's alpha (opacity) as a floating point value.
  17677. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  17678. */
  17679. float getFloatAlpha() const throw();
  17680. /** Returns true if this colour is completely opaque.
  17681. Equivalent to (getAlpha() == 0xff).
  17682. */
  17683. bool isOpaque() const throw();
  17684. /** Returns true if this colour is completely transparent.
  17685. Equivalent to (getAlpha() == 0x00).
  17686. */
  17687. bool isTransparent() const throw();
  17688. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17689. const Colour withAlpha (uint8 newAlpha) const throw();
  17690. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17691. const Colour withAlpha (float newAlpha) const throw();
  17692. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  17693. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  17694. */
  17695. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  17696. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  17697. If the foreground colour is semi-transparent, it is blended onto this colour
  17698. accordingly.
  17699. */
  17700. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  17701. /** Returns a colour that lies somewhere between this one and another.
  17702. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  17703. is 1.0, the result is 100% of the other colour.
  17704. */
  17705. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  17706. /** Returns the colour's hue component.
  17707. The value returned is in the range 0.0 to 1.0
  17708. */
  17709. float getHue() const throw();
  17710. /** Returns the colour's saturation component.
  17711. The value returned is in the range 0.0 to 1.0
  17712. */
  17713. float getSaturation() const throw();
  17714. /** Returns the colour's brightness component.
  17715. The value returned is in the range 0.0 to 1.0
  17716. */
  17717. float getBrightness() const throw();
  17718. /** Returns the colour's hue, saturation and brightness components all at once.
  17719. The values returned are in the range 0.0 to 1.0
  17720. */
  17721. void getHSB (float& hue,
  17722. float& saturation,
  17723. float& brightness) const throw();
  17724. /** Returns a copy of this colour with a different hue. */
  17725. const Colour withHue (float newHue) const throw();
  17726. /** Returns a copy of this colour with a different saturation. */
  17727. const Colour withSaturation (float newSaturation) const throw();
  17728. /** Returns a copy of this colour with a different brightness.
  17729. @see brighter, darker, withMultipliedBrightness
  17730. */
  17731. const Colour withBrightness (float newBrightness) const throw();
  17732. /** Returns a copy of this colour with it hue rotated.
  17733. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  17734. @see brighter, darker, withMultipliedBrightness
  17735. */
  17736. const Colour withRotatedHue (float amountToRotate) const throw();
  17737. /** Returns a copy of this colour with its saturation multiplied by the given value.
  17738. The new colour's saturation is (this->getSaturation() * multiplier)
  17739. (the result is clipped to legal limits).
  17740. */
  17741. const Colour withMultipliedSaturation (float multiplier) const throw();
  17742. /** Returns a copy of this colour with its brightness multiplied by the given value.
  17743. The new colour's saturation is (this->getBrightness() * multiplier)
  17744. (the result is clipped to legal limits).
  17745. */
  17746. const Colour withMultipliedBrightness (float amount) const throw();
  17747. /** Returns a brighter version of this colour.
  17748. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  17749. unchanged, and higher values make it brighter
  17750. @see withMultipliedBrightness
  17751. */
  17752. const Colour brighter (float amountBrighter = 0.4f) const throw();
  17753. /** Returns a darker version of this colour.
  17754. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  17755. unchanged, and higher values make it darker
  17756. @see withMultipliedBrightness
  17757. */
  17758. const Colour darker (float amountDarker = 0.4f) const throw();
  17759. /** Returns a colour that will be clearly visible against this colour.
  17760. The amount parameter indicates how contrasting the new colour should
  17761. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  17762. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  17763. return white; Colours::white.contrasting (1.0f) will return black, etc.
  17764. */
  17765. const Colour contrasting (float amount = 1.0f) const throw();
  17766. /** Returns a colour that contrasts against two colours.
  17767. Looks for a colour that contrasts with both of the colours passed-in.
  17768. Handy for things like choosing a highlight colour in text editors, etc.
  17769. */
  17770. static const Colour contrasting (const Colour& colour1,
  17771. const Colour& colour2) throw();
  17772. /** Returns an opaque shade of grey.
  17773. @param brightness the level of grey to return - 0 is black, 1.0 is white
  17774. */
  17775. static const Colour greyLevel (float brightness) throw();
  17776. /** Returns a stringified version of this colour.
  17777. The string can be turned back into a colour using the fromString() method.
  17778. */
  17779. const String toString() const;
  17780. /** Reads the colour from a string that was created with toString().
  17781. */
  17782. static const Colour fromString (const String& encodedColourString);
  17783. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  17784. const String toDisplayString (bool includeAlphaValue) const;
  17785. juce_UseDebuggingNewOperator
  17786. private:
  17787. PixelARGB argb;
  17788. };
  17789. #endif // __JUCE_COLOUR_JUCEHEADER__
  17790. /*** End of inlined file: juce_Colour.h ***/
  17791. /**
  17792. Contains a set of predefined named colours (mostly standard HTML colours)
  17793. @see Colour, Colours::greyLevel
  17794. */
  17795. class Colours
  17796. {
  17797. public:
  17798. static JUCE_API const Colour
  17799. transparentBlack, /**< ARGB = 0x00000000 */
  17800. transparentWhite, /**< ARGB = 0x00ffffff */
  17801. black, /**< ARGB = 0xff000000 */
  17802. white, /**< ARGB = 0xffffffff */
  17803. blue, /**< ARGB = 0xff0000ff */
  17804. grey, /**< ARGB = 0xff808080 */
  17805. green, /**< ARGB = 0xff008000 */
  17806. red, /**< ARGB = 0xffff0000 */
  17807. yellow, /**< ARGB = 0xffffff00 */
  17808. aliceblue, antiquewhite, aqua, aquamarine,
  17809. azure, beige, bisque, blanchedalmond,
  17810. blueviolet, brown, burlywood, cadetblue,
  17811. chartreuse, chocolate, coral, cornflowerblue,
  17812. cornsilk, crimson, cyan, darkblue,
  17813. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  17814. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  17815. darkorchid, darkred, darksalmon, darkseagreen,
  17816. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  17817. deeppink, deepskyblue, dimgrey, dodgerblue,
  17818. firebrick, floralwhite, forestgreen, fuchsia,
  17819. gainsboro, gold, goldenrod, greenyellow,
  17820. honeydew, hotpink, indianred, indigo,
  17821. ivory, khaki, lavender, lavenderblush,
  17822. lemonchiffon, lightblue, lightcoral, lightcyan,
  17823. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  17824. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  17825. lightsteelblue, lightyellow, lime, limegreen,
  17826. linen, magenta, maroon, mediumaquamarine,
  17827. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  17828. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  17829. midnightblue, mintcream, mistyrose, navajowhite,
  17830. navy, oldlace, olive, olivedrab,
  17831. orange, orangered, orchid, palegoldenrod,
  17832. palegreen, paleturquoise, palevioletred, papayawhip,
  17833. peachpuff, peru, pink, plum,
  17834. powderblue, purple, rosybrown, royalblue,
  17835. saddlebrown, salmon, sandybrown, seagreen,
  17836. seashell, sienna, silver, skyblue,
  17837. slateblue, slategrey, snow, springgreen,
  17838. steelblue, tan, teal, thistle,
  17839. tomato, turquoise, violet, wheat,
  17840. whitesmoke, yellowgreen;
  17841. /** Attempts to look up a string in the list of known colour names, and return
  17842. the appropriate colour.
  17843. A non-case-sensitive search is made of the list of predefined colours, and
  17844. if a match is found, that colour is returned. If no match is found, the
  17845. colour passed in as the defaultColour parameter is returned.
  17846. */
  17847. static JUCE_API const Colour findColourForName (const String& colourName,
  17848. const Colour& defaultColour);
  17849. private:
  17850. // this isn't a class you should ever instantiate - it's just here for the
  17851. // static values in it.
  17852. Colours();
  17853. Colours (const Colours&);
  17854. Colours& operator= (const Colours&);
  17855. };
  17856. #endif // __JUCE_COLOURS_JUCEHEADER__
  17857. /*** End of inlined file: juce_Colours.h ***/
  17858. /*** Start of inlined file: juce_ColourGradient.h ***/
  17859. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  17860. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  17861. /**
  17862. Describes the layout and colours that should be used to paint a colour gradient.
  17863. @see Graphics::setGradientFill
  17864. */
  17865. class JUCE_API ColourGradient
  17866. {
  17867. public:
  17868. /** Creates a gradient object.
  17869. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  17870. colour2 should be. In between them there's a gradient.
  17871. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  17872. its centre.
  17873. The alpha transparencies of the colours are used, so note that
  17874. if you blend from transparent to a solid colour, the RGB of the transparent
  17875. colour will become visible in parts of the gradient. e.g. blending
  17876. from Colour::transparentBlack to Colours::white will produce a
  17877. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  17878. will be white all the way across.
  17879. @see ColourGradient
  17880. */
  17881. ColourGradient (const Colour& colour1, float x1, float y1,
  17882. const Colour& colour2, float x2, float y2,
  17883. bool isRadial);
  17884. /** Creates an uninitialised gradient.
  17885. If you use this constructor instead of the other one, be sure to set all the
  17886. object's public member variables before using it!
  17887. */
  17888. ColourGradient() throw();
  17889. /** Destructor */
  17890. ~ColourGradient();
  17891. /** Removes any colours that have been added.
  17892. This will also remove any start and end colours, so the gradient won't work. You'll
  17893. need to add more colours with addColour().
  17894. */
  17895. void clearColours();
  17896. /** Adds a colour at a point along the length of the gradient.
  17897. This allows the gradient to go through a spectrum of colours, instead of just a
  17898. start and end colour.
  17899. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  17900. of the distance along the line between the two points
  17901. at which the colour should occur.
  17902. @param colour the colour that should be used at this point
  17903. @returns the index at which the new point was added
  17904. */
  17905. int addColour (double proportionAlongGradient,
  17906. const Colour& colour);
  17907. /** Removes one of the colours from the gradient. */
  17908. void removeColour (int index);
  17909. /** Multiplies the alpha value of all the colours by the given scale factor */
  17910. void multiplyOpacity (float multiplier) throw();
  17911. /** Returns the number of colour-stops that have been added. */
  17912. int getNumColours() const throw();
  17913. /** Returns the position along the length of the gradient of the colour with this index.
  17914. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  17915. */
  17916. double getColourPosition (int index) const throw();
  17917. /** Returns the colour that was added with a given index.
  17918. The index is from 0 to getNumColours() - 1.
  17919. */
  17920. const Colour getColour (int index) const throw();
  17921. /** Changes the colour at a given index.
  17922. The index is from 0 to getNumColours() - 1.
  17923. */
  17924. void setColour (int index, const Colour& newColour) throw();
  17925. /** Returns the an interpolated colour at any position along the gradient.
  17926. @param position the position along the gradient, between 0 and 1
  17927. */
  17928. const Colour getColourAtPosition (double position) const throw();
  17929. /** Creates a set of interpolated premultiplied ARGB values.
  17930. This will resize the HeapBlock, fill it with the colours, and will return the number of
  17931. colours that it added.
  17932. */
  17933. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  17934. /** Returns true if all colours are opaque. */
  17935. bool isOpaque() const throw();
  17936. /** Returns true if all colours are completely transparent. */
  17937. bool isInvisible() const throw();
  17938. Point<float> point1, point2;
  17939. /** If true, the gradient should be filled circularly, centred around
  17940. point1, with point2 defining a point on the circumference.
  17941. If false, the gradient is linear between the two points.
  17942. */
  17943. bool isRadial;
  17944. bool operator== (const ColourGradient& other) const throw();
  17945. bool operator!= (const ColourGradient& other) const throw();
  17946. juce_UseDebuggingNewOperator
  17947. private:
  17948. struct ColourPoint
  17949. {
  17950. ColourPoint() throw() {}
  17951. ColourPoint (const double position_, const Colour& colour_) throw()
  17952. : position (position_), colour (colour_)
  17953. {}
  17954. bool operator== (const ColourPoint& other) const throw() { return position == other.position && colour == other.colour; }
  17955. bool operator!= (const ColourPoint& other) const throw() { return position != other.position || colour != other.colour; }
  17956. double position;
  17957. Colour colour;
  17958. };
  17959. Array <ColourPoint> colours;
  17960. };
  17961. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  17962. /*** End of inlined file: juce_ColourGradient.h ***/
  17963. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  17964. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17965. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17966. /**
  17967. Defines the method used to postion some kind of rectangular object within
  17968. a rectangular viewport.
  17969. Although similar to Justification, this is more specific, and has some extra
  17970. options.
  17971. */
  17972. class JUCE_API RectanglePlacement
  17973. {
  17974. public:
  17975. /** Creates a RectanglePlacement object using a combination of flags. */
  17976. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  17977. /** Creates a copy of another RectanglePlacement object. */
  17978. RectanglePlacement (const RectanglePlacement& other) throw();
  17979. /** Copies another RectanglePlacement object. */
  17980. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  17981. /** Flag values that can be combined and used in the constructor. */
  17982. enum
  17983. {
  17984. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  17985. xLeft = 1,
  17986. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  17987. xRight = 2,
  17988. /** Indicates that the source should be placed in the centre between the left and right
  17989. sides of the available space. */
  17990. xMid = 4,
  17991. /** Indicates that the source's top edge should be aligned with the top edge of the
  17992. destination rectangle. */
  17993. yTop = 8,
  17994. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  17995. destination rectangle. */
  17996. yBottom = 16,
  17997. /** Indicates that the source should be placed in the centre between the top and bottom
  17998. sides of the available space. */
  17999. yMid = 32,
  18000. /** If this flag is set, then the source rectangle will be resized to completely fill
  18001. the destination rectangle, and all other flags are ignored.
  18002. */
  18003. stretchToFit = 64,
  18004. /** If this flag is set, then the source rectangle will be resized so that it is the
  18005. minimum size to completely fill the destination rectangle, without changing its
  18006. aspect ratio. This means that some of the source rectangle may fall outside
  18007. the destination.
  18008. If this flag is not set, the source will be given the maximum size at which none
  18009. of it falls outside the destination rectangle.
  18010. */
  18011. fillDestination = 128,
  18012. /** Indicates that the source rectangle can be reduced in size if required, but should
  18013. never be made larger than its original size.
  18014. */
  18015. onlyReduceInSize = 256,
  18016. /** Indicates that the source rectangle can be enlarged if required, but should
  18017. never be made smaller than its original size.
  18018. */
  18019. onlyIncreaseInSize = 512,
  18020. /** Indicates that the source rectangle's size should be left unchanged.
  18021. */
  18022. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  18023. /** A shorthand value that is equivalent to (xMid | yMid). */
  18024. centred = 4 + 32
  18025. };
  18026. /** Returns the raw flags that are set for this object. */
  18027. inline int getFlags() const throw() { return flags; }
  18028. /** Tests a set of flags for this object.
  18029. @returns true if any of the flags passed in are set on this object.
  18030. */
  18031. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  18032. /** Adjusts the position and size of a rectangle to fit it into a space.
  18033. The source rectangle co-ordinates will be adjusted so that they fit into
  18034. the destination rectangle based on this object's flags.
  18035. */
  18036. void applyTo (double& sourceX,
  18037. double& sourceY,
  18038. double& sourceW,
  18039. double& sourceH,
  18040. double destinationX,
  18041. double destinationY,
  18042. double destinationW,
  18043. double destinationH) const throw();
  18044. /** Returns the transform that should be applied to these source co-ordinates to fit them
  18045. into the destination rectangle using the current flags.
  18046. */
  18047. const AffineTransform getTransformToFit (float sourceX,
  18048. float sourceY,
  18049. float sourceW,
  18050. float sourceH,
  18051. float destinationX,
  18052. float destinationY,
  18053. float destinationW,
  18054. float destinationH) const throw();
  18055. private:
  18056. int flags;
  18057. };
  18058. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  18059. /*** End of inlined file: juce_RectanglePlacement.h ***/
  18060. class LowLevelGraphicsContext;
  18061. class Image;
  18062. class FillType;
  18063. class RectangleList;
  18064. /**
  18065. A graphics context, used for drawing a component or image.
  18066. When a Component needs painting, a Graphics context is passed to its
  18067. Component::paint() method, and this you then call methods within this
  18068. object to actually draw the component's content.
  18069. A Graphics can also be created from an image, to allow drawing directly onto
  18070. that image.
  18071. @see Component::paint
  18072. */
  18073. class JUCE_API Graphics
  18074. {
  18075. public:
  18076. /** Creates a Graphics object to draw directly onto the given image.
  18077. The graphics object that is created will be set up to draw onto the image,
  18078. with the context's clipping area being the entire size of the image, and its
  18079. origin being the image's origin. To draw into a subsection of an image, use the
  18080. reduceClipRegion() and setOrigin() methods.
  18081. Obviously you shouldn't delete the image before this context is deleted.
  18082. */
  18083. explicit Graphics (const Image& imageToDrawOnto);
  18084. /** Destructor. */
  18085. ~Graphics();
  18086. /** Changes the current drawing colour.
  18087. This sets the colour that will now be used for drawing operations - it also
  18088. sets the opacity to that of the colour passed-in.
  18089. If a brush is being used when this method is called, the brush will be deselected,
  18090. and any subsequent drawing will be done with a solid colour brush instead.
  18091. @see setOpacity
  18092. */
  18093. void setColour (const Colour& newColour);
  18094. /** Changes the opacity to use with the current colour.
  18095. If a solid colour is being used for drawing, this changes its opacity
  18096. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  18097. If a gradient is being used, this will have no effect on it.
  18098. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  18099. */
  18100. void setOpacity (const float newOpacity);
  18101. /** Sets the context to use a gradient for its fill pattern.
  18102. */
  18103. void setGradientFill (const ColourGradient& gradient);
  18104. /** Sets the context to use a tiled image pattern for filling.
  18105. Make sure that you don't delete this image while it's still being used by
  18106. this context!
  18107. */
  18108. void setTiledImageFill (const Image& imageToUse,
  18109. int anchorX, int anchorY,
  18110. float opacity);
  18111. /** Changes the current fill settings.
  18112. @see setColour, setGradientFill, setTiledImageFill
  18113. */
  18114. void setFillType (const FillType& newFill);
  18115. /** Changes the font to use for subsequent text-drawing functions.
  18116. Note there's also a setFont (float, int) method to quickly change the size and
  18117. style of the current font.
  18118. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  18119. */
  18120. void setFont (const Font& newFont);
  18121. /** Changes the size and style of the currently-selected font.
  18122. This is a convenient shortcut that changes the context's current font to a
  18123. different size or style. The typeface won't be changed.
  18124. @see Font
  18125. */
  18126. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  18127. /** Returns the currently selected font. */
  18128. const Font getCurrentFont() const;
  18129. /** Draws a one-line text string.
  18130. This will use the current colour (or brush) to fill the text. The font is the last
  18131. one specified by setFont().
  18132. @param text the string to draw
  18133. @param startX the position to draw the left-hand edge of the text
  18134. @param baselineY the position of the text's baseline
  18135. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  18136. */
  18137. void drawSingleLineText (const String& text,
  18138. int startX, int baselineY) const;
  18139. /** Draws text across multiple lines.
  18140. This will break the text onto a new line where there's a new-line or
  18141. carriage-return character, or at a word-boundary when the text becomes wider
  18142. than the size specified by the maximumLineWidth parameter.
  18143. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  18144. */
  18145. void drawMultiLineText (const String& text,
  18146. int startX, int baselineY,
  18147. int maximumLineWidth) const;
  18148. /** Renders a string of text as a vector path.
  18149. This allows a string to be transformed with an arbitrary AffineTransform and
  18150. rendered using the current colour/brush. It's much slower than the normal text methods
  18151. but more accurate.
  18152. @see setFont
  18153. */
  18154. void drawTextAsPath (const String& text,
  18155. const AffineTransform& transform) const;
  18156. /** Draws a line of text within a specified rectangle.
  18157. The text will be positioned within the rectangle based on the justification
  18158. flags passed-in. If the string is too long to fit inside the rectangle, it will
  18159. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  18160. flag is true).
  18161. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  18162. */
  18163. void drawText (const String& text,
  18164. int x, int y, int width, int height,
  18165. const Justification& justificationType,
  18166. bool useEllipsesIfTooBig) const;
  18167. /** Tries to draw a text string inside a given space.
  18168. This does its best to make the given text readable within the specified rectangle,
  18169. so it useful for labelling things.
  18170. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  18171. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  18172. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  18173. it's been truncated.
  18174. A Justification parameter lets you specify how the text is laid out within the rectangle,
  18175. both horizontally and vertically.
  18176. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  18177. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  18178. can set this value to 1.0f.
  18179. @see GlyphArrangement::addFittedText
  18180. */
  18181. void drawFittedText (const String& text,
  18182. int x, int y, int width, int height,
  18183. const Justification& justificationFlags,
  18184. int maximumNumberOfLines,
  18185. float minimumHorizontalScale = 0.7f) const;
  18186. /** Fills the context's entire clip region with the current colour or brush.
  18187. (See also the fillAll (const Colour&) method which is a quick way of filling
  18188. it with a given colour).
  18189. */
  18190. void fillAll() const;
  18191. /** Fills the context's entire clip region with a given colour.
  18192. This leaves the context's current colour and brush unchanged, it just
  18193. uses the specified colour temporarily.
  18194. */
  18195. void fillAll (const Colour& colourToUse) const;
  18196. /** Fills a rectangle with the current colour or brush.
  18197. @see drawRect, fillRoundedRectangle
  18198. */
  18199. void fillRect (int x, int y, int width, int height) const;
  18200. /** Fills a rectangle with the current colour or brush. */
  18201. void fillRect (const Rectangle<int>& rectangle) const;
  18202. /** Fills a rectangle with the current colour or brush.
  18203. This uses sub-pixel positioning so is slower than the fillRect method which
  18204. takes integer co-ordinates.
  18205. */
  18206. void fillRect (float x, float y, float width, float height) const;
  18207. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18208. @see drawRoundedRectangle, Path::addRoundedRectangle
  18209. */
  18210. void fillRoundedRectangle (float x, float y, float width, float height,
  18211. float cornerSize) const;
  18212. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18213. @see drawRoundedRectangle, Path::addRoundedRectangle
  18214. */
  18215. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  18216. float cornerSize) const;
  18217. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  18218. */
  18219. void fillCheckerBoard (const Rectangle<int>& area,
  18220. int checkWidth, int checkHeight,
  18221. const Colour& colour1, const Colour& colour2) const;
  18222. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18223. The lines are drawn inside the given rectangle, and greater line thicknesses
  18224. extend inwards.
  18225. @see fillRect
  18226. */
  18227. void drawRect (int x, int y, int width, int height,
  18228. int lineThickness = 1) const;
  18229. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18230. The lines are drawn inside the given rectangle, and greater line thicknesses
  18231. extend inwards.
  18232. @see fillRect
  18233. */
  18234. void drawRect (float x, float y, float width, float height,
  18235. float lineThickness = 1.0f) const;
  18236. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18237. The lines are drawn inside the given rectangle, and greater line thicknesses
  18238. extend inwards.
  18239. @see fillRect
  18240. */
  18241. void drawRect (const Rectangle<int>& rectangle,
  18242. int lineThickness = 1) const;
  18243. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18244. @see fillRoundedRectangle, Path::addRoundedRectangle
  18245. */
  18246. void drawRoundedRectangle (float x, float y, float width, float height,
  18247. float cornerSize, float lineThickness) const;
  18248. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18249. @see fillRoundedRectangle, Path::addRoundedRectangle
  18250. */
  18251. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  18252. float cornerSize, float lineThickness) const;
  18253. /** Draws a 3D raised (or indented) bevel using two colours.
  18254. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  18255. extend inwards.
  18256. The top-left colour is used for the top- and left-hand edges of the
  18257. bevel; the bottom-right colour is used for the bottom- and right-hand
  18258. edges.
  18259. If useGradient is true, then the bevel fades out to make it look more curved
  18260. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  18261. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  18262. the centre edges are sharp and it fades towards the outside.
  18263. */
  18264. void drawBevel (int x, int y, int width, int height,
  18265. int bevelThickness,
  18266. const Colour& topLeftColour = Colours::white,
  18267. const Colour& bottomRightColour = Colours::black,
  18268. bool useGradient = true,
  18269. bool sharpEdgeOnOutside = true) const;
  18270. /** Draws a pixel using the current colour or brush.
  18271. */
  18272. void setPixel (int x, int y) const;
  18273. /** Fills an ellipse with the current colour or brush.
  18274. The ellipse is drawn to fit inside the given rectangle.
  18275. @see drawEllipse, Path::addEllipse
  18276. */
  18277. void fillEllipse (float x, float y, float width, float height) const;
  18278. /** Draws an elliptical stroke using the current colour or brush.
  18279. @see fillEllipse, Path::addEllipse
  18280. */
  18281. void drawEllipse (float x, float y, float width, float height,
  18282. float lineThickness) const;
  18283. /** Draws a line between two points.
  18284. The line is 1 pixel wide and drawn with the current colour or brush.
  18285. */
  18286. void drawLine (float startX, float startY, float endX, float endY) const;
  18287. /** Draws a line between two points with a given thickness.
  18288. @see Path::addLineSegment
  18289. */
  18290. void drawLine (float startX, float startY, float endX, float endY,
  18291. float lineThickness) const;
  18292. /** Draws a line between two points.
  18293. The line is 1 pixel wide and drawn with the current colour or brush.
  18294. */
  18295. void drawLine (const Line<float>& line) const;
  18296. /** Draws a line between two points with a given thickness.
  18297. @see Path::addLineSegment
  18298. */
  18299. void drawLine (const Line<float>& line, float lineThickness) const;
  18300. /** Draws a dashed line using a custom set of dash-lengths.
  18301. @param startX the line's start x co-ordinate
  18302. @param startY the line's start y co-ordinate
  18303. @param endX the line's end x co-ordinate
  18304. @param endY the line's end y co-ordinate
  18305. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  18306. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  18307. draw 6 pixels, skip 7 pixels, and then repeat.
  18308. @param numDashLengths the number of elements in the array (this must be an even number).
  18309. @param lineThickness the thickness of the line to draw
  18310. @see PathStrokeType::createDashedStroke
  18311. */
  18312. void drawDashedLine (float startX, float startY,
  18313. float endX, float endY,
  18314. const float* dashLengths, int numDashLengths,
  18315. float lineThickness = 1.0f) const;
  18316. /** Draws a vertical line of pixels at a given x position.
  18317. The x position is an integer, but the top and bottom of the line can be sub-pixel
  18318. positions, and these will be anti-aliased if necessary.
  18319. */
  18320. void drawVerticalLine (int x, float top, float bottom) const;
  18321. /** Draws a horizontal line of pixels at a given y position.
  18322. The y position is an integer, but the left and right ends of the line can be sub-pixel
  18323. positions, and these will be anti-aliased if necessary.
  18324. */
  18325. void drawHorizontalLine (int y, float left, float right) const;
  18326. /** Fills a path using the currently selected colour or brush.
  18327. */
  18328. void fillPath (const Path& path,
  18329. const AffineTransform& transform = AffineTransform::identity) const;
  18330. /** Draws a path's outline using the currently selected colour or brush.
  18331. */
  18332. void strokePath (const Path& path,
  18333. const PathStrokeType& strokeType,
  18334. const AffineTransform& transform = AffineTransform::identity) const;
  18335. /** Draws a line with an arrowhead at its end.
  18336. @param line the line to draw
  18337. @param lineThickness the thickness of the line
  18338. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  18339. @param arrowheadLength the length of the arrow head (along the length of the line)
  18340. */
  18341. void drawArrow (const Line<float>& line,
  18342. float lineThickness,
  18343. float arrowheadWidth,
  18344. float arrowheadLength) const;
  18345. /** Types of rendering quality that can be specified when drawing images.
  18346. @see blendImage, Graphics::setImageResamplingQuality
  18347. */
  18348. enum ResamplingQuality
  18349. {
  18350. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  18351. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  18352. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  18353. };
  18354. /** Changes the quality that will be used when resampling images.
  18355. By default a Graphics object will be set to mediumRenderingQuality.
  18356. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  18357. */
  18358. void setImageResamplingQuality (const ResamplingQuality newQuality);
  18359. /** Draws an image.
  18360. This will draw the whole of an image, positioning its top-left corner at the
  18361. given co-ordinates, and keeping its size the same. This is the simplest image
  18362. drawing method - the others give more control over the scaling and clipping
  18363. of the images.
  18364. Images are composited using the context's current opacity, so if you
  18365. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18366. (or setColour() with an opaque colour) before drawing images.
  18367. */
  18368. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  18369. bool fillAlphaChannelWithCurrentBrush = false) const;
  18370. /** Draws part of an image, rescaling it to fit in a given target region.
  18371. The specified area of the source image is rescaled and drawn to fill the
  18372. specifed destination rectangle.
  18373. Images are composited using the context's current opacity, so if you
  18374. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18375. (or setColour() with an opaque colour) before drawing images.
  18376. @param imageToDraw the image to overlay
  18377. @param destX the left of the destination rectangle
  18378. @param destY the top of the destination rectangle
  18379. @param destWidth the width of the destination rectangle
  18380. @param destHeight the height of the destination rectangle
  18381. @param sourceX the left of the rectangle to copy from the source image
  18382. @param sourceY the top of the rectangle to copy from the source image
  18383. @param sourceWidth the width of the rectangle to copy from the source image
  18384. @param sourceHeight the height of the rectangle to copy from the source image
  18385. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  18386. the source image's alpha channel is used as a mask with
  18387. which to fill the destination using the current colour
  18388. or brush. (If the source is has no alpha channel, then
  18389. it will just fill the target with a solid rectangle)
  18390. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  18391. */
  18392. void drawImage (const Image& imageToDraw,
  18393. int destX, int destY, int destWidth, int destHeight,
  18394. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  18395. bool fillAlphaChannelWithCurrentBrush = false) const;
  18396. /** Draws part of an image, having applied an affine transform to it.
  18397. This lets you throw the image around in some wacky ways, rotate it, shear,
  18398. scale it, etc.
  18399. A subregion is specified within the source image, and all transformations
  18400. will be treated as relative to the origin of this sub-region. So, for example if
  18401. your subregion is (50, 50, 100, 100), and your transform is a translation of (20, 20),
  18402. the resulting pixel drawn at (20, 20) in the destination context is from (50, 50) in
  18403. your image. If you want to use the whole image, then Image::getBounds() returns a
  18404. suitable rectangle to use as the imageSubRegion parameter.
  18405. Images are composited using the context's current opacity, so if you
  18406. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18407. (or setColour() with an opaque colour) before drawing images.
  18408. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  18409. are ignored and it is filled with the current brush, masked by its alpha channel.
  18410. @see setImageResamplingQuality, drawImage
  18411. */
  18412. void drawImageTransformed (const Image& imageToDraw,
  18413. const Rectangle<int>& imageSubRegion,
  18414. const AffineTransform& transform,
  18415. bool fillAlphaChannelWithCurrentBrush = false) const;
  18416. /** Draws an image to fit within a designated rectangle.
  18417. If the image is too big or too small for the space, it will be rescaled
  18418. to fit as nicely as it can do without affecting its aspect ratio. It will
  18419. then be placed within the target rectangle according to the justification flags
  18420. specified.
  18421. @param imageToDraw the source image to draw
  18422. @param destX top-left of the target rectangle to fit it into
  18423. @param destY top-left of the target rectangle to fit it into
  18424. @param destWidth size of the target rectangle to fit the image into
  18425. @param destHeight size of the target rectangle to fit the image into
  18426. @param placementWithinTarget this specifies how the image should be positioned
  18427. within the target rectangle - see the RectanglePlacement
  18428. class for more details about this.
  18429. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  18430. alpha channel will be used as a mask with which to
  18431. draw with the current brush or colour. This is
  18432. similar to fillAlphaMap(), and see also drawImage()
  18433. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  18434. */
  18435. void drawImageWithin (const Image& imageToDraw,
  18436. int destX, int destY, int destWidth, int destHeight,
  18437. const RectanglePlacement& placementWithinTarget,
  18438. bool fillAlphaChannelWithCurrentBrush = false) const;
  18439. /** Returns the position of the bounding box for the current clipping region.
  18440. @see getClipRegion, clipRegionIntersects
  18441. */
  18442. const Rectangle<int> getClipBounds() const;
  18443. /** Checks whether a rectangle overlaps the context's clipping region.
  18444. If this returns false, no part of the given area can be drawn onto, so this
  18445. method can be used to optimise a component's paint() method, by letting it
  18446. avoid drawing complex objects that aren't within the region being repainted.
  18447. */
  18448. bool clipRegionIntersects (const Rectangle<int>& area) const;
  18449. /** Intersects the current clipping region with another region.
  18450. @returns true if the resulting clipping region is non-zero in size
  18451. @see setOrigin, clipRegionIntersects
  18452. */
  18453. bool reduceClipRegion (int x, int y, int width, int height);
  18454. /** Intersects the current clipping region with a rectangle list region.
  18455. @returns true if the resulting clipping region is non-zero in size
  18456. @see setOrigin, clipRegionIntersects
  18457. */
  18458. bool reduceClipRegion (const RectangleList& clipRegion);
  18459. /** Intersects the current clipping region with a path.
  18460. @returns true if the resulting clipping region is non-zero in size
  18461. @see reduceClipRegion
  18462. */
  18463. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  18464. /** Intersects the current clipping region with an image's alpha-channel.
  18465. The current clipping path is intersected with the area covered by this image's
  18466. alpha-channel, after the image has been transformed by the specified matrix.
  18467. @param image the image whose alpha-channel should be used. If the image doesn't
  18468. have an alpha-channel, it is treated as entirely opaque.
  18469. @param sourceClipRegion a subsection of the image that should be used. To use the
  18470. entire image, just pass a rectangle of bounds
  18471. (0, 0, image.getWidth(), image.getHeight()).
  18472. @param transform a matrix to apply to the image
  18473. @returns true if the resulting clipping region is non-zero in size
  18474. @see reduceClipRegion
  18475. */
  18476. bool reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion,
  18477. const AffineTransform& transform);
  18478. /** Excludes a rectangle to stop it being drawn into. */
  18479. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  18480. /** Returns true if no drawing can be done because the clip region is zero. */
  18481. bool isClipEmpty() const;
  18482. /** Saves the current graphics state on an internal stack.
  18483. To restore the state, use restoreState().
  18484. */
  18485. void saveState();
  18486. /** Restores a graphics state that was previously saved with saveState().
  18487. */
  18488. void restoreState();
  18489. /** Moves the position of the context's origin.
  18490. This changes the position that the context considers to be (0, 0) to
  18491. the specified position.
  18492. So if you call setOrigin (100, 100), then the position that was previously
  18493. referred to as (100, 100) will subsequently be considered to be (0, 0).
  18494. @see reduceClipRegion
  18495. */
  18496. void setOrigin (int newOriginX, int newOriginY);
  18497. /** Resets the current colour, brush, and font to default settings. */
  18498. void resetToDefaultState();
  18499. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  18500. bool isVectorDevice() const;
  18501. juce_UseDebuggingNewOperator
  18502. /** Create a graphics that uses a given low-level renderer.
  18503. For internal use only.
  18504. NB. The context will NOT be deleted by this object when it is deleted.
  18505. */
  18506. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  18507. /** @internal */
  18508. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  18509. private:
  18510. LowLevelGraphicsContext* const context;
  18511. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  18512. bool saveStatePending;
  18513. void saveStateIfPending();
  18514. Graphics (const Graphics&);
  18515. Graphics& operator= (const Graphics& other);
  18516. };
  18517. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  18518. /*** End of inlined file: juce_Graphics.h ***/
  18519. /**
  18520. A graphical effect filter that can be applied to components.
  18521. An ImageEffectFilter can be applied to the image that a component
  18522. paints before it hits the screen.
  18523. This is used for adding effects like shadows, blurs, etc.
  18524. @see Component::setComponentEffect
  18525. */
  18526. class JUCE_API ImageEffectFilter
  18527. {
  18528. public:
  18529. /** Overridden to render the effect.
  18530. The implementation of this method must use the image that is passed in
  18531. as its source, and should render its output to the graphics context passed in.
  18532. @param sourceImage the image that the source component has just rendered with
  18533. its paint() method. The image may or may not have an alpha
  18534. channel, depending on whether the component is opaque.
  18535. @param destContext the graphics context to use to draw the resultant image.
  18536. */
  18537. virtual void applyEffect (Image& sourceImage,
  18538. Graphics& destContext) = 0;
  18539. /** Destructor. */
  18540. virtual ~ImageEffectFilter() {}
  18541. };
  18542. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18543. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  18544. /*** Start of inlined file: juce_Image.h ***/
  18545. #ifndef __JUCE_IMAGE_JUCEHEADER__
  18546. #define __JUCE_IMAGE_JUCEHEADER__
  18547. /**
  18548. Holds a fixed-size bitmap.
  18549. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  18550. To draw into an image, create a Graphics object for it.
  18551. e.g. @code
  18552. // create a transparent 500x500 image..
  18553. Image myImage (Image::RGB, 500, 500, true);
  18554. Graphics g (myImage);
  18555. g.setColour (Colours::red);
  18556. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  18557. @endcode
  18558. Other useful ways to create an image are with the ImageCache class, or the
  18559. ImageFileFormat, which provides a way to load common image files.
  18560. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  18561. */
  18562. class JUCE_API Image
  18563. {
  18564. public:
  18565. /**
  18566. */
  18567. enum PixelFormat
  18568. {
  18569. UnknownFormat,
  18570. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  18571. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  18572. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  18573. };
  18574. /**
  18575. */
  18576. enum ImageType
  18577. {
  18578. SoftwareImage = 0,
  18579. NativeImage
  18580. };
  18581. /** Creates a null image. */
  18582. Image();
  18583. /** Creates an image with a specified size and format.
  18584. @param format the number of colour channels in the image
  18585. @param imageWidth the desired width of the image, in pixels - this value must be
  18586. greater than zero (otherwise a width of 1 will be used)
  18587. @param imageHeight the desired width of the image, in pixels - this value must be
  18588. greater than zero (otherwise a height of 1 will be used)
  18589. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  18590. or transparent black (if it's ARGB). If false, the image may contain
  18591. junk initially, so you need to make sure you overwrite it thoroughly.
  18592. @param type the type of image - this lets you specify whether you want a purely
  18593. memory-based image, or one that may be managed by the OS if possible.
  18594. */
  18595. Image (PixelFormat format,
  18596. int imageWidth,
  18597. int imageHeight,
  18598. bool clearImage,
  18599. ImageType type = NativeImage);
  18600. /** Creates a shared reference to another image.
  18601. This won't create a duplicate of the image - when Image objects are copied, they simply
  18602. point to the same shared image data. To make sure that an Image object has its own unique,
  18603. unshared internal data, call duplicateIfShared().
  18604. */
  18605. Image (const Image& other);
  18606. /** Makes this image refer to the same underlying image as another object.
  18607. This won't create a duplicate of the image - when Image objects are copied, they simply
  18608. point to the same shared image data. To make sure that an Image object has its own unique,
  18609. unshared internal data, call duplicateIfShared().
  18610. */
  18611. Image& operator= (const Image&);
  18612. /** Destructor. */
  18613. ~Image();
  18614. /** Returns true if the two images are referring to the same internal, shared image. */
  18615. bool operator== (const Image& other) const throw() { return image == other.image; }
  18616. /** Returns true if the two images are not referring to the same internal, shared image. */
  18617. bool operator!= (const Image& other) const throw() { return image != other.image; }
  18618. /** Returns true if this image isn't null.
  18619. If you create an Image with the default constructor, it has no size or content, and is null
  18620. until you reassign it to an Image which contains some actual data.
  18621. The isNull() method is the opposite of isValid().
  18622. @see isNull
  18623. */
  18624. inline bool isValid() const throw() { return image != 0; }
  18625. /** Returns true if this image is not valid.
  18626. If you create an Image with the default constructor, it has no size or content, and is null
  18627. until you reassign it to an Image which contains some actual data.
  18628. The isNull() method is the opposite of isValid().
  18629. @see isValid
  18630. */
  18631. inline bool isNull() const throw() { return image == 0; }
  18632. /** Returns the image's width (in pixels). */
  18633. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  18634. /** Returns the image's height (in pixels). */
  18635. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  18636. /** Returns a rectangle with the same size as this image.
  18637. The rectangle's origin is always (0, 0).
  18638. */
  18639. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  18640. /** Returns the image's pixel format. */
  18641. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  18642. /** True if the image's format is ARGB. */
  18643. bool isARGB() const throw() { return getFormat() == ARGB; }
  18644. /** True if the image's format is RGB. */
  18645. bool isRGB() const throw() { return getFormat() == RGB; }
  18646. /** True if the image's format is a single-channel alpha map. */
  18647. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  18648. /** True if the image contains an alpha-channel. */
  18649. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  18650. /** Clears a section of the image with a given colour.
  18651. This won't do any alpha-blending - it just sets all pixels in the image to
  18652. the given colour (which may be non-opaque if the image has an alpha channel).
  18653. */
  18654. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  18655. /** Returns a rescaled version of this image.
  18656. A new image is returned which is a copy of this one, rescaled to the given size.
  18657. Note that if the new size is identical to the existing image, this will just return
  18658. a reference to the original image, and won't actually create a duplicate.
  18659. */
  18660. const Image rescaled (int newWidth, int newHeight,
  18661. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  18662. /** Returns a version of this image with a different image format.
  18663. A new image is returned which has been converted to the specified format.
  18664. Note that if the new format is no different to the current one, this will just return
  18665. a reference to the original image, and won't actually create a copy.
  18666. */
  18667. const Image convertedToFormat (PixelFormat newFormat) const;
  18668. /** Makes sure that no other Image objects share the same underlying data as this one.
  18669. If no other Image objects refer to the same shared data as this one, this method has no
  18670. effect. But if there are other references to the data, this will create a new copy of
  18671. the data internally.
  18672. Call this if you want to draw onto the image, but want to make sure that this doesn't
  18673. affect any other code that may be sharing the same data.
  18674. @see getReferenceCount
  18675. */
  18676. void duplicateIfShared();
  18677. /** Returns the colour of one of the pixels in the image.
  18678. If the co-ordinates given are beyond the image's boundaries, this will
  18679. return Colours::transparentBlack.
  18680. @see setPixelAt, Image::BitmapData::getPixelColour
  18681. */
  18682. const Colour getPixelAt (int x, int y) const;
  18683. /** Sets the colour of one of the image's pixels.
  18684. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  18685. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  18686. with the given one. The colour's opacity will be ignored if this image doesn't have
  18687. an alpha-channel.
  18688. @see getPixelAt, Image::BitmapData::setPixelColour
  18689. */
  18690. void setPixelAt (int x, int y, const Colour& colour);
  18691. /** Changes the opacity of a pixel.
  18692. This only has an effect if the image has an alpha channel and if the
  18693. given co-ordinates are inside the image's boundary.
  18694. The multiplier must be in the range 0 to 1.0, and the current alpha
  18695. at the given co-ordinates will be multiplied by this value.
  18696. @see setPixelAt
  18697. */
  18698. void multiplyAlphaAt (int x, int y, float multiplier);
  18699. /** Changes the overall opacity of the image.
  18700. This will multiply the alpha value of each pixel in the image by the given
  18701. amount (limiting the resulting alpha values between 0 and 255). This allows
  18702. you to make an image more or less transparent.
  18703. If the image doesn't have an alpha channel, this won't have any effect.
  18704. */
  18705. void multiplyAllAlphas (float amountToMultiplyBy);
  18706. /** Changes all the colours to be shades of grey, based on their current luminosity.
  18707. */
  18708. void desaturate();
  18709. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  18710. You should only use this class as a last resort - messing about with the internals of
  18711. an image is only recommended for people who really know what they're doing!
  18712. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  18713. hanging around while the image is being used elsewhere.
  18714. Depending on the way the image class is implemented, this may create a temporary buffer
  18715. which is copied back to the image when the object is deleted, or it may just get a pointer
  18716. directly into the image's raw data.
  18717. You can use the stride and data values in this class directly, but don't alter them!
  18718. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  18719. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  18720. */
  18721. class BitmapData
  18722. {
  18723. public:
  18724. BitmapData (Image& image, int x, int y, int w, int h, bool needsToBeWritable);
  18725. BitmapData (const Image& image, int x, int y, int w, int h);
  18726. ~BitmapData();
  18727. /** Returns a pointer to the start of a line in the image.
  18728. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  18729. sure it's not out-of-range.
  18730. */
  18731. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  18732. /** Returns a pointer to a pixel in the image.
  18733. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  18734. not out-of-range.
  18735. */
  18736. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  18737. /** Returns the colour of a given pixel.
  18738. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18739. repsonsibility to make sure they're within the image's size.
  18740. */
  18741. const Colour getPixelColour (int x, int y) const throw();
  18742. /** Sets the colour of a given pixel.
  18743. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18744. repsonsibility to make sure they're within the image's size.
  18745. */
  18746. void setPixelColour (int x, int y, const Colour& colour) const throw();
  18747. uint8* data;
  18748. const PixelFormat pixelFormat;
  18749. int lineStride, pixelStride, width, height;
  18750. private:
  18751. BitmapData (const BitmapData&);
  18752. BitmapData& operator= (const BitmapData&);
  18753. };
  18754. /** Copies some pixel values to a rectangle of the image.
  18755. The format of the pixel data must match that of the image itself, and the
  18756. rectangle supplied must be within the image's bounds.
  18757. */
  18758. void setPixelData (int destX, int destY, int destW, int destH,
  18759. const uint8* sourcePixelData, int sourceLineStride);
  18760. /** Copies a section of the image to somewhere else within itself. */
  18761. void moveImageSection (int destX, int destY,
  18762. int sourceX, int sourceY,
  18763. int width, int height);
  18764. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  18765. of the image.
  18766. @param result the list that will have the area added to it
  18767. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  18768. above this level will be considered opaque
  18769. */
  18770. void createSolidAreaMask (RectangleList& result,
  18771. float alphaThreshold = 0.5f) const;
  18772. /** Returns a user-specified data item that was set with setTag().
  18773. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18774. image. The value is shared between all Image object that are referring to the
  18775. same underlying image data object.
  18776. */
  18777. const var getTag() const;
  18778. /** Attaches a user-specified data item to this image, which can be retrieved using getTag().
  18779. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18780. image. The value is shared between all Image object that are referring to the
  18781. same underlying image data object.
  18782. Note that if this Image is null, this method will fail to store the data.
  18783. */
  18784. void setTag (const var& newTag);
  18785. /** Creates a context suitable for drawing onto this image.
  18786. Don't call this method directly! It's used internally by the Graphics class.
  18787. */
  18788. LowLevelGraphicsContext* createLowLevelContext() const;
  18789. /** Returns the number of Image objects which are currently referring to the same internal
  18790. shared image data.
  18791. @see duplicateIfShared
  18792. */
  18793. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  18794. /** This is a base class for task-specific types of image.
  18795. Don't use this class directly! It's used internally by the Image class.
  18796. */
  18797. class SharedImage : public ReferenceCountedObject
  18798. {
  18799. public:
  18800. SharedImage (PixelFormat format, int width, int height);
  18801. ~SharedImage();
  18802. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  18803. virtual SharedImage* clone() = 0;
  18804. virtual ImageType getType() const = 0;
  18805. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  18806. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  18807. protected:
  18808. friend class Image;
  18809. friend class Image::BitmapData;
  18810. const PixelFormat format;
  18811. const int width, height;
  18812. int pixelStride, lineStride;
  18813. uint8* imageData;
  18814. var userTag;
  18815. uint8* getPixelData (int x, int y) const throw();
  18816. SharedImage (const SharedImage&);
  18817. SharedImage& operator= (const SharedImage&);
  18818. };
  18819. /** @internal */
  18820. SharedImage* getSharedImage() const throw() { return image; }
  18821. /** @internal */
  18822. explicit Image (SharedImage* instance);
  18823. juce_UseDebuggingNewOperator
  18824. private:
  18825. ReferenceCountedObjectPtr<SharedImage> image;
  18826. };
  18827. #endif // __JUCE_IMAGE_JUCEHEADER__
  18828. /*** End of inlined file: juce_Image.h ***/
  18829. /*** Start of inlined file: juce_RectangleList.h ***/
  18830. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  18831. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  18832. /**
  18833. Maintains a set of rectangles as a complex region.
  18834. This class allows a set of rectangles to be treated as a solid shape, and can
  18835. add and remove rectangular sections of it, and simplify overlapping or
  18836. adjacent rectangles.
  18837. @see Rectangle
  18838. */
  18839. class JUCE_API RectangleList
  18840. {
  18841. public:
  18842. /** Creates an empty RectangleList */
  18843. RectangleList() throw();
  18844. /** Creates a copy of another list */
  18845. RectangleList (const RectangleList& other);
  18846. /** Creates a list containing just one rectangle. */
  18847. RectangleList (const Rectangle<int>& rect);
  18848. /** Copies this list from another one. */
  18849. RectangleList& operator= (const RectangleList& other);
  18850. /** Destructor. */
  18851. ~RectangleList();
  18852. /** Returns true if the region is empty. */
  18853. bool isEmpty() const throw();
  18854. /** Returns the number of rectangles in the list. */
  18855. int getNumRectangles() const throw() { return rects.size(); }
  18856. /** Returns one of the rectangles at a particular index.
  18857. @returns the rectangle at the index, or an empty rectangle if the
  18858. index is out-of-range.
  18859. */
  18860. const Rectangle<int> getRectangle (int index) const throw();
  18861. /** Removes all rectangles to leave an empty region. */
  18862. void clear();
  18863. /** Merges a new rectangle into the list.
  18864. The rectangle being added will first be clipped to remove any parts of it
  18865. that overlap existing rectangles in the list.
  18866. */
  18867. void add (int x, int y, int width, int height);
  18868. /** Merges a new rectangle into the list.
  18869. The rectangle being added will first be clipped to remove any parts of it
  18870. that overlap existing rectangles in the list, and adjacent rectangles will be
  18871. merged into it.
  18872. */
  18873. void add (const Rectangle<int>& rect);
  18874. /** Dumbly adds a rectangle to the list without checking for overlaps.
  18875. This simply adds the rectangle to the end, it doesn't merge it or remove
  18876. any overlapping bits.
  18877. */
  18878. void addWithoutMerging (const Rectangle<int>& rect);
  18879. /** Merges another rectangle list into this one.
  18880. Any overlaps between the two lists will be clipped, so that the result is
  18881. the union of both lists.
  18882. */
  18883. void add (const RectangleList& other);
  18884. /** Removes a rectangular region from the list.
  18885. Any rectangles in the list which overlap this will be clipped and subdivided
  18886. if necessary.
  18887. */
  18888. void subtract (const Rectangle<int>& rect);
  18889. /** Removes all areas in another RectangleList from this one.
  18890. Any rectangles in the list which overlap this will be clipped and subdivided
  18891. if necessary.
  18892. @returns true if the resulting list is non-empty.
  18893. */
  18894. bool subtract (const RectangleList& otherList);
  18895. /** Removes any areas of the region that lie outside a given rectangle.
  18896. Any rectangles in the list which overlap this will be clipped and subdivided
  18897. if necessary.
  18898. Returns true if the resulting region is not empty, false if it is empty.
  18899. @see getIntersectionWith
  18900. */
  18901. bool clipTo (const Rectangle<int>& rect);
  18902. /** Removes any areas of the region that lie outside a given rectangle list.
  18903. Any rectangles in this object which overlap the specified list will be clipped
  18904. and subdivided if necessary.
  18905. Returns true if the resulting region is not empty, false if it is empty.
  18906. @see getIntersectionWith
  18907. */
  18908. bool clipTo (const RectangleList& other);
  18909. /** Creates a region which is the result of clipping this one to a given rectangle.
  18910. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  18911. resulting region into the list whose reference is passed-in.
  18912. Returns true if the resulting region is not empty, false if it is empty.
  18913. @see clipTo
  18914. */
  18915. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  18916. /** Swaps the contents of this and another list.
  18917. This swaps their internal pointers, so is hugely faster than using copy-by-value
  18918. to swap them.
  18919. */
  18920. void swapWith (RectangleList& otherList) throw();
  18921. /** Checks whether the region contains a given point.
  18922. @returns true if the point lies within one of the rectangles in the list
  18923. */
  18924. bool containsPoint (int x, int y) const throw();
  18925. /** Checks whether the region contains the whole of a given rectangle.
  18926. @returns true all parts of the rectangle passed in lie within the region
  18927. defined by this object
  18928. @see intersectsRectangle, containsPoint
  18929. */
  18930. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  18931. /** Checks whether the region contains any part of a given rectangle.
  18932. @returns true if any part of the rectangle passed in lies within the region
  18933. defined by this object
  18934. @see containsRectangle
  18935. */
  18936. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  18937. /** Checks whether this region intersects any part of another one.
  18938. @see intersectsRectangle
  18939. */
  18940. bool intersects (const RectangleList& other) const throw();
  18941. /** Returns the smallest rectangle that can enclose the whole of this region. */
  18942. const Rectangle<int> getBounds() const throw();
  18943. /** Optimises the list into a minimum number of constituent rectangles.
  18944. This will try to combine any adjacent rectangles into larger ones where
  18945. possible, to simplify lists that might have been fragmented by repeated
  18946. add/subtract calls.
  18947. */
  18948. void consolidate();
  18949. /** Adds an x and y value to all the co-ordinates. */
  18950. void offsetAll (int dx, int dy) throw();
  18951. /** Creates a Path object to represent this region. */
  18952. const Path toPath() const;
  18953. /** An iterator for accessing all the rectangles in a RectangleList. */
  18954. class Iterator
  18955. {
  18956. public:
  18957. Iterator (const RectangleList& list) throw();
  18958. ~Iterator();
  18959. /** Advances to the next rectangle, and returns true if it's not finished.
  18960. Call this before using getRectangle() to find the rectangle that was returned.
  18961. */
  18962. bool next() throw();
  18963. /** Returns the current rectangle. */
  18964. const Rectangle<int>* getRectangle() const throw() { return current; }
  18965. juce_UseDebuggingNewOperator
  18966. private:
  18967. const Rectangle<int>* current;
  18968. const RectangleList& owner;
  18969. int index;
  18970. Iterator (const Iterator&);
  18971. Iterator& operator= (const Iterator&);
  18972. };
  18973. juce_UseDebuggingNewOperator
  18974. private:
  18975. friend class Iterator;
  18976. Array <Rectangle<int> > rects;
  18977. };
  18978. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  18979. /*** End of inlined file: juce_RectangleList.h ***/
  18980. /*** Start of inlined file: juce_BorderSize.h ***/
  18981. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  18982. #define __JUCE_BORDERSIZE_JUCEHEADER__
  18983. /**
  18984. Specifies a set of gaps to be left around the sides of a rectangle.
  18985. This is basically the size of the spaces at the top, bottom, left and right of
  18986. a rectangle. It's used by various component classes to specify borders.
  18987. @see Rectangle
  18988. */
  18989. class JUCE_API BorderSize
  18990. {
  18991. public:
  18992. /** Creates a null border.
  18993. All sizes are left as 0.
  18994. */
  18995. BorderSize() throw();
  18996. /** Creates a copy of another border. */
  18997. BorderSize (const BorderSize& other) throw();
  18998. /** Creates a border with the given gaps. */
  18999. BorderSize (int topGap,
  19000. int leftGap,
  19001. int bottomGap,
  19002. int rightGap) throw();
  19003. /** Creates a border with the given gap on all sides. */
  19004. explicit BorderSize (int allGaps) throw();
  19005. /** Destructor. */
  19006. ~BorderSize() throw();
  19007. /** Returns the gap that should be left at the top of the region. */
  19008. int getTop() const throw() { return top; }
  19009. /** Returns the gap that should be left at the top of the region. */
  19010. int getLeft() const throw() { return left; }
  19011. /** Returns the gap that should be left at the top of the region. */
  19012. int getBottom() const throw() { return bottom; }
  19013. /** Returns the gap that should be left at the top of the region. */
  19014. int getRight() const throw() { return right; }
  19015. /** Returns the sum of the top and bottom gaps. */
  19016. int getTopAndBottom() const throw() { return top + bottom; }
  19017. /** Returns the sum of the left and right gaps. */
  19018. int getLeftAndRight() const throw() { return left + right; }
  19019. /** Changes the top gap. */
  19020. void setTop (int newTopGap) throw();
  19021. /** Changes the left gap. */
  19022. void setLeft (int newLeftGap) throw();
  19023. /** Changes the bottom gap. */
  19024. void setBottom (int newBottomGap) throw();
  19025. /** Changes the right gap. */
  19026. void setRight (int newRightGap) throw();
  19027. /** Returns a rectangle with these borders removed from it. */
  19028. const Rectangle<int> subtractedFrom (const Rectangle<int>& original) const throw();
  19029. /** Removes this border from a given rectangle. */
  19030. void subtractFrom (Rectangle<int>& rectangle) const throw();
  19031. /** Returns a rectangle with these borders added around it. */
  19032. const Rectangle<int> addedTo (const Rectangle<int>& original) const throw();
  19033. /** Adds this border around a given rectangle. */
  19034. void addTo (Rectangle<int>& original) const throw();
  19035. bool operator== (const BorderSize& other) const throw();
  19036. bool operator!= (const BorderSize& other) const throw();
  19037. juce_UseDebuggingNewOperator
  19038. private:
  19039. int top, left, bottom, right;
  19040. };
  19041. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  19042. /*** End of inlined file: juce_BorderSize.h ***/
  19043. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  19044. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19045. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19046. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  19047. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19048. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19049. /**
  19050. Classes derived from this will be automatically deleted when the application exits.
  19051. After JUCEApplication::shutdown() has been called, any objects derived from
  19052. DeletedAtShutdown which are still in existence will be deleted in the reverse
  19053. order to that in which they were created.
  19054. So if you've got a singleton and don't want to have to explicitly delete it, just
  19055. inherit from this and it'll be taken care of.
  19056. */
  19057. class JUCE_API DeletedAtShutdown
  19058. {
  19059. protected:
  19060. /** Creates a DeletedAtShutdown object. */
  19061. DeletedAtShutdown();
  19062. /** Destructor.
  19063. It's ok to delete these objects explicitly - it's only the ones left
  19064. dangling at the end that will be deleted automatically.
  19065. */
  19066. virtual ~DeletedAtShutdown();
  19067. public:
  19068. /** Deletes all extant objects.
  19069. This shouldn't be used by applications, as it's called automatically
  19070. in the shutdown code of the JUCEApplication class.
  19071. */
  19072. static void deleteAll();
  19073. private:
  19074. DeletedAtShutdown (const DeletedAtShutdown&);
  19075. DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  19076. static CriticalSection& getLock();
  19077. static Array <DeletedAtShutdown*>& getObjects();
  19078. };
  19079. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19080. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  19081. /**
  19082. Manages the system's stack of modal components.
  19083. Normally you'll just use the Component methods to invoke modal states in components,
  19084. and won't have to deal with this class directly, but this is the singleton object that's
  19085. used internally to manage the stack.
  19086. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  19087. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  19088. */
  19089. class JUCE_API ModalComponentManager : public AsyncUpdater,
  19090. public DeletedAtShutdown
  19091. {
  19092. public:
  19093. /** Receives callbacks when a modal component is dismissed.
  19094. You can register a callback using Component::enterModalState() or
  19095. ModalComponentManager::attachCallback().
  19096. */
  19097. class Callback
  19098. {
  19099. public:
  19100. /** */
  19101. Callback() {}
  19102. /** Destructor. */
  19103. virtual ~Callback() {}
  19104. /** Called to indicate that a modal component has been dismissed.
  19105. You can register a callback using Component::enterModalState() or
  19106. ModalComponentManager::attachCallback().
  19107. The returnValue parameter is the value that was passed to Component::exitModalState()
  19108. when the component was dismissed.
  19109. The callback object will be deleted shortly after this method is called.
  19110. */
  19111. virtual void modalStateFinished (int returnValue) = 0;
  19112. };
  19113. /** Returns the number of components currently being shown modally.
  19114. @see getModalComponent
  19115. */
  19116. int getNumModalComponents() const;
  19117. /** Returns one of the components being shown modally.
  19118. An index of 0 is the most recently-shown, topmost component.
  19119. */
  19120. Component* getModalComponent (int index) const;
  19121. /** Returns true if the specified component is in a modal state. */
  19122. bool isModal (Component* component) const;
  19123. /** Returns true if the specified component is currently the topmost modal component. */
  19124. bool isFrontModalComponent (Component* component) const;
  19125. /** Adds a new callback that will be called when the specified modal component is dismissed.
  19126. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  19127. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  19128. called.
  19129. Each component can have any number of callbacks associated with it, and this one is added
  19130. to that list.
  19131. The object that is passed in will be deleted by the manager when it's no longer needed. If
  19132. the given component is not currently modal, the callback object is deleted immediately and
  19133. no action is taken.
  19134. */
  19135. void attachCallback (Component* component, Callback* callback);
  19136. /** Runs the event loop until the currently topmost modal component is dismissed, and
  19137. returns the exit code for that component.
  19138. */
  19139. int runEventLoopForCurrentComponent();
  19140. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  19141. protected:
  19142. /** Creates a ModalComponentManager.
  19143. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  19144. */
  19145. ModalComponentManager();
  19146. /** Destructor. */
  19147. ~ModalComponentManager();
  19148. /** @internal */
  19149. void handleAsyncUpdate();
  19150. private:
  19151. class ModalItem;
  19152. class ReturnValueRetriever;
  19153. friend class Component;
  19154. friend class OwnedArray <ModalItem>;
  19155. OwnedArray <ModalItem> stack;
  19156. void startModal (Component* component, Callback* callback);
  19157. void endModal (Component* component, int returnValue);
  19158. void endModal (Component* component);
  19159. };
  19160. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19161. /*** End of inlined file: juce_ModalComponentManager.h ***/
  19162. class LookAndFeel;
  19163. class MouseInputSource;
  19164. class MouseInputSourceInternal;
  19165. class ComponentPeer;
  19166. /**
  19167. The base class for all JUCE user-interface objects.
  19168. */
  19169. class JUCE_API Component : public MouseListener,
  19170. public MessageListener
  19171. {
  19172. public:
  19173. /** Creates a component.
  19174. To get it to actually appear, you'll also need to:
  19175. - Either add it to a parent component or use the addToDesktop() method to
  19176. make it a desktop window
  19177. - Set its size and position to something sensible
  19178. - Use setVisible() to make it visible
  19179. And for it to serve any useful purpose, you'll need to write a
  19180. subclass of Component or use one of the other types of component from
  19181. the library.
  19182. */
  19183. Component();
  19184. /** Destructor.
  19185. Note that when a component is deleted, any child components it might
  19186. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  19187. */
  19188. virtual ~Component();
  19189. /** Creates a component, setting its name at the same time.
  19190. @see getName, setName
  19191. */
  19192. explicit Component (const String& componentName);
  19193. /** Returns the name of this component.
  19194. @see setName
  19195. */
  19196. const String& getName() const throw() { return componentName_; }
  19197. /** Sets the name of this component.
  19198. When the name changes, all registered ComponentListeners will receive a
  19199. ComponentListener::componentNameChanged() callback.
  19200. @see getName
  19201. */
  19202. virtual void setName (const String& newName);
  19203. /** Checks whether this Component object has been deleted.
  19204. This will check whether this object is still a valid component, or whether
  19205. it's been deleted.
  19206. It's safe to call this on null or dangling pointers, but note that there is a
  19207. small risk if another new (but different) component has been created at the
  19208. same memory address which this one occupied, this methods can return a
  19209. false positive.
  19210. */
  19211. bool isValidComponent() const;
  19212. /** Makes the component visible or invisible.
  19213. This method will show or hide the component.
  19214. Note that components default to being non-visible when first created.
  19215. Also note that visible components won't be seen unless all their parent components
  19216. are also visible.
  19217. This method will call visibilityChanged() and also componentVisibilityChanged()
  19218. for any component listeners that are interested in this component.
  19219. @param shouldBeVisible whether to show or hide the component
  19220. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  19221. */
  19222. virtual void setVisible (bool shouldBeVisible);
  19223. /** Tests whether the component is visible or not.
  19224. this doesn't necessarily tell you whether this comp is actually on the screen
  19225. because this depends on whether all the parent components are also visible - use
  19226. isShowing() to find this out.
  19227. @see isShowing, setVisible
  19228. */
  19229. bool isVisible() const throw() { return flags.visibleFlag; }
  19230. /** Called when this component's visiblility changes.
  19231. @see setVisible, isVisible
  19232. */
  19233. virtual void visibilityChanged();
  19234. /** Tests whether this component and all its parents are visible.
  19235. @returns true only if this component and all its parents are visible.
  19236. @see isVisible
  19237. */
  19238. bool isShowing() const;
  19239. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  19240. To do this, this function will cunningly:
  19241. - take a snapshot of the component as it currently looks
  19242. - call setVisible(false) on the component
  19243. - replace it with a special component that will continue drawing the
  19244. snapshot, animating it and gradually making it more transparent
  19245. - when it's gone, the special component will also be deleted
  19246. As soon as this method returns, the component can be safely removed and deleted
  19247. leaving the proxy to do the fade-out, so it's even ok to call this in a
  19248. component's destructor.
  19249. Passing non-zero x and y values will cause the ghostly component image to
  19250. also whizz off by this distance while fading out. If the scale factor is
  19251. not 1.0, it will also zoom from the component's current size to this new size.
  19252. One thing to be careful about is that the parent component must be able to cope
  19253. with this unknown component type being added to it.
  19254. */
  19255. void fadeOutComponent (int lengthOfFadeOutInMilliseconds,
  19256. int deltaXToMove = 0,
  19257. int deltaYToMove = 0,
  19258. float scaleFactorAtEnd = 1.0f);
  19259. /** Makes this component appear as a window on the desktop.
  19260. Note that before calling this, you should make sure that the component's opacity is
  19261. set correctly using setOpaque(). If the component is non-opaque, the windowing
  19262. system will try to create a special transparent window for it, which will generally take
  19263. a lot more CPU to operate (and might not even be possible on some platforms).
  19264. If the component is inside a parent component at the time this method is called, it
  19265. will be first be removed from that parent. Likewise if a component on the desktop
  19266. is subsequently added to another component, it'll be removed from the desktop.
  19267. @param windowStyleFlags a combination of the flags specified in the
  19268. ComponentPeer::StyleFlags enum, which define the
  19269. window's characteristics.
  19270. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  19271. in which the juce component should place itself. On Windows,
  19272. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  19273. supported on all platforms, and best left as 0 unless you know
  19274. what you're doing
  19275. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  19276. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  19277. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  19278. */
  19279. virtual void addToDesktop (int windowStyleFlags,
  19280. void* nativeWindowToAttachTo = 0);
  19281. /** If the component is currently showing on the desktop, this will hide it.
  19282. You can also use setVisible() to hide a desktop window temporarily, but
  19283. removeFromDesktop() will free any system resources that are being used up.
  19284. @see addToDesktop, isOnDesktop
  19285. */
  19286. void removeFromDesktop();
  19287. /** Returns true if this component is currently showing on the desktop.
  19288. @see addToDesktop, removeFromDesktop
  19289. */
  19290. bool isOnDesktop() const throw();
  19291. /** Returns the heavyweight window that contains this component.
  19292. If this component is itself on the desktop, this will return the window
  19293. object that it is using. Otherwise, it will return the window of
  19294. its top-level parent component.
  19295. This may return 0 if there isn't a desktop component.
  19296. @see addToDesktop, isOnDesktop
  19297. */
  19298. ComponentPeer* getPeer() const;
  19299. /** For components on the desktop, this is called if the system wants to close the window.
  19300. This is a signal that either the user or the system wants the window to close. The
  19301. default implementation of this method will trigger an assertion to warn you that your
  19302. component should do something about it, but you can override this to ignore the event
  19303. if you want.
  19304. */
  19305. virtual void userTriedToCloseWindow();
  19306. /** Called for a desktop component which has just been minimised or un-minimised.
  19307. This will only be called for components on the desktop.
  19308. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  19309. */
  19310. virtual void minimisationStateChanged (bool isNowMinimised);
  19311. /** Brings the component to the front of its siblings.
  19312. If some of the component's siblings have had their 'always-on-top' flag set,
  19313. then they will still be kept in front of this one (unless of course this
  19314. one is also 'always-on-top').
  19315. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  19316. to the component (see grabKeyboardFocus() for more details)
  19317. @see toBack, toBehind, setAlwaysOnTop
  19318. */
  19319. void toFront (bool shouldAlsoGainFocus);
  19320. /** Changes this component's z-order to be at the back of all its siblings.
  19321. If the component is set to be 'always-on-top', it will only be moved to the
  19322. back of the other other 'always-on-top' components.
  19323. @see toFront, toBehind, setAlwaysOnTop
  19324. */
  19325. void toBack();
  19326. /** Changes this component's z-order so that it's just behind another component.
  19327. @see toFront, toBack
  19328. */
  19329. void toBehind (Component* other);
  19330. /** Sets whether the component should always be kept at the front of its siblings.
  19331. @see isAlwaysOnTop
  19332. */
  19333. void setAlwaysOnTop (bool shouldStayOnTop);
  19334. /** Returns true if this component is set to always stay in front of its siblings.
  19335. @see setAlwaysOnTop
  19336. */
  19337. bool isAlwaysOnTop() const throw();
  19338. /** Returns the x co-ordinate of the component's left edge.
  19339. This is a distance in pixels from the left edge of the component's parent.
  19340. @see getScreenX
  19341. */
  19342. inline int getX() const throw() { return bounds_.getX(); }
  19343. /** Returns the y co-ordinate of the top of this component.
  19344. This is a distance in pixels from the top edge of the component's parent.
  19345. @see getScreenY
  19346. */
  19347. inline int getY() const throw() { return bounds_.getY(); }
  19348. /** Returns the component's width in pixels. */
  19349. inline int getWidth() const throw() { return bounds_.getWidth(); }
  19350. /** Returns the component's height in pixels. */
  19351. inline int getHeight() const throw() { return bounds_.getHeight(); }
  19352. /** Returns the x co-ordinate of the component's right-hand edge.
  19353. This is a distance in pixels from the left edge of the component's parent.
  19354. */
  19355. int getRight() const throw() { return bounds_.getRight(); }
  19356. /** Returns the component's top-left position as a Point. */
  19357. const Point<int> getPosition() const throw() { return bounds_.getPosition(); }
  19358. /** Returns the y co-ordinate of the bottom edge of this component.
  19359. This is a distance in pixels from the top edge of the component's parent.
  19360. */
  19361. int getBottom() const throw() { return bounds_.getBottom(); }
  19362. /** Returns this component's bounding box.
  19363. The rectangle returned is relative to the top-left of the component's parent.
  19364. */
  19365. const Rectangle<int>& getBounds() const throw() { return bounds_; }
  19366. /** Returns the component's bounds, relative to its own origin.
  19367. This is like getBounds(), but returns the rectangle in local co-ordinates, In practice, it'll
  19368. return a rectangle with position (0, 0), and the same size as this component.
  19369. */
  19370. const Rectangle<int> getLocalBounds() const throw();
  19371. /** Returns the region of this component that's not obscured by other, opaque components.
  19372. The RectangleList that is returned represents the area of this component
  19373. which isn't covered by opaque child components.
  19374. If includeSiblings is true, it will also take into account any siblings
  19375. that may be overlapping the component.
  19376. */
  19377. void getVisibleArea (RectangleList& result,
  19378. bool includeSiblings) const;
  19379. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  19380. @see getX, relativePositionToGlobal
  19381. */
  19382. int getScreenX() const;
  19383. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  19384. @see getY, relativePositionToGlobal
  19385. */
  19386. int getScreenY() const;
  19387. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  19388. @see getScreenBounds
  19389. */
  19390. const Point<int> getScreenPosition() const;
  19391. /** Returns the bounds of this component, relative to the screen's top-left.
  19392. @see getScreenPosition
  19393. */
  19394. const Rectangle<int> getScreenBounds() const;
  19395. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  19396. @see globalPositionToRelative, relativePositionToOtherComponent
  19397. */
  19398. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) const;
  19399. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  19400. @see relativePositionToGlobal, relativePositionToOtherComponent
  19401. */
  19402. const Point<int> globalPositionToRelative (const Point<int>& screenPosition) const;
  19403. /** Converts a position relative to this component's top-left into a position
  19404. relative to another component's top-left.
  19405. @see relativePositionToGlobal, globalPositionToRelative
  19406. */
  19407. const Point<int> relativePositionToOtherComponent (const Component* targetComponent,
  19408. const Point<int>& positionRelativeToThis) const;
  19409. /** Moves the component to a new position.
  19410. Changes the component's top-left position (without changing its size).
  19411. The position is relative to the top-left of the component's parent.
  19412. If the component actually moves, this method will make a synchronous call to moved().
  19413. @see setBounds, ComponentListener::componentMovedOrResized
  19414. */
  19415. void setTopLeftPosition (int x, int y);
  19416. /** Moves the component to a new position.
  19417. Changes the position of the component's top-right corner (keeping it the same size).
  19418. The position is relative to the top-left of the component's parent.
  19419. If the component actually moves, this method will make a synchronous call to moved().
  19420. */
  19421. void setTopRightPosition (int x, int y);
  19422. /** Changes the size of the component.
  19423. A synchronous call to resized() will be occur if the size actually changes.
  19424. */
  19425. void setSize (int newWidth, int newHeight);
  19426. /** Changes the component's position and size.
  19427. The co-ordinates are relative to the top-left of the component's parent, or relative
  19428. to the origin of the screen is the component is on the desktop.
  19429. If this method changes the component's top-left position, it will make a synchronous
  19430. call to moved(). If it changes the size, it will also make a call to resized().
  19431. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  19432. */
  19433. void setBounds (int x, int y, int width, int height);
  19434. /** Changes the component's position and size.
  19435. @see setBounds
  19436. */
  19437. void setBounds (const Rectangle<int>& newBounds);
  19438. /** Changes the component's position and size in terms of fractions of its parent's size.
  19439. The values are factors of the parent's size, so for example
  19440. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  19441. width and height of the parent, with its top-left position 20% of
  19442. the way across and down the parent.
  19443. */
  19444. void setBoundsRelative (float proportionalX, float proportionalY,
  19445. float proportionalWidth, float proportionalHeight);
  19446. /** Changes the component's position and size based on the amount of space to leave around it.
  19447. This will position the component within its parent, leaving the specified number of
  19448. pixels around each edge.
  19449. */
  19450. void setBoundsInset (const BorderSize& borders);
  19451. /** Positions the component within a given rectangle, keeping its proportions
  19452. unchanged.
  19453. If onlyReduceInSize is false, the component will be resized to fill as much of the
  19454. rectangle as possible without changing its aspect ratio (the component's
  19455. current size is used to determine its aspect ratio, so a zero-size component
  19456. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  19457. too big to fit inside the rectangle.
  19458. It will then be positioned within the rectangle according to the justification flags
  19459. specified.
  19460. */
  19461. void setBoundsToFit (int x, int y, int width, int height,
  19462. const Justification& justification,
  19463. bool onlyReduceInSize);
  19464. /** Changes the position of the component's centre.
  19465. Leaves the component's size unchanged, but sets the position of its centre
  19466. relative to its parent's top-left.
  19467. */
  19468. void setCentrePosition (int x, int y);
  19469. /** Changes the position of the component's centre.
  19470. Leaves the position unchanged, but positions its centre relative to its
  19471. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  19472. its parent.
  19473. */
  19474. void setCentreRelative (float x, float y);
  19475. /** Changes the component's size and centres it within its parent.
  19476. After changing the size, the component will be moved so that it's
  19477. centred within its parent. If the component is on the desktop (or has no
  19478. parent component), then it'll be centred within the main monitor area.
  19479. */
  19480. void centreWithSize (int width, int height);
  19481. /** Returns a proportion of the component's width.
  19482. This is a handy equivalent of (getWidth() * proportion).
  19483. */
  19484. int proportionOfWidth (float proportion) const throw();
  19485. /** Returns a proportion of the component's height.
  19486. This is a handy equivalent of (getHeight() * proportion).
  19487. */
  19488. int proportionOfHeight (float proportion) const throw();
  19489. /** Returns the width of the component's parent.
  19490. If the component has no parent (i.e. if it's on the desktop), this will return
  19491. the width of the screen.
  19492. */
  19493. int getParentWidth() const throw();
  19494. /** Returns the height of the component's parent.
  19495. If the component has no parent (i.e. if it's on the desktop), this will return
  19496. the height of the screen.
  19497. */
  19498. int getParentHeight() const throw();
  19499. /** Returns the screen co-ordinates of the monitor that contains this component.
  19500. If there's only one monitor, this will return its size - if there are multiple
  19501. monitors, it will return the area of the monitor that contains the component's
  19502. centre.
  19503. */
  19504. const Rectangle<int> getParentMonitorArea() const;
  19505. /** Returns the number of child components that this component contains.
  19506. @see getChildComponent, getIndexOfChildComponent
  19507. */
  19508. int getNumChildComponents() const throw();
  19509. /** Returns one of this component's child components, by it index.
  19510. The component with index 0 is at the back of the z-order, the one at the
  19511. front will have index (getNumChildComponents() - 1).
  19512. If the index is out-of-range, this will return a null pointer.
  19513. @see getNumChildComponents, getIndexOfChildComponent
  19514. */
  19515. Component* getChildComponent (int index) const throw();
  19516. /** Returns the index of this component in the list of child components.
  19517. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  19518. values are further towards the front.
  19519. Returns -1 if the component passed-in is not a child of this component.
  19520. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  19521. */
  19522. int getIndexOfChildComponent (const Component* child) const throw();
  19523. /** Adds a child component to this one.
  19524. @param child the new component to add. If the component passed-in is already
  19525. the child of another component, it'll first be removed from that.
  19526. @param zOrder The index in the child-list at which this component should be inserted.
  19527. A value of -1 will insert it in front of the others, 0 is the back.
  19528. @see removeChildComponent, addAndMakeVisible, getChild,
  19529. ComponentListener::componentChildrenChanged
  19530. */
  19531. void addChildComponent (Component* child, int zOrder = -1);
  19532. /** Adds a child component to this one, and also makes the child visible if it isn't.
  19533. Quite a useful function, this is just the same as calling addChildComponent()
  19534. followed by setVisible (true) on the child.
  19535. */
  19536. void addAndMakeVisible (Component* child, int zOrder = -1);
  19537. /** Removes one of this component's child-components.
  19538. If the child passed-in isn't actually a child of this component (either because
  19539. it's invalid or is the child of a different parent), then nothing is done.
  19540. Note that removing a child will not delete it!
  19541. @see addChildComponent, ComponentListener::componentChildrenChanged
  19542. */
  19543. void removeChildComponent (Component* childToRemove);
  19544. /** Removes one of this component's child-components by index.
  19545. This will return a pointer to the component that was removed, or null if
  19546. the index was out-of-range.
  19547. Note that removing a child will not delete it!
  19548. @see addChildComponent, ComponentListener::componentChildrenChanged
  19549. */
  19550. Component* removeChildComponent (int childIndexToRemove);
  19551. /** Removes all this component's children.
  19552. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  19553. */
  19554. void removeAllChildren();
  19555. /** Removes all this component's children, and deletes them.
  19556. @see removeAllChildren
  19557. */
  19558. void deleteAllChildren();
  19559. /** Returns the component which this component is inside.
  19560. If this is the highest-level component or hasn't yet been added to
  19561. a parent, this will return null.
  19562. */
  19563. Component* getParentComponent() const throw() { return parentComponent_; }
  19564. /** Searches the parent components for a component of a specified class.
  19565. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  19566. component that can be dynamically cast to a MyComp, or will return 0 if none
  19567. of the parents are suitable.
  19568. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  19569. */
  19570. template <class TargetClass>
  19571. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  19572. {
  19573. (void) dummyParameter;
  19574. Component* p = parentComponent_;
  19575. while (p != 0)
  19576. {
  19577. TargetClass* target = dynamic_cast <TargetClass*> (p);
  19578. if (target != 0)
  19579. return target;
  19580. p = p->parentComponent_;
  19581. }
  19582. return 0;
  19583. }
  19584. /** Returns the highest-level component which contains this one or its parents.
  19585. This will search upwards in the parent-hierarchy from this component, until it
  19586. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  19587. not yet added to a parent), and will return that.
  19588. */
  19589. Component* getTopLevelComponent() const throw();
  19590. /** Checks whether a component is anywhere inside this component or its children.
  19591. This will recursively check through this component's children to see if the
  19592. given component is anywhere inside.
  19593. */
  19594. bool isParentOf (const Component* possibleChild) const throw();
  19595. /** Called to indicate that the component's parents have changed.
  19596. When a component is added or removed from its parent, this method will
  19597. be called on all of its children (recursively - so all children of its
  19598. children will also be called as well).
  19599. Subclasses can override this if they need to react to this in some way.
  19600. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  19601. */
  19602. virtual void parentHierarchyChanged();
  19603. /** Subclasses can use this callback to be told when children are added or removed.
  19604. @see parentHierarchyChanged
  19605. */
  19606. virtual void childrenChanged();
  19607. /** Tests whether a given point inside the component.
  19608. Overriding this method allows you to create components which only intercept
  19609. mouse-clicks within a user-defined area.
  19610. This is called to find out whether a particular x, y co-ordinate is
  19611. considered to be inside the component or not, and is used by methods such
  19612. as contains() and getComponentAt() to work out which component
  19613. the mouse is clicked on.
  19614. Components with custom shapes will probably want to override it to perform
  19615. some more complex hit-testing.
  19616. The default implementation of this method returns either true or false,
  19617. depending on the value that was set by calling setInterceptsMouseClicks() (true
  19618. is the default return value).
  19619. Note that the hit-test region is not related to the opacity with which
  19620. areas of a component are painted.
  19621. Applications should never call hitTest() directly - instead use the
  19622. contains() method, because this will also test for occlusion by the
  19623. component's parent.
  19624. Note that for components on the desktop, this method will be ignored, because it's
  19625. not always possible to implement this behaviour on all platforms.
  19626. @param x the x co-ordinate to test, relative to the left hand edge of this
  19627. component. This value is guaranteed to be greater than or equal to
  19628. zero, and less than the component's width
  19629. @param y the y co-ordinate to test, relative to the top edge of this
  19630. component. This value is guaranteed to be greater than or equal to
  19631. zero, and less than the component's height
  19632. @returns true if the click is considered to be inside the component
  19633. @see setInterceptsMouseClicks, contains
  19634. */
  19635. virtual bool hitTest (int x, int y);
  19636. /** Changes the default return value for the hitTest() method.
  19637. Setting this to false is an easy way to make a component pass its mouse-clicks
  19638. through to the components behind it.
  19639. When a component is created, the default setting for this is true.
  19640. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  19641. return false (or true for child components if allowClicksOnChildComponents
  19642. is true)
  19643. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  19644. components can be clicked on as normal but clicks on this component pass
  19645. straight through; if this is false and allowClicksOnThisComponent
  19646. is false, then neither this component nor any child components can
  19647. be clicked on
  19648. @see hitTest, getInterceptsMouseClicks
  19649. */
  19650. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  19651. bool allowClicksOnChildComponents) throw();
  19652. /** Retrieves the current state of the mouse-click interception flags.
  19653. On return, the two parameters are set to the state used in the last call to
  19654. setInterceptsMouseClicks().
  19655. @see setInterceptsMouseClicks
  19656. */
  19657. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  19658. bool& allowsClicksOnChildComponents) const throw();
  19659. /** Returns true if a given point lies within this component or one of its children.
  19660. Never override this method! Use hitTest to create custom hit regions.
  19661. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19662. @param y the y co-ordinate to test, relative to this component's top edge.
  19663. @returns true if the point is within the component's hit-test area, but only if
  19664. that part of the component isn't clipped by its parent component. Note
  19665. that this won't take into account any overlapping sibling components
  19666. which might be in the way - for that, see reallyContains()
  19667. @see hitTest, reallyContains, getComponentAt
  19668. */
  19669. virtual bool contains (int x, int y);
  19670. /** Returns true if a given point lies in this component, taking any overlapping
  19671. siblings into account.
  19672. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19673. @param y the y co-ordinate to test, relative to this component's top edge.
  19674. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  19675. component, this determines the value that will
  19676. be returned.
  19677. @see contains, getComponentAt
  19678. */
  19679. bool reallyContains (int x, int y, bool returnTrueIfWithinAChild);
  19680. /** Returns the component at a certain point within this one.
  19681. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19682. @param y the y co-ordinate to test, relative to this component's top edge.
  19683. @returns the component that is at this position - which may be 0, this component,
  19684. or one of its children. Note that overlapping siblings that might actually
  19685. be in the way are not taken into account by this method - to account for these,
  19686. instead call getComponentAt on the top-level parent of this component.
  19687. @see hitTest, contains, reallyContains
  19688. */
  19689. Component* getComponentAt (int x, int y);
  19690. /** Returns the component at a certain point within this one.
  19691. @param position the co-ordinates to test, relative to this component's top-left.
  19692. @returns the component that is at this position - which may be 0, this component,
  19693. or one of its children. Note that overlapping siblings that might actually
  19694. be in the way are not taken into account by this method - to account for these,
  19695. instead call getComponentAt on the top-level parent of this component.
  19696. @see hitTest, contains, reallyContains
  19697. */
  19698. Component* getComponentAt (const Point<int>& position);
  19699. /** Marks the whole component as needing to be redrawn.
  19700. Calling this will not do any repainting immediately, but will mark the component
  19701. as 'dirty'. At some point in the near future the operating system will send a paint
  19702. message, which will redraw all the dirty regions of all components.
  19703. There's no guarantee about how soon after calling repaint() the redraw will actually
  19704. happen, and other queued events may be delivered before a redraw is done.
  19705. If the setBufferedToImage() method has been used to cause this component
  19706. to use a buffer, the repaint() call will invalidate the component's buffer.
  19707. To redraw just a subsection of the component rather than the whole thing,
  19708. use the repaint (int, int, int, int) method.
  19709. @see paint
  19710. */
  19711. void repaint();
  19712. /** Marks a subsection of this component as needing to be redrawn.
  19713. Calling this will not do any repainting immediately, but will mark the given region
  19714. of the component as 'dirty'. At some point in the near future the operating system
  19715. will send a paint message, which will redraw all the dirty regions of all components.
  19716. There's no guarantee about how soon after calling repaint() the redraw will actually
  19717. happen, and other queued events may be delivered before a redraw is done.
  19718. The region that is passed in will be clipped to keep it within the bounds of this
  19719. component.
  19720. @see repaint()
  19721. */
  19722. void repaint (int x, int y, int width, int height);
  19723. /** Marks a subsection of this component as needing to be redrawn.
  19724. Calling this will not do any repainting immediately, but will mark the given region
  19725. of the component as 'dirty'. At some point in the near future the operating system
  19726. will send a paint message, which will redraw all the dirty regions of all components.
  19727. There's no guarantee about how soon after calling repaint() the redraw will actually
  19728. happen, and other queued events may be delivered before a redraw is done.
  19729. The region that is passed in will be clipped to keep it within the bounds of this
  19730. component.
  19731. @see repaint()
  19732. */
  19733. void repaint (const Rectangle<int>& area);
  19734. /** Makes the component use an internal buffer to optimise its redrawing.
  19735. Setting this flag to true will cause the component to allocate an
  19736. internal buffer into which it paints itself, so that when asked to
  19737. redraw itself, it can use this buffer rather than actually calling the
  19738. paint() method.
  19739. The buffer is kept until the repaint() method is called directly on
  19740. this component (or until it is resized), when the image is invalidated
  19741. and then redrawn the next time the component is painted.
  19742. Note that only the drawing that happens within the component's paint()
  19743. method is drawn into the buffer, it's child components are not buffered, and
  19744. nor is the paintOverChildren() method.
  19745. @see repaint, paint, createComponentSnapshot
  19746. */
  19747. void setBufferedToImage (bool shouldBeBuffered);
  19748. /** Generates a snapshot of part of this component.
  19749. This will return a new Image, the size of the rectangle specified,
  19750. containing a snapshot of the specified area of the component and all
  19751. its children.
  19752. The image may or may not have an alpha-channel, depending on whether the
  19753. image is opaque or not.
  19754. If the clipImageToComponentBounds parameter is true and the area is greater than
  19755. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  19756. then parts of the component beyond its bounds can be drawn.
  19757. @see paintEntireComponent
  19758. */
  19759. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  19760. bool clipImageToComponentBounds = true);
  19761. /** Draws this component and all its subcomponents onto the specified graphics
  19762. context.
  19763. You should very rarely have to use this method, it's simply there in case you need
  19764. to draw a component with a custom graphics context for some reason, e.g. for
  19765. creating a snapshot of the component.
  19766. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  19767. on its children in order to render the entire tree.
  19768. The graphics context may be left in an undefined state after this method returns,
  19769. so you may need to reset it if you're going to use it again.
  19770. */
  19771. void paintEntireComponent (Graphics& context);
  19772. /** Adds an effect filter to alter the component's appearance.
  19773. When a component has an effect filter set, then this is applied to the
  19774. results of its paint() method. There are a few preset effects, such as
  19775. a drop-shadow or glow, but they can be user-defined as well.
  19776. The effect that is passed in will not be deleted by the component - the
  19777. caller must take care of deleting it.
  19778. To remove an effect from a component, pass a null pointer in as the parameter.
  19779. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  19780. */
  19781. void setComponentEffect (ImageEffectFilter* newEffect);
  19782. /** Returns the current component effect.
  19783. @see setComponentEffect
  19784. */
  19785. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  19786. /** Finds the appropriate look-and-feel to use for this component.
  19787. If the component hasn't had a look-and-feel explicitly set, this will
  19788. return the parent's look-and-feel, or just the default one if there's no
  19789. parent.
  19790. @see setLookAndFeel, lookAndFeelChanged
  19791. */
  19792. LookAndFeel& getLookAndFeel() const throw();
  19793. /** Sets the look and feel to use for this component.
  19794. This will also change the look and feel for any child components that haven't
  19795. had their look set explicitly.
  19796. The object passed in will not be deleted by the component, so it's the caller's
  19797. responsibility to manage it. It may be used at any time until this component
  19798. has been deleted.
  19799. Calling this method will also invoke the sendLookAndFeelChange() method.
  19800. @see getLookAndFeel, lookAndFeelChanged
  19801. */
  19802. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  19803. /** Called to let the component react to a change in the look-and-feel setting.
  19804. When the look-and-feel is changed for a component, this will be called in
  19805. all its child components, recursively.
  19806. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  19807. an application uses a LookAndFeel class that might have changed internally.
  19808. @see sendLookAndFeelChange, getLookAndFeel
  19809. */
  19810. virtual void lookAndFeelChanged();
  19811. /** Calls the lookAndFeelChanged() method in this component and all its children.
  19812. This will recurse through the children and their children, calling lookAndFeelChanged()
  19813. on them all.
  19814. @see lookAndFeelChanged
  19815. */
  19816. void sendLookAndFeelChange();
  19817. /** Indicates whether any parts of the component might be transparent.
  19818. Components that always paint all of their contents with solid colour and
  19819. thus completely cover any components behind them should use this method
  19820. to tell the repaint system that they are opaque.
  19821. This information is used to optimise drawing, because it means that
  19822. objects underneath opaque windows don't need to be painted.
  19823. By default, components are considered transparent, unless this is used to
  19824. make it otherwise.
  19825. @see isOpaque, getVisibleArea
  19826. */
  19827. void setOpaque (bool shouldBeOpaque);
  19828. /** Returns true if no parts of this component are transparent.
  19829. @returns the value that was set by setOpaque, (the default being false)
  19830. @see setOpaque
  19831. */
  19832. bool isOpaque() const throw();
  19833. /** Indicates whether the component should be brought to the front when clicked.
  19834. Setting this flag to true will cause the component to be brought to the front
  19835. when the mouse is clicked somewhere inside it or its child components.
  19836. Note that a top-level desktop window might still be brought to the front by the
  19837. operating system when it's clicked, depending on how the OS works.
  19838. By default this is set to false.
  19839. @see setMouseClickGrabsKeyboardFocus
  19840. */
  19841. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  19842. /** Indicates whether the component should be brought to the front when clicked-on.
  19843. @see setBroughtToFrontOnMouseClick
  19844. */
  19845. bool isBroughtToFrontOnMouseClick() const throw();
  19846. // Keyboard focus methods
  19847. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  19848. By default components aren't actually interested in gaining the
  19849. focus, but this method can be used to turn this on.
  19850. See the grabKeyboardFocus() method for details about the way a component
  19851. is chosen to receive the focus.
  19852. @see grabKeyboardFocus, getWantsKeyboardFocus
  19853. */
  19854. void setWantsKeyboardFocus (bool wantsFocus) throw();
  19855. /** Returns true if the component is interested in getting keyboard focus.
  19856. This returns the flag set by setWantsKeyboardFocus(). The default
  19857. setting is false.
  19858. @see setWantsKeyboardFocus
  19859. */
  19860. bool getWantsKeyboardFocus() const throw();
  19861. /** Chooses whether a click on this component automatically grabs the focus.
  19862. By default this is set to true, but you might want a component which can
  19863. be focused, but where you don't want the user to be able to affect it directly
  19864. by clicking.
  19865. */
  19866. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  19867. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  19868. See setMouseClickGrabsKeyboardFocus() for more info.
  19869. */
  19870. bool getMouseClickGrabsKeyboardFocus() const throw();
  19871. /** Tries to give keyboard focus to this component.
  19872. When the user clicks on a component or its grabKeyboardFocus()
  19873. method is called, the following procedure is used to work out which
  19874. component should get it:
  19875. - if the component that was clicked on actually wants focus (as indicated
  19876. by calling getWantsKeyboardFocus), it gets it.
  19877. - if the component itself doesn't want focus, it will try to pass it
  19878. on to whichever of its children is the default component, as determined by
  19879. KeyboardFocusTraverser::getDefaultComponent()
  19880. - if none of its children want focus at all, it will pass it up to its
  19881. parent instead, unless it's a top-level component without a parent,
  19882. in which case it just takes the focus itself.
  19883. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  19884. getCurrentlyFocusedComponent, focusGained, focusLost,
  19885. keyPressed, keyStateChanged
  19886. */
  19887. void grabKeyboardFocus();
  19888. /** Returns true if this component currently has the keyboard focus.
  19889. @param trueIfChildIsFocused if this is true, then the method returns true if
  19890. either this component or any of its children (recursively)
  19891. have the focus. If false, the method only returns true if
  19892. this component has the focus.
  19893. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  19894. focusGained, focusLost
  19895. */
  19896. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  19897. /** Returns the component that currently has the keyboard focus.
  19898. @returns the focused component, or null if nothing is focused.
  19899. */
  19900. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  19901. /** Tries to move the keyboard focus to one of this component's siblings.
  19902. This will try to move focus to either the next or previous component. (This
  19903. is the method that is used when shifting focus by pressing the tab key).
  19904. Components for which getWantsKeyboardFocus() returns false are not looked at.
  19905. @param moveToNext if true, the focus will move forwards; if false, it will
  19906. move backwards
  19907. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  19908. */
  19909. void moveKeyboardFocusToSibling (bool moveToNext);
  19910. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  19911. which focus should be passed from this component.
  19912. The default implementation of this method will return a default
  19913. KeyboardFocusTraverser if this component is a focus container (as determined
  19914. by the setFocusContainer() method). If the component isn't a focus
  19915. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  19916. If you overrride this to return a custom KeyboardFocusTraverser, then
  19917. this component and all its sub-components will use the new object to
  19918. make their focusing decisions.
  19919. The method should return a new object, which the caller is required to
  19920. delete when no longer needed.
  19921. */
  19922. virtual KeyboardFocusTraverser* createFocusTraverser();
  19923. /** Returns the focus order of this component, if one has been specified.
  19924. By default components don't have a focus order - in that case, this
  19925. will return 0. Lower numbers indicate that the component will be
  19926. earlier in the focus traversal order.
  19927. To change the order, call setExplicitFocusOrder().
  19928. The focus order may be used by the KeyboardFocusTraverser class as part of
  19929. its algorithm for deciding the order in which components should be traversed.
  19930. See the KeyboardFocusTraverser class for more details on this.
  19931. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  19932. */
  19933. int getExplicitFocusOrder() const;
  19934. /** Sets the index used in determining the order in which focusable components
  19935. should be traversed.
  19936. A value of 0 or less is taken to mean that no explicit order is wanted, and
  19937. that traversal should use other factors, like the component's position.
  19938. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  19939. */
  19940. void setExplicitFocusOrder (int newFocusOrderIndex);
  19941. /** Indicates whether this component is a parent for components that can have
  19942. their focus traversed.
  19943. This flag is used by the default implementation of the createFocusTraverser()
  19944. method, which uses the flag to find the first parent component (of the currently
  19945. focused one) which wants to be a focus container.
  19946. So using this method to set the flag to 'true' causes this component to
  19947. act as the top level within which focus is passed around.
  19948. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  19949. */
  19950. void setFocusContainer (bool shouldBeFocusContainer) throw();
  19951. /** Returns true if this component has been marked as a focus container.
  19952. See setFocusContainer() for more details.
  19953. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  19954. */
  19955. bool isFocusContainer() const throw();
  19956. /** Returns true if the component (and all its parents) are enabled.
  19957. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  19958. what difference this makes to the component depends on the type. E.g. buttons
  19959. and sliders will choose to draw themselves differently, etc.
  19960. Note that if one of this component's parents is disabled, this will always
  19961. return false, even if this component itself is enabled.
  19962. @see setEnabled, enablementChanged
  19963. */
  19964. bool isEnabled() const throw();
  19965. /** Enables or disables this component.
  19966. Disabling a component will also cause all of its child components to become
  19967. disabled.
  19968. Similarly, enabling a component which is inside a disabled parent
  19969. component won't make any difference until the parent is re-enabled.
  19970. @see isEnabled, enablementChanged
  19971. */
  19972. void setEnabled (bool shouldBeEnabled);
  19973. /** Callback to indicate that this component has been enabled or disabled.
  19974. This can be triggered by one of the component's parent components
  19975. being enabled or disabled, as well as changes to the component itself.
  19976. The default implementation of this method does nothing; your class may
  19977. wish to repaint itself or something when this happens.
  19978. @see setEnabled, isEnabled
  19979. */
  19980. virtual void enablementChanged();
  19981. /** Changes the mouse cursor shape to use when the mouse is over this component.
  19982. Note that the cursor set by this method can be overridden by the getMouseCursor
  19983. method.
  19984. @see MouseCursor
  19985. */
  19986. void setMouseCursor (const MouseCursor& cursorType);
  19987. /** Returns the mouse cursor shape to use when the mouse is over this component.
  19988. The default implementation will return the cursor that was set by setCursor()
  19989. but can be overridden for more specialised purposes, e.g. returning different
  19990. cursors depending on the mouse position.
  19991. @see MouseCursor
  19992. */
  19993. virtual const MouseCursor getMouseCursor();
  19994. /** Forces the current mouse cursor to be updated.
  19995. If you're overriding the getMouseCursor() method to control which cursor is
  19996. displayed, then this will only be checked each time the user moves the mouse. So
  19997. if you want to force the system to check that the cursor being displayed is
  19998. up-to-date (even if the mouse is just sitting there), call this method.
  19999. This isn't needed if you're only using setMouseCursor().
  20000. */
  20001. void updateMouseCursor() const;
  20002. /** Components can override this method to draw their content.
  20003. The paint() method gets called when a region of a component needs redrawing,
  20004. either because the component's repaint() method has been called, or because
  20005. something has happened on the screen that means a section of a window needs
  20006. to be redrawn.
  20007. Any child components will draw themselves over whatever this method draws. If
  20008. you need to paint over the top of your child components, you can also implement
  20009. the paintOverChildren() method to do this.
  20010. If you want to cause a component to redraw itself, this is done asynchronously -
  20011. calling the repaint() method marks a region of the component as "dirty", and the
  20012. paint() method will automatically be called sometime later, by the message thread,
  20013. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  20014. you never redraw something synchronously.
  20015. You should never need to call this method directly - to take a snapshot of the
  20016. component you could use createComponentSnapshot() or paintEntireComponent().
  20017. @param g the graphics context that must be used to do the drawing operations.
  20018. @see repaint, paintOverChildren, Graphics
  20019. */
  20020. virtual void paint (Graphics& g);
  20021. /** Components can override this method to draw over the top of their children.
  20022. For most drawing operations, it's better to use the normal paint() method,
  20023. but if you need to overlay something on top of the children, this can be
  20024. used.
  20025. @see paint, Graphics
  20026. */
  20027. virtual void paintOverChildren (Graphics& g);
  20028. /** Called when the mouse moves inside this component.
  20029. If the mouse button isn't pressed and the mouse moves over a component,
  20030. this will be called to let the component react to this.
  20031. A component will always get a mouseEnter callback before a mouseMove.
  20032. @param e details about the position and status of the mouse event
  20033. @see mouseEnter, mouseExit, mouseDrag, contains
  20034. */
  20035. virtual void mouseMove (const MouseEvent& e);
  20036. /** Called when the mouse first enters this component.
  20037. If the mouse button isn't pressed and the mouse moves into a component,
  20038. this will be called to let the component react to this.
  20039. When the mouse button is pressed and held down while being moved in
  20040. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  20041. mouseDrag messages are sent to the component that the mouse was originally
  20042. clicked on, until the button is released.
  20043. If you're writing a component that needs to repaint itself when the mouse
  20044. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  20045. method.
  20046. @param e details about the position and status of the mouse event
  20047. @see mouseExit, mouseDrag, mouseMove, contains
  20048. */
  20049. virtual void mouseEnter (const MouseEvent& e);
  20050. /** Called when the mouse moves out of this component.
  20051. This will be called when the mouse moves off the edge of this
  20052. component.
  20053. If the mouse button was pressed, and it was then dragged off the
  20054. edge of the component and released, then this callback will happen
  20055. when the button is released, after the mouseUp callback.
  20056. If you're writing a component that needs to repaint itself when the mouse
  20057. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  20058. method.
  20059. @param e details about the position and status of the mouse event
  20060. @see mouseEnter, mouseDrag, mouseMove, contains
  20061. */
  20062. virtual void mouseExit (const MouseEvent& e);
  20063. /** Called when a mouse button is pressed while it's over this component.
  20064. The MouseEvent object passed in contains lots of methods for finding out
  20065. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  20066. were held down at the time.
  20067. Once a button is held down, the mouseDrag method will be called when the
  20068. mouse moves, until the button is released.
  20069. @param e details about the position and status of the mouse event
  20070. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  20071. */
  20072. virtual void mouseDown (const MouseEvent& e);
  20073. /** Called when the mouse is moved while a button is held down.
  20074. When a mouse button is pressed inside a component, that component
  20075. receives mouseDrag callbacks each time the mouse moves, even if the
  20076. mouse strays outside the component's bounds.
  20077. If you want to be able to drag things off the edge of a component
  20078. and have the component scroll when you get to the edges, the
  20079. beginDragAutoRepeat() method might be useful.
  20080. @param e details about the position and status of the mouse event
  20081. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  20082. */
  20083. virtual void mouseDrag (const MouseEvent& e);
  20084. /** Called when a mouse button is released.
  20085. A mouseUp callback is sent to the component in which a button was pressed
  20086. even if the mouse is actually over a different component when the
  20087. button is released.
  20088. The MouseEvent object passed in contains lots of methods for finding out
  20089. which buttons were down just before they were released.
  20090. @param e details about the position and status of the mouse event
  20091. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  20092. */
  20093. virtual void mouseUp (const MouseEvent& e);
  20094. /** Called when a mouse button has been double-clicked in this component.
  20095. The MouseEvent object passed in contains lots of methods for finding out
  20096. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  20097. were held down at the time.
  20098. For altering the time limit used to detect double-clicks,
  20099. see MouseEvent::setDoubleClickTimeout.
  20100. @param e details about the position and status of the mouse event
  20101. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  20102. MouseEvent::getDoubleClickTimeout
  20103. */
  20104. virtual void mouseDoubleClick (const MouseEvent& e);
  20105. /** Called when the mouse-wheel is moved.
  20106. This callback is sent to the component that the mouse is over when the
  20107. wheel is moved.
  20108. If not overridden, the component will forward this message to its parent, so
  20109. that parent components can collect mouse-wheel messages that happen to
  20110. child components which aren't interested in them.
  20111. @param e details about the position and status of the mouse event
  20112. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  20113. value means the wheel has been pushed to the right, negative means it
  20114. was pushed to the left
  20115. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  20116. value means the wheel has been pushed upwards, negative means it
  20117. was pushed downwards
  20118. */
  20119. virtual void mouseWheelMove (const MouseEvent& e,
  20120. float wheelIncrementX,
  20121. float wheelIncrementY);
  20122. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  20123. next mouse-drag operation.
  20124. This allows you to make sure that mouseDrag() events sent continuously, even
  20125. when the mouse isn't moving. This can be useful for things like auto-scrolling
  20126. components when the mouse is near an edge.
  20127. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  20128. minimum interval between consecutive mouse drag callbacks. The callbacks
  20129. will continue until the mouse is released, and then the interval will be reset,
  20130. so you need to make sure it's called every time you begin a drag event. If it
  20131. is called when the mouse isn't actually being pressed, it will apply to the next
  20132. mouse-drag operation that happens.
  20133. Passing an interval of 0 or less will cancel the auto-repeat.
  20134. @see mouseDrag
  20135. */
  20136. static void beginDragAutoRepeat (int millisecondIntervalBetweenCallbacks);
  20137. /** Causes automatic repaints when the mouse enters or exits this component.
  20138. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  20139. on the component, it will trigger a repaint.
  20140. This is handy for things like buttons that need to draw themselves differently when
  20141. the mouse moves over them, and it avoids having to override all the different mouse
  20142. callbacks and call repaint().
  20143. @see mouseEnter, mouseExit, mouseDown, mouseUp
  20144. */
  20145. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  20146. /** Registers a listener to be told when mouse events occur in this component.
  20147. If you need to get informed about mouse events in a component but can't or
  20148. don't want to override its methods, you can attach any number of listeners
  20149. to the component, and these will get told about the events in addition to
  20150. the component's own callbacks being called.
  20151. Note that a MouseListener can also be attached to more than one component.
  20152. @param newListener the listener to register
  20153. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  20154. for events that happen to any child component
  20155. within this component, including deeply-nested
  20156. child components. If false, it will only be
  20157. told about events that this component handles.
  20158. @see MouseListener, removeMouseListener
  20159. */
  20160. void addMouseListener (MouseListener* newListener,
  20161. bool wantsEventsForAllNestedChildComponents);
  20162. /** Deregisters a mouse listener.
  20163. @see addMouseListener, MouseListener
  20164. */
  20165. void removeMouseListener (MouseListener* listenerToRemove);
  20166. /** Adds a listener that wants to hear about keypresses that this component receives.
  20167. The listeners that are registered with a component are called by its keyPressed() or
  20168. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  20169. If you add an object as a key listener, be careful to remove it when the object
  20170. is deleted, or the component will be left with a dangling pointer.
  20171. @see keyPressed, keyStateChanged, removeKeyListener
  20172. */
  20173. void addKeyListener (KeyListener* newListener);
  20174. /** Removes a previously-registered key listener.
  20175. @see addKeyListener
  20176. */
  20177. void removeKeyListener (KeyListener* listenerToRemove);
  20178. /** Called when a key is pressed.
  20179. When a key is pressed, the component that has the keyboard focus will have this
  20180. method called. Remember that a component will only be given the focus if its
  20181. setWantsKeyboardFocus() method has been used to enable this.
  20182. If your implementation returns true, the event will be consumed and not passed
  20183. on to any other listeners. If it returns false, the key will be passed to any
  20184. KeyListeners that have been registered with this component. As soon as one of these
  20185. returns true, the process will stop, but if they all return false, the event will
  20186. be passed upwards to this component's parent, and so on.
  20187. The default implementation of this method does nothing and returns false.
  20188. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  20189. */
  20190. virtual bool keyPressed (const KeyPress& key);
  20191. /** Called when a key is pressed or released.
  20192. Whenever a key on the keyboard is pressed or released (including modifier keys
  20193. like shift and ctrl), this method will be called on the component that currently
  20194. has the keyboard focus. Remember that a component will only be given the focus if
  20195. its setWantsKeyboardFocus() method has been used to enable this.
  20196. If your implementation returns true, the event will be consumed and not passed
  20197. on to any other listeners. If it returns false, then any KeyListeners that have
  20198. been registered with this component will have their keyStateChanged methods called.
  20199. As soon as one of these returns true, the process will stop, but if they all return
  20200. false, the event will be passed upwards to this component's parent, and so on.
  20201. The default implementation of this method does nothing and returns false.
  20202. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  20203. method.
  20204. @param isKeyDown true if a key has been pressed; false if it has been released
  20205. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  20206. */
  20207. virtual bool keyStateChanged (bool isKeyDown);
  20208. /** Called when a modifier key is pressed or released.
  20209. Whenever the shift, control, alt or command keys are pressed or released,
  20210. this method will be called on the component that currently has the keyboard focus.
  20211. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  20212. method has been used to enable this.
  20213. The default implementation of this method actually calls its parent's modifierKeysChanged
  20214. method, so that focused components which aren't interested in this will give their
  20215. parents a chance to act on the event instead.
  20216. @see keyStateChanged, ModifierKeys
  20217. */
  20218. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  20219. /** Enumeration used by the focusChanged() and focusLost() methods. */
  20220. enum FocusChangeType
  20221. {
  20222. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  20223. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  20224. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  20225. };
  20226. /** Called to indicate that this component has just acquired the keyboard focus.
  20227. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20228. */
  20229. virtual void focusGained (FocusChangeType cause);
  20230. /** Called to indicate that this component has just lost the keyboard focus.
  20231. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20232. */
  20233. virtual void focusLost (FocusChangeType cause);
  20234. /** Called to indicate that one of this component's children has been focused or unfocused.
  20235. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  20236. changed. It happens when focus moves from one of this component's children (at any depth)
  20237. to a component that isn't contained in this one, (or vice-versa).
  20238. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20239. */
  20240. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  20241. /** Returns true if the mouse is currently over this component.
  20242. If the mouse isn't over the component, this will return false, even if the
  20243. mouse is currently being dragged - so you can use this in your mouseDrag
  20244. method to find out whether it's really over the component or not.
  20245. Note that when the mouse button is being held down, then the only component
  20246. for which this method will return true is the one that was originally
  20247. clicked on.
  20248. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  20249. */
  20250. bool isMouseOver() const throw();
  20251. /** Returns true if the mouse button is currently held down in this component.
  20252. Note that this is a test to see whether the mouse is being pressed in this
  20253. component, so it'll return false if called on component A when the mouse
  20254. is actually being dragged in component B.
  20255. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  20256. */
  20257. bool isMouseButtonDown() const throw();
  20258. /** True if the mouse is over this component, or if it's being dragged in this component.
  20259. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  20260. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  20261. */
  20262. bool isMouseOverOrDragging() const throw();
  20263. /** Returns true if a mouse button is currently down.
  20264. Unlike isMouseButtonDown, this will test the current state of the
  20265. buttons without regard to which component (if any) it has been
  20266. pressed in.
  20267. @see isMouseButtonDown, ModifierKeys
  20268. */
  20269. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  20270. /** Returns the mouse's current position, relative to this component.
  20271. The co-ordinates are relative to the component's top-left corner.
  20272. */
  20273. const Point<int> getMouseXYRelative() const;
  20274. /** Called when this component's size has been changed.
  20275. A component can implement this method to do things such as laying out its
  20276. child components when its width or height changes.
  20277. The method is called synchronously as a result of the setBounds or setSize
  20278. methods, so repeatedly changing a components size will repeatedly call its
  20279. resized method (unlike things like repainting, where multiple calls to repaint
  20280. are coalesced together).
  20281. If the component is a top-level window on the desktop, its size could also
  20282. be changed by operating-system factors beyond the application's control.
  20283. @see moved, setSize
  20284. */
  20285. virtual void resized();
  20286. /** Called when this component's position has been changed.
  20287. This is called when the position relative to its parent changes, not when
  20288. its absolute position on the screen changes (so it won't be called for
  20289. all child components when a parent component is moved).
  20290. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  20291. or any of the other repositioning methods, and like resized(), it will be
  20292. called each time those methods are called.
  20293. If the component is a top-level window on the desktop, its position could also
  20294. be changed by operating-system factors beyond the application's control.
  20295. @see resized, setBounds
  20296. */
  20297. virtual void moved();
  20298. /** Called when one of this component's children is moved or resized.
  20299. If the parent wants to know about changes to its immediate children (not
  20300. to children of its children), this is the method to override.
  20301. @see moved, resized, parentSizeChanged
  20302. */
  20303. virtual void childBoundsChanged (Component* child);
  20304. /** Called when this component's immediate parent has been resized.
  20305. If the component is a top-level window, this indicates that the screen size
  20306. has changed.
  20307. @see childBoundsChanged, moved, resized
  20308. */
  20309. virtual void parentSizeChanged();
  20310. /** Called when this component has been moved to the front of its siblings.
  20311. The component may have been brought to the front by the toFront() method, or
  20312. by the operating system if it's a top-level window.
  20313. @see toFront
  20314. */
  20315. virtual void broughtToFront();
  20316. /** Adds a listener to be told about changes to the component hierarchy or position.
  20317. Component listeners get called when this component's size, position or children
  20318. change - see the ComponentListener class for more details.
  20319. @param newListener the listener to register - if this is already registered, it
  20320. will be ignored.
  20321. @see ComponentListener, removeComponentListener
  20322. */
  20323. void addComponentListener (ComponentListener* newListener);
  20324. /** Removes a component listener.
  20325. @see addComponentListener
  20326. */
  20327. void removeComponentListener (ComponentListener* listenerToRemove);
  20328. /** Dispatches a numbered message to this component.
  20329. This is a quick and cheap way of allowing simple asynchronous messages to
  20330. be sent to components. It's also safe, because if the component that you
  20331. send the message to is a null or dangling pointer, this won't cause an error.
  20332. The command ID is later delivered to the component's handleCommandMessage() method by
  20333. the application's message queue.
  20334. @see handleCommandMessage
  20335. */
  20336. void postCommandMessage (int commandId);
  20337. /** Called to handle a command that was sent by postCommandMessage().
  20338. This is called by the message thread when a command message arrives, and
  20339. the component can override this method to process it in any way it needs to.
  20340. @see postCommandMessage
  20341. */
  20342. virtual void handleCommandMessage (int commandId);
  20343. /** Runs a component modally, waiting until the loop terminates.
  20344. This method first makes the component visible, brings it to the front and
  20345. gives it the keyboard focus.
  20346. It then runs a loop, dispatching messages from the system message queue, but
  20347. blocking all mouse or keyboard messages from reaching any components other
  20348. than this one and its children.
  20349. This loop continues until the component's exitModalState() method is called (or
  20350. the component is deleted), and then this method returns, returning the value
  20351. passed into exitModalState().
  20352. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  20353. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  20354. */
  20355. int runModalLoop();
  20356. /** Puts the component into a modal state.
  20357. This makes the component modal, so that messages are blocked from reaching
  20358. any components other than this one and its children, but unlike runModalLoop(),
  20359. this method returns immediately.
  20360. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  20361. get the focus, which is usually what you'll want it to do. If not, it will leave
  20362. the focus unchanged.
  20363. The callback is an optional object which will receive a callback when the modal
  20364. component loses its modal status, either by being hidden or when exitModalState()
  20365. is called. If you pass an object in here, the system will take care of deleting it
  20366. later, after making the callback
  20367. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  20368. */
  20369. void enterModalState (bool takeKeyboardFocus = true,
  20370. ModalComponentManager::Callback* callback = 0);
  20371. /** Ends a component's modal state.
  20372. If this component is currently modal, this will turn of its modalness, and return
  20373. a value to the runModalLoop() method that might have be running its modal loop.
  20374. @see runModalLoop, enterModalState, isCurrentlyModal
  20375. */
  20376. void exitModalState (int returnValue);
  20377. /** Returns true if this component is the modal one.
  20378. It's possible to have nested modal components, e.g. a pop-up dialog box
  20379. that launches another pop-up, but this will only return true for
  20380. the one at the top of the stack.
  20381. @see getCurrentlyModalComponent
  20382. */
  20383. bool isCurrentlyModal() const throw();
  20384. /** Returns the number of components that are currently in a modal state.
  20385. @see getCurrentlyModalComponent
  20386. */
  20387. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  20388. /** Returns one of the components that are currently modal.
  20389. The index specifies which of the possible modal components to return. The order
  20390. of the components in this list is the reverse of the order in which they became
  20391. modal - so the component at index 0 is always the active component, and the others
  20392. are progressively earlier ones that are themselves now blocked by later ones.
  20393. @returns the modal component, or null if no components are modal (or if the
  20394. index is out of range)
  20395. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  20396. */
  20397. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  20398. /** Checks whether there's a modal component somewhere that's stopping this one
  20399. from receiving messages.
  20400. If there is a modal component, its canModalEventBeSentToComponent() method
  20401. will be called to see if it will still allow this component to receive events.
  20402. @see runModalLoop, getCurrentlyModalComponent
  20403. */
  20404. bool isCurrentlyBlockedByAnotherModalComponent() const;
  20405. /** When a component is modal, this callback allows it to choose which other
  20406. components can still receive events.
  20407. When a modal component is active and the user clicks on a non-modal component,
  20408. this method is called on the modal component, and if it returns true, the
  20409. event is allowed to reach its target. If it returns false, the event is blocked
  20410. and the inputAttemptWhenModal() callback is made.
  20411. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  20412. implementation just returns false in all cases.
  20413. */
  20414. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  20415. /** Called when the user tries to click on a component that is blocked by another
  20416. modal component.
  20417. When a component is modal and the user clicks on one of the other components,
  20418. the modal component will receive this callback.
  20419. The default implementation of this method will play a beep, and bring the currently
  20420. modal component to the front, but it can be overridden to do other tasks.
  20421. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  20422. */
  20423. virtual void inputAttemptWhenModal();
  20424. /** Returns the set of properties that belong to this component.
  20425. Each component has a NamedValueSet object which you can use to attach arbitrary
  20426. items of data to it.
  20427. */
  20428. NamedValueSet& getProperties() throw() { return properties; }
  20429. /** Returns the set of properties that belong to this component.
  20430. Each component has a NamedValueSet object which you can use to attach arbitrary
  20431. items of data to it.
  20432. */
  20433. const NamedValueSet& getProperties() const throw() { return properties; }
  20434. /** Looks for a colour that has been registered with the given colour ID number.
  20435. If a colour has been set for this ID number using setColour(), then it is
  20436. returned. If none has been set, the method will try calling the component's
  20437. LookAndFeel class's findColour() method. If none has been registered with the
  20438. look-and-feel either, it will just return black.
  20439. The colour IDs for various purposes are stored as enums in the components that
  20440. they are relevent to - for an example, see Slider::ColourIds,
  20441. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  20442. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20443. */
  20444. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  20445. /** Registers a colour to be used for a particular purpose.
  20446. Changing a colour will cause a synchronous callback to the colourChanged()
  20447. method, which your component can override if it needs to do something when
  20448. colours are altered.
  20449. For more details about colour IDs, see the comments for findColour().
  20450. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20451. */
  20452. void setColour (int colourId, const Colour& colour);
  20453. /** If a colour has been set with setColour(), this will remove it.
  20454. This allows you to make a colour revert to its default state.
  20455. */
  20456. void removeColour (int colourId);
  20457. /** Returns true if the specified colour ID has been explicitly set for this
  20458. component using the setColour() method.
  20459. */
  20460. bool isColourSpecified (int colourId) const;
  20461. /** This looks for any colours that have been specified for this component,
  20462. and copies them to the specified target component.
  20463. */
  20464. void copyAllExplicitColoursTo (Component& target) const;
  20465. /** This method is called when a colour is changed by the setColour() method.
  20466. @see setColour, findColour
  20467. */
  20468. virtual void colourChanged();
  20469. /** Returns the underlying native window handle for this component.
  20470. This is platform-dependent and strictly for power-users only!
  20471. */
  20472. void* getWindowHandle() const;
  20473. /** When created, each component is given a number to uniquely identify it.
  20474. The number is incremented each time a new component is created, so it's a more
  20475. unique way of identifying a component than using its memory location (which
  20476. may be reused after the component is deleted, of course).
  20477. */
  20478. uint32 getComponentUID() const throw() { return componentUID; }
  20479. /** Holds a pointer to some type of Component, which automatically becomes null if
  20480. the component is deleted.
  20481. If you're using a component which may be deleted by another event that's outside
  20482. of your control, use a SafePointer instead of a normal pointer to refer to it,
  20483. and you can test whether it's null before using it to see if something has deleted
  20484. it.
  20485. The ComponentType typedef must be Component, or some subclass of Component.
  20486. Note that this class isn't thread-safe, and assumes that all the code that uses
  20487. it is running on the message thread.
  20488. */
  20489. template <class ComponentType>
  20490. class SafePointer : private ComponentListener
  20491. {
  20492. public:
  20493. /** Creates a null SafePointer. */
  20494. SafePointer() : comp (0) {}
  20495. /** Creates a SafePointer that points at the given component. */
  20496. SafePointer (ComponentType* const component) : comp (component) { attach(); }
  20497. /** Creates a copy of another SafePointer. */
  20498. SafePointer (const SafePointer& other) : comp (other.comp) { attach(); }
  20499. /** Destructor. */
  20500. ~SafePointer() { detach(); }
  20501. /** Copies another pointer to this one. */
  20502. SafePointer& operator= (const SafePointer& other) { return operator= (other.comp); }
  20503. /** Copies another pointer to this one. */
  20504. SafePointer& operator= (ComponentType* const newComponent)
  20505. {
  20506. detach();
  20507. comp = newComponent;
  20508. attach();
  20509. return *this;
  20510. }
  20511. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20512. operator ComponentType*() const throw() { return comp; }
  20513. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20514. ComponentType* getComponent() const throw() { return comp; }
  20515. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20516. ComponentType* operator->() throw() { jassert (comp != 0); return comp; }
  20517. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20518. const ComponentType* operator->() const throw() { jassert (comp != 0); return comp; }
  20519. juce_UseDebuggingNewOperator
  20520. private:
  20521. ComponentType* comp;
  20522. void attach() { if (comp != 0) comp->addComponentListener (this); }
  20523. void detach() { if (comp != 0) comp->removeComponentListener (this); }
  20524. void componentBeingDeleted (Component&) { comp = 0; }
  20525. };
  20526. /** A class to keep an eye on one or two components and check for them being deleted.
  20527. This is designed for use with the ListenerList::callChecked() methods, to allow
  20528. the list iterator to stop cleanly if the component is deleted by a listener callback
  20529. while the list is still being iterated.
  20530. */
  20531. class BailOutChecker
  20532. {
  20533. public:
  20534. /** Creates a checker that watches either one or two components.
  20535. component1 must be a valid component; component2 can be null if you only need
  20536. to check on one component.
  20537. */
  20538. BailOutChecker (Component* component1,
  20539. Component* component2 = 0);
  20540. /** Returns true if either of the two components have been deleted since this
  20541. object was created. */
  20542. bool shouldBailOut() const throw();
  20543. private:
  20544. typedef SafePointer<Component> SafeComponentPtr;
  20545. SafeComponentPtr safePointer1, safePointer2;
  20546. Component* const component2;
  20547. BailOutChecker (const BailOutChecker&);
  20548. BailOutChecker& operator= (const BailOutChecker&);
  20549. };
  20550. juce_UseDebuggingNewOperator
  20551. private:
  20552. friend class ComponentPeer;
  20553. friend class InternalDragRepeater;
  20554. friend class MouseInputSource;
  20555. friend class MouseInputSourceInternal;
  20556. static Component* currentlyFocusedComponent;
  20557. String componentName_;
  20558. Component* parentComponent_;
  20559. uint32 componentUID;
  20560. Rectangle<int> bounds_;
  20561. int numDeepMouseListeners;
  20562. Array <Component*> childComponentList_;
  20563. LookAndFeel* lookAndFeel_;
  20564. MouseCursor cursor_;
  20565. ImageEffectFilter* effect_;
  20566. Image bufferedImage_;
  20567. Array <MouseListener*>* mouseListeners_;
  20568. Array <KeyListener*>* keyListeners_;
  20569. ListenerList <ComponentListener> componentListeners;
  20570. NamedValueSet properties;
  20571. struct ComponentFlags
  20572. {
  20573. bool hasHeavyweightPeerFlag : 1;
  20574. bool visibleFlag : 1;
  20575. bool opaqueFlag : 1;
  20576. bool ignoresMouseClicksFlag : 1;
  20577. bool allowChildMouseClicksFlag : 1;
  20578. bool wantsFocusFlag : 1;
  20579. bool isFocusContainerFlag : 1;
  20580. bool dontFocusOnMouseClickFlag : 1;
  20581. bool alwaysOnTopFlag : 1;
  20582. bool bufferToImageFlag : 1;
  20583. bool bringToFrontOnClickFlag : 1;
  20584. bool repaintOnMouseActivityFlag : 1;
  20585. bool draggingFlag : 1;
  20586. bool mouseOverFlag : 1;
  20587. bool mouseInsideFlag : 1;
  20588. bool currentlyModalFlag : 1;
  20589. bool isDisabledFlag : 1;
  20590. bool childCompFocusedFlag : 1;
  20591. #if JUCE_DEBUG
  20592. bool isInsidePaintCall : 1;
  20593. #endif
  20594. };
  20595. union
  20596. {
  20597. uint32 componentFlags_;
  20598. ComponentFlags flags;
  20599. };
  20600. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20601. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20602. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20603. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  20604. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20605. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20606. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  20607. void internalBroughtToFront();
  20608. void internalFocusGain (const FocusChangeType cause);
  20609. void internalFocusLoss (const FocusChangeType cause);
  20610. void internalChildFocusChange (FocusChangeType cause);
  20611. void internalModalInputAttempt();
  20612. void internalModifierKeysChanged();
  20613. void internalChildrenChanged();
  20614. void internalHierarchyChanged();
  20615. void renderComponent (Graphics& context);
  20616. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  20617. void repaintParent();
  20618. void sendFakeMouseMove() const;
  20619. void takeKeyboardFocus (const FocusChangeType cause);
  20620. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  20621. static void giveAwayFocus();
  20622. void sendEnablementChangeMessage();
  20623. static void* runModalLoopCallback (void*);
  20624. static void bringModalComponentToFront();
  20625. void subtractObscuredRegions (RectangleList& result, const Point<int>& delta,
  20626. const Rectangle<int>& clipRect,
  20627. const Component* const compToAvoid) const;
  20628. void clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  20629. int deltaX, int deltaY) const;
  20630. // how much of the component is not off the edges of its parents
  20631. const Rectangle<int> getUnclippedArea() const;
  20632. void sendVisibilityChangeMessage();
  20633. const Rectangle<int> getParentOrMainMonitorBounds() const;
  20634. // This is included here just to cause a compile error if your code is still handling
  20635. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  20636. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  20637. // implement its methods instead of this Component method).
  20638. virtual void filesDropped (const StringArray&, int, int) {}
  20639. // components aren't allowed to have copy constructors, as this would mess up parent
  20640. // hierarchies. You might need to give your subclasses a private dummy constructor like
  20641. // this one to avoid compiler warnings.
  20642. Component (const Component&);
  20643. Component& operator= (const Component&);
  20644. protected:
  20645. /** @internal */
  20646. virtual void internalRepaint (int x, int y, int w, int h);
  20647. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  20648. /** Overridden from the MessageListener parent class.
  20649. You can override this if you really need to, but be sure to pass your unwanted messages up
  20650. to this base class implementation, as the Component class needs to send itself messages
  20651. to work properly.
  20652. */
  20653. void handleMessage (const Message&);
  20654. };
  20655. #endif // __JUCE_COMPONENT_JUCEHEADER__
  20656. /*** End of inlined file: juce_Component.h ***/
  20657. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  20658. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20659. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20660. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  20661. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20662. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20663. /** A type used to hold the unique ID for an application command.
  20664. This is a numeric type, so it can be stored as an integer.
  20665. @see ApplicationCommandInfo, ApplicationCommandManager,
  20666. ApplicationCommandTarget, KeyPressMappingSet
  20667. */
  20668. typedef int CommandID;
  20669. /** A set of general-purpose application command IDs.
  20670. Because these commands are likely to be used in most apps, they're defined
  20671. here to help different apps to use the same numeric values for them.
  20672. Of course you don't have to use these, but some of them are used internally by
  20673. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  20674. @see ApplicationCommandInfo, ApplicationCommandManager,
  20675. ApplicationCommandTarget, KeyPressMappingSet
  20676. */
  20677. namespace StandardApplicationCommandIDs
  20678. {
  20679. /** This command ID should be used to send a "Quit the App" command.
  20680. This command is recognised by the JUCEApplication class, so if it is invoked
  20681. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  20682. object will catch it and call JUCEApplication::systemRequestedQuit().
  20683. */
  20684. static const CommandID quit = 0x1001;
  20685. /** The command ID that should be used to send a "Delete" command. */
  20686. static const CommandID del = 0x1002;
  20687. /** The command ID that should be used to send a "Cut" command. */
  20688. static const CommandID cut = 0x1003;
  20689. /** The command ID that should be used to send a "Copy to clipboard" command. */
  20690. static const CommandID copy = 0x1004;
  20691. /** The command ID that should be used to send a "Paste from clipboard" command. */
  20692. static const CommandID paste = 0x1005;
  20693. /** The command ID that should be used to send a "Select all" command. */
  20694. static const CommandID selectAll = 0x1006;
  20695. /** The command ID that should be used to send a "Deselect all" command. */
  20696. static const CommandID deselectAll = 0x1007;
  20697. }
  20698. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20699. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  20700. /**
  20701. Holds information describing an application command.
  20702. This object is used to pass information about a particular command, such as its
  20703. name, description and other usage flags.
  20704. When an ApplicationCommandTarget is asked to provide information about the commands
  20705. it can perform, this is the structure gets filled-in to describe each one.
  20706. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  20707. ApplicationCommandManager
  20708. */
  20709. struct JUCE_API ApplicationCommandInfo
  20710. {
  20711. explicit ApplicationCommandInfo (CommandID commandID) throw();
  20712. /** Sets a number of the structures values at once.
  20713. The meanings of each of the parameters is described below, in the appropriate
  20714. member variable's description.
  20715. */
  20716. void setInfo (const String& shortName,
  20717. const String& description,
  20718. const String& categoryName,
  20719. int flags) throw();
  20720. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  20721. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  20722. is false, the bit is set.
  20723. */
  20724. void setActive (bool isActive) throw();
  20725. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  20726. */
  20727. void setTicked (bool isTicked) throw();
  20728. /** Handy method for adding a keypress to the defaultKeypresses array.
  20729. This is just so you can write things like:
  20730. @code
  20731. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  20732. @endcode
  20733. instead of
  20734. @code
  20735. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  20736. @endcode
  20737. */
  20738. void addDefaultKeypress (int keyCode,
  20739. const ModifierKeys& modifiers) throw();
  20740. /** The command's unique ID number.
  20741. */
  20742. CommandID commandID;
  20743. /** A short name to describe the command.
  20744. This should be suitable for use in menus, on buttons that trigger the command, etc.
  20745. You can use the setInfo() method to quickly set this and some of the command's
  20746. other properties.
  20747. */
  20748. String shortName;
  20749. /** A longer description of the command.
  20750. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  20751. pop-up tooltip describing what the command does.
  20752. You can use the setInfo() method to quickly set this and some of the command's
  20753. other properties.
  20754. */
  20755. String description;
  20756. /** A named category that the command fits into.
  20757. You can give your commands any category you like, and these will be displayed in
  20758. contexts such as the KeyMappingEditorComponent, where the category is used to group
  20759. commands together.
  20760. You can use the setInfo() method to quickly set this and some of the command's
  20761. other properties.
  20762. */
  20763. String categoryName;
  20764. /** A list of zero or more keypresses that should be used as the default keys for
  20765. this command.
  20766. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  20767. this list to initialise the default set of key-to-command mappings.
  20768. @see addDefaultKeypress
  20769. */
  20770. Array <KeyPress> defaultKeypresses;
  20771. /** Flags describing the ways in which this command should be used.
  20772. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  20773. variable.
  20774. */
  20775. enum CommandFlags
  20776. {
  20777. /** Indicates that the command can't currently be performed.
  20778. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  20779. not currently permissable to perform the command. If the flag is set, then
  20780. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  20781. command or show themselves as not being enabled.
  20782. @see ApplicationCommandInfo::setActive
  20783. */
  20784. isDisabled = 1 << 0,
  20785. /** Indicates that the command should have a tick next to it on a menu.
  20786. If your command is shown on a menu and this is set, it'll show a tick next to
  20787. it. Other components such as buttons may also use this flag to indicate that it
  20788. is a value that can be toggled, and is currently in the 'on' state.
  20789. @see ApplicationCommandInfo::setTicked
  20790. */
  20791. isTicked = 1 << 1,
  20792. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  20793. it will call the command twice, once on key-down and again on key-up.
  20794. @see ApplicationCommandTarget::InvocationInfo
  20795. */
  20796. wantsKeyUpDownCallbacks = 1 << 2,
  20797. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  20798. command in its list.
  20799. */
  20800. hiddenFromKeyEditor = 1 << 3,
  20801. /** If this flag is present, then a KeyMappingEditorComponent will display the
  20802. command in its list, but won't allow the assigned keypress to be changed.
  20803. */
  20804. readOnlyInKeyEditor = 1 << 4,
  20805. /** If this flag is present and the command is invoked from a keypress, then any
  20806. buttons or menus that are also connected to the command will not flash to
  20807. indicate that they've been triggered.
  20808. */
  20809. dontTriggerVisualFeedback = 1 << 5
  20810. };
  20811. /** A bitwise-OR of the values specified in the CommandFlags enum.
  20812. You can use the setInfo() method to quickly set this and some of the command's
  20813. other properties.
  20814. */
  20815. int flags;
  20816. };
  20817. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20818. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  20819. /**
  20820. A command target publishes a list of command IDs that it can perform.
  20821. An ApplicationCommandManager despatches commands to targets, which must be
  20822. able to provide information about what commands they can handle.
  20823. To create a target, you'll need to inherit from this class, implementing all of
  20824. its pure virtual methods.
  20825. For info about how a target is chosen to receive a command, see
  20826. ApplicationCommandManager::getFirstCommandTarget().
  20827. @see ApplicationCommandManager, ApplicationCommandInfo
  20828. */
  20829. class JUCE_API ApplicationCommandTarget
  20830. {
  20831. public:
  20832. /** Creates a command target. */
  20833. ApplicationCommandTarget();
  20834. /** Destructor. */
  20835. virtual ~ApplicationCommandTarget();
  20836. /**
  20837. */
  20838. struct JUCE_API InvocationInfo
  20839. {
  20840. InvocationInfo (const CommandID commandID) throw();
  20841. /** The UID of the command that should be performed. */
  20842. CommandID commandID;
  20843. /** The command's flags.
  20844. See ApplicationCommandInfo for a description of these flag values.
  20845. */
  20846. int commandFlags;
  20847. /** The types of context in which the command might be called. */
  20848. enum InvocationMethod
  20849. {
  20850. direct = 0, /**< The command is being invoked directly by a piece of code. */
  20851. fromKeyPress, /**< The command is being invoked by a key-press. */
  20852. fromMenu, /**< The command is being invoked by a menu selection. */
  20853. fromButton /**< The command is being invoked by a button click. */
  20854. };
  20855. /** The type of event that triggered this command. */
  20856. InvocationMethod invocationMethod;
  20857. /** If triggered by a keypress or menu, this will be the component that had the
  20858. keyboard focus at the time.
  20859. If triggered by a button, it may be set to that component, or it may be null.
  20860. */
  20861. Component* originatingComponent;
  20862. /** The keypress that was used to invoke it.
  20863. Note that this will be an invalid keypress if the command was invoked
  20864. by some other means than a keyboard shortcut.
  20865. */
  20866. KeyPress keyPress;
  20867. /** True if the callback is being invoked when the key is pressed,
  20868. false if the key is being released.
  20869. @see KeyPressMappingSet::addCommand()
  20870. */
  20871. bool isKeyDown;
  20872. /** If the key is being released, this indicates how long it had been held
  20873. down for.
  20874. (Only relevant if isKeyDown is false.)
  20875. */
  20876. int millisecsSinceKeyPressed;
  20877. };
  20878. /** This must return the next target to try after this one.
  20879. When a command is being sent, and the first target can't handle
  20880. that command, this method is used to determine the next target that should
  20881. be tried.
  20882. It may return 0 if it doesn't know of another target.
  20883. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  20884. method to return a parent component that might want to handle it.
  20885. @see invoke
  20886. */
  20887. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  20888. /** This must return a complete list of commands that this target can handle.
  20889. Your target should add all the command IDs that it handles to the array that is
  20890. passed-in.
  20891. */
  20892. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  20893. /** This must provide details about one of the commands that this target can perform.
  20894. This will be called with one of the command IDs that the target provided in its
  20895. getAllCommands() methods.
  20896. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  20897. suitable information about the command. (The commandID field will already have been filled-in
  20898. by the caller).
  20899. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  20900. set all the fields at once.
  20901. If the command is currently inactive for some reason, this method must use
  20902. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  20903. bit of the ApplicationCommandInfo::flags field).
  20904. Any default key-presses for the command should be appended to the
  20905. ApplicationCommandInfo::defaultKeypresses field.
  20906. Note that if you change something that affects the status of the commands
  20907. that would be returned by this method (e.g. something that makes some commands
  20908. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  20909. to cause the manager to refresh its status.
  20910. */
  20911. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  20912. /** This must actually perform the specified command.
  20913. If this target is able to perform the command specified by the commandID field of the
  20914. InvocationInfo structure, then it should do so, and must return true.
  20915. If it can't handle this command, it should return false, which tells the caller to pass
  20916. the command on to the next target in line.
  20917. @see invoke, ApplicationCommandManager::invoke
  20918. */
  20919. virtual bool perform (const InvocationInfo& info) = 0;
  20920. /** Makes this target invoke a command.
  20921. Your code can call this method to invoke a command on this target, but normally
  20922. you'd call it indirectly via ApplicationCommandManager::invoke() or
  20923. ApplicationCommandManager::invokeDirectly().
  20924. If this target can perform the given command, it will call its perform() method to
  20925. do so. If not, then getNextCommandTarget() will be used to determine the next target
  20926. to try, and the command will be passed along to it.
  20927. @param invocationInfo this must be correctly filled-in, describing the context for
  20928. the invocation.
  20929. @param asynchronously if false, the command will be performed before this method returns.
  20930. If true, a message will be posted so that the command will be performed
  20931. later on the message thread, and this method will return immediately.
  20932. @see perform, ApplicationCommandManager::invoke
  20933. */
  20934. bool invoke (const InvocationInfo& invocationInfo,
  20935. const bool asynchronously);
  20936. /** Invokes a given command directly on this target.
  20937. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  20938. structure.
  20939. */
  20940. bool invokeDirectly (const CommandID commandID,
  20941. const bool asynchronously);
  20942. /** Searches this target and all subsequent ones for the first one that can handle
  20943. the specified command.
  20944. This will use getNextCommandTarget() to determine the chain of targets to try
  20945. after this one.
  20946. */
  20947. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  20948. /** Checks whether this command can currently be performed by this target.
  20949. This will return true only if a call to getCommandInfo() doesn't set the
  20950. isDisabled flag to indicate that the command is inactive.
  20951. */
  20952. bool isCommandActive (const CommandID commandID);
  20953. /** If this object is a Component, this method will seach upwards in its current
  20954. UI hierarchy for the next parent component that implements the
  20955. ApplicationCommandTarget class.
  20956. If your target is a Component, this is a very handy method to use in your
  20957. getNextCommandTarget() implementation.
  20958. */
  20959. ApplicationCommandTarget* findFirstTargetParentComponent();
  20960. juce_UseDebuggingNewOperator
  20961. private:
  20962. // (for async invocation of commands)
  20963. class CommandTargetMessageInvoker : public MessageListener
  20964. {
  20965. public:
  20966. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  20967. ~CommandTargetMessageInvoker();
  20968. void handleMessage (const Message& message);
  20969. private:
  20970. ApplicationCommandTarget* const owner;
  20971. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  20972. CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  20973. };
  20974. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  20975. friend class CommandTargetMessageInvoker;
  20976. bool tryToInvoke (const InvocationInfo& info, const bool async);
  20977. ApplicationCommandTarget (const ApplicationCommandTarget&);
  20978. ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  20979. };
  20980. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  20981. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  20982. /*** Start of inlined file: juce_ActionListener.h ***/
  20983. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  20984. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  20985. /**
  20986. Receives callbacks to indicate that some kind of event has occurred.
  20987. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  20988. about something that's happened.
  20989. @see ActionListenerList, ActionBroadcaster, ChangeListener
  20990. */
  20991. class JUCE_API ActionListener
  20992. {
  20993. public:
  20994. /** Destructor. */
  20995. virtual ~ActionListener() {}
  20996. /** Overridden by your subclass to receive the callback.
  20997. @param message the string that was specified when the event was triggered
  20998. by a call to ActionListenerList::sendActionMessage()
  20999. */
  21000. virtual void actionListenerCallback (const String& message) = 0;
  21001. };
  21002. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  21003. /*** End of inlined file: juce_ActionListener.h ***/
  21004. /**
  21005. An instance of this class is used to specify initialisation and shutdown
  21006. code for the application.
  21007. An application that wants to run in the JUCE framework needs to declare a
  21008. subclass of JUCEApplication and implement its various pure virtual methods.
  21009. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  21010. to declare an instance of this class and generate a suitable platform-specific
  21011. main() function.
  21012. e.g. @code
  21013. class MyJUCEApp : public JUCEApplication
  21014. {
  21015. // NEVER put objects inside a JUCEApplication class - only use pointers to
  21016. // objects, which you must create in the initialise() method.
  21017. MyApplicationWindow* myMainWindow;
  21018. public:
  21019. MyJUCEApp()
  21020. : myMainWindow (0)
  21021. {
  21022. // never create any Juce objects in the constructor - do all your initialisation
  21023. // in the initialise() method.
  21024. }
  21025. ~MyJUCEApp()
  21026. {
  21027. // all your shutdown code must have already been done in the shutdown() method -
  21028. // nothing should happen in this destructor.
  21029. }
  21030. void initialise (const String& commandLine)
  21031. {
  21032. myMainWindow = new MyApplicationWindow();
  21033. myMainWindow->setBounds (100, 100, 400, 500);
  21034. myMainWindow->setVisible (true);
  21035. }
  21036. void shutdown()
  21037. {
  21038. delete myMainWindow;
  21039. }
  21040. const String getApplicationName()
  21041. {
  21042. return "Super JUCE-o-matic";
  21043. }
  21044. const String getApplicationVersion()
  21045. {
  21046. return "1.0";
  21047. }
  21048. };
  21049. // this creates wrapper code to actually launch the app properly.
  21050. START_JUCE_APPLICATION (MyJUCEApp)
  21051. @endcode
  21052. Because this object will be created before Juce has properly initialised, you must
  21053. NEVER add any member variable objects that will be automatically constructed. Likewise
  21054. don't put ANY code in the constructor that could call Juce functions. Any objects that
  21055. you want to add to the class must be pointers, which you should instantiate during the
  21056. initialise() method, and delete in the shutdown() method.
  21057. @see MessageManager, DeletedAtShutdown
  21058. */
  21059. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  21060. private ActionListener
  21061. {
  21062. protected:
  21063. /** Constructs a JUCE app object.
  21064. If subclasses implement a constructor or destructor, they shouldn't call any
  21065. JUCE code in there - put your startup/shutdown code in initialise() and
  21066. shutdown() instead.
  21067. */
  21068. JUCEApplication();
  21069. public:
  21070. /** Destructor.
  21071. If subclasses implement a constructor or destructor, they shouldn't call any
  21072. JUCE code in there - put your startup/shutdown code in initialise() and
  21073. shutdown() instead.
  21074. */
  21075. virtual ~JUCEApplication();
  21076. /** Returns the global instance of the application object being run. */
  21077. static JUCEApplication* getInstance() throw();
  21078. /** Called when the application starts.
  21079. This will be called once to let the application do whatever initialisation
  21080. it needs, create its windows, etc.
  21081. After the method returns, the normal event-dispatch loop will be run,
  21082. until the quit() method is called, at which point the shutdown()
  21083. method will be called to let the application clear up anything it needs
  21084. to delete.
  21085. If during the initialise() method, the application decides not to start-up
  21086. after all, it can just call the quit() method and the event loop won't be run.
  21087. @param commandLineParameters the line passed in does not include the
  21088. name of the executable, just the parameter list.
  21089. @see shutdown, quit
  21090. */
  21091. virtual void initialise (const String& commandLineParameters) = 0;
  21092. /** Returns true if the application hasn't yet completed its initialise() method
  21093. and entered the main event loop.
  21094. This is handy for things like splash screens to know when the app's up-and-running
  21095. properly.
  21096. */
  21097. bool isInitialising() const throw();
  21098. /* Called to allow the application to clear up before exiting.
  21099. After JUCEApplication::quit() has been called, the event-dispatch loop will
  21100. terminate, and this method will get called to allow the app to sort itself
  21101. out.
  21102. Be careful that nothing happens in this method that might rely on messages
  21103. being sent, or any kind of window activity, because the message loop is no
  21104. longer running at this point.
  21105. @see DeletedAtShutdown
  21106. */
  21107. virtual void shutdown() = 0;
  21108. /** Returns the application's name.
  21109. An application must implement this to name itself.
  21110. */
  21111. virtual const String getApplicationName() = 0;
  21112. /** Returns the application's version number.
  21113. An application can implement this to give itself a version.
  21114. (The default implementation of this just returns an empty string).
  21115. */
  21116. virtual const String getApplicationVersion();
  21117. /** Checks whether multiple instances of the app are allowed.
  21118. If you application class returns true for this, more than one instance is
  21119. permitted to run (except on the Mac where this isn't possible).
  21120. If it's false, the second instance won't start, but it you will still get a
  21121. callback to anotherInstanceStarted() to tell you about this - which
  21122. gives you a chance to react to what the user was trying to do.
  21123. */
  21124. virtual bool moreThanOneInstanceAllowed();
  21125. /** Indicates that the user has tried to start up another instance of the app.
  21126. This will get called even if moreThanOneInstanceAllowed() is false.
  21127. */
  21128. virtual void anotherInstanceStarted (const String& commandLine);
  21129. /** Called when the operating system is trying to close the application.
  21130. The default implementation of this method is to call quit(), but it may
  21131. be overloaded to ignore the request or do some other special behaviour
  21132. instead. For example, you might want to offer the user the chance to save
  21133. their changes before quitting, and give them the chance to cancel.
  21134. If you want to send a quit signal to your app, this is the correct method
  21135. to call, because it means that requests that come from the system get handled
  21136. in the same way as those from your own application code. So e.g. you'd
  21137. call this method from a "quit" item on a menu bar.
  21138. */
  21139. virtual void systemRequestedQuit();
  21140. /** If any unhandled exceptions make it through to the message dispatch loop, this
  21141. callback will be triggered, in case you want to log them or do some other
  21142. type of error-handling.
  21143. If the type of exception is derived from the std::exception class, the pointer
  21144. passed-in will be valid. If the exception is of unknown type, this pointer
  21145. will be null.
  21146. */
  21147. virtual void unhandledException (const std::exception* e,
  21148. const String& sourceFilename,
  21149. int lineNumber);
  21150. /** Signals that the main message loop should stop and the application should terminate.
  21151. This isn't synchronous, it just posts a quit message to the main queue, and
  21152. when this message arrives, the message loop will stop, the shutdown() method
  21153. will be called, and the app will exit.
  21154. Note that this will cause an unconditional quit to happen, so if you need an
  21155. extra level before this, e.g. to give the user the chance to save their work
  21156. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  21157. method - see that method's help for more info.
  21158. @see MessageManager, DeletedAtShutdown
  21159. */
  21160. static void quit();
  21161. /** Sets the value that should be returned as the application's exit code when the
  21162. app quits.
  21163. This is the value that's returned by the main() function. Normally you'd leave this
  21164. as 0 unless you want to indicate an error code.
  21165. @see getApplicationReturnValue
  21166. */
  21167. void setApplicationReturnValue (int newReturnValue) throw();
  21168. /** Returns the value that has been set as the application's exit code.
  21169. @see setApplicationReturnValue
  21170. */
  21171. int getApplicationReturnValue() const throw() { return appReturnValue; }
  21172. /** Returns the application's command line params.
  21173. */
  21174. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  21175. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  21176. /** @internal */
  21177. static int main (String& commandLine, JUCEApplication* newApp);
  21178. /** @internal */
  21179. static int main (int argc, const char* argv[], JUCEApplication* newApp);
  21180. /** @internal */
  21181. static void sendUnhandledException (const std::exception* e,
  21182. const char* sourceFile,
  21183. int lineNumber);
  21184. /** @internal */
  21185. ApplicationCommandTarget* getNextCommandTarget();
  21186. /** @internal */
  21187. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  21188. /** @internal */
  21189. void getAllCommands (Array <CommandID>& commands);
  21190. /** @internal */
  21191. bool perform (const InvocationInfo& info);
  21192. /** @internal */
  21193. void actionListenerCallback (const String& message);
  21194. private:
  21195. String commandLineParameters;
  21196. int appReturnValue;
  21197. bool stillInitialising;
  21198. ScopedPointer<InterProcessLock> appLock;
  21199. JUCEApplication (const JUCEApplication&);
  21200. JUCEApplication& operator= (const JUCEApplication&);
  21201. public:
  21202. /** @internal */
  21203. bool initialiseApp (String& commandLine);
  21204. /** @internal */
  21205. static int shutdownAppAndClearUp();
  21206. };
  21207. #endif // __JUCE_APPLICATION_JUCEHEADER__
  21208. /*** End of inlined file: juce_Application.h ***/
  21209. #endif
  21210. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  21211. #endif
  21212. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  21213. #endif
  21214. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21215. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  21216. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21217. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21218. /*** Start of inlined file: juce_Desktop.h ***/
  21219. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  21220. #define __JUCE_DESKTOP_JUCEHEADER__
  21221. /*** Start of inlined file: juce_Timer.h ***/
  21222. #ifndef __JUCE_TIMER_JUCEHEADER__
  21223. #define __JUCE_TIMER_JUCEHEADER__
  21224. class InternalTimerThread;
  21225. /**
  21226. Repeatedly calls a user-defined method at a specified time interval.
  21227. A Timer's timerCallback() method will be repeatedly called at a given
  21228. interval. Initially when a Timer object is created, they will do nothing
  21229. until the startTimer() method is called, then the message thread will
  21230. start calling it back until stopTimer() is called.
  21231. The time interval isn't guaranteed to be precise to any more than maybe
  21232. 10-20ms, and the intervals may end up being much longer than requested if the
  21233. system is busy. Because it's the message thread that is doing the callbacks,
  21234. any messages that take a significant amount of time to process will block
  21235. all the timers for that period.
  21236. If you need to have a single callback that is shared by multiple timers with
  21237. different frequencies, then the MultiTimer class allows you to do that - its
  21238. structure is very similar to the Timer class, but contains multiple timers
  21239. internally, each one identified by an ID number.
  21240. @see MultiTimer
  21241. */
  21242. class JUCE_API Timer
  21243. {
  21244. protected:
  21245. /** Creates a Timer.
  21246. When created, the timer is stopped, so use startTimer() to get it going.
  21247. */
  21248. Timer() throw();
  21249. /** Creates a copy of another timer.
  21250. Note that this timer won't be started, even if the one you're copying
  21251. is running.
  21252. */
  21253. Timer (const Timer& other) throw();
  21254. public:
  21255. /** Destructor. */
  21256. virtual ~Timer();
  21257. /** The user-defined callback routine that actually gets called periodically.
  21258. It's perfectly ok to call startTimer() or stopTimer() from within this
  21259. callback to change the subsequent intervals.
  21260. */
  21261. virtual void timerCallback() = 0;
  21262. /** Starts the timer and sets the length of interval required.
  21263. If the timer is already started, this will reset it, so the
  21264. time between calling this method and the next timer callback
  21265. will not be less than the interval length passed in.
  21266. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  21267. rounded up to 1)
  21268. */
  21269. void startTimer (int intervalInMilliseconds) throw();
  21270. /** Stops the timer.
  21271. No more callbacks will be made after this method returns.
  21272. If this is called from a different thread, any callbacks that may
  21273. be currently executing may be allowed to finish before the method
  21274. returns.
  21275. */
  21276. void stopTimer() throw();
  21277. /** Checks if the timer has been started.
  21278. @returns true if the timer is running.
  21279. */
  21280. bool isTimerRunning() const throw() { return periodMs > 0; }
  21281. /** Returns the timer's interval.
  21282. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  21283. */
  21284. int getTimerInterval() const throw() { return periodMs; }
  21285. private:
  21286. friend class InternalTimerThread;
  21287. int countdownMs, periodMs;
  21288. Timer* previous;
  21289. Timer* next;
  21290. Timer& operator= (const Timer&);
  21291. };
  21292. #endif // __JUCE_TIMER_JUCEHEADER__
  21293. /*** End of inlined file: juce_Timer.h ***/
  21294. class MouseInputSource;
  21295. class MouseInputSourceInternal;
  21296. class MouseListener;
  21297. /**
  21298. Classes can implement this interface and register themselves with the Desktop class
  21299. to receive callbacks when the currently focused component changes.
  21300. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  21301. */
  21302. class JUCE_API FocusChangeListener
  21303. {
  21304. public:
  21305. /** Destructor. */
  21306. virtual ~FocusChangeListener() {}
  21307. /** Callback to indicate that the currently focused component has changed. */
  21308. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  21309. };
  21310. /**
  21311. Describes and controls aspects of the computer's desktop.
  21312. */
  21313. class JUCE_API Desktop : private DeletedAtShutdown,
  21314. private Timer,
  21315. private AsyncUpdater
  21316. {
  21317. public:
  21318. /** There's only one dektop object, and this method will return it.
  21319. */
  21320. static Desktop& JUCE_CALLTYPE getInstance();
  21321. /** Returns a list of the positions of all the monitors available.
  21322. The first rectangle in the list will be the main monitor area.
  21323. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21324. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21325. */
  21326. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  21327. /** Returns the position and size of the main monitor.
  21328. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21329. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21330. */
  21331. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  21332. /** Returns the position and size of the monitor which contains this co-ordinate.
  21333. If none of the monitors contains the point, this will just return the
  21334. main monitor.
  21335. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21336. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21337. */
  21338. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  21339. /** Returns the mouse position.
  21340. The co-ordinates are relative to the top-left of the main monitor.
  21341. */
  21342. static const Point<int> getMousePosition();
  21343. /** Makes the mouse pointer jump to a given location.
  21344. The co-ordinates are relative to the top-left of the main monitor.
  21345. */
  21346. static void setMousePosition (const Point<int>& newPosition);
  21347. /** Returns the last position at which a mouse button was pressed.
  21348. */
  21349. static const Point<int> getLastMouseDownPosition() throw();
  21350. /** Returns the number of times the mouse button has been clicked since the
  21351. app started.
  21352. Each mouse-down event increments this number by 1.
  21353. */
  21354. static int getMouseButtonClickCounter() throw();
  21355. /** This lets you prevent the screensaver from becoming active.
  21356. Handy if you're running some sort of presentation app where having a screensaver
  21357. appear would be annoying.
  21358. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  21359. won't enable a screensaver unless the user has actually set one up).
  21360. The disablement will only happen while the Juce application is the foreground
  21361. process - if another task is running in front of it, then the screensaver will
  21362. be unaffected.
  21363. @see isScreenSaverEnabled
  21364. */
  21365. static void setScreenSaverEnabled (bool isEnabled);
  21366. /** Returns true if the screensaver has not been turned off.
  21367. This will return the last value passed into setScreenSaverEnabled(). Note that
  21368. it won't tell you whether the user is actually using a screen saver, just
  21369. whether this app is deliberately preventing one from running.
  21370. @see setScreenSaverEnabled
  21371. */
  21372. static bool isScreenSaverEnabled();
  21373. /** Registers a MouseListener that will receive all mouse events that occur on
  21374. any component.
  21375. @see removeGlobalMouseListener
  21376. */
  21377. void addGlobalMouseListener (MouseListener* listener);
  21378. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  21379. method.
  21380. @see addGlobalMouseListener
  21381. */
  21382. void removeGlobalMouseListener (MouseListener* listener);
  21383. /** Registers a MouseListener that will receive a callback whenever the focused
  21384. component changes.
  21385. */
  21386. void addFocusChangeListener (FocusChangeListener* listener);
  21387. /** Unregisters a listener that was added with addFocusChangeListener(). */
  21388. void removeFocusChangeListener (FocusChangeListener* listener);
  21389. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  21390. The component must already be on the desktop for this method to work. It will
  21391. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  21392. etc will be hidden.
  21393. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  21394. the component that's currently being used will be resized back to the size
  21395. and position it was in before being put into this mode.
  21396. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  21397. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  21398. to hide as much on-screen paraphenalia as possible.
  21399. */
  21400. void setKioskModeComponent (Component* componentToUse,
  21401. bool allowMenusAndBars = true);
  21402. /** Returns the component that is currently being used in kiosk-mode.
  21403. This is the component that was last set by setKioskModeComponent(). If none
  21404. has been set, this returns 0.
  21405. */
  21406. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  21407. /** Returns the number of components that are currently active as top-level
  21408. desktop windows.
  21409. @see getComponent, Component::addToDesktop
  21410. */
  21411. int getNumComponents() const throw();
  21412. /** Returns one of the top-level desktop window components.
  21413. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  21414. index is out-of-range.
  21415. @see getNumComponents, Component::addToDesktop
  21416. */
  21417. Component* getComponent (int index) const throw();
  21418. /** Finds the component at a given screen location.
  21419. This will drill down into top-level windows to find the child component at
  21420. the given position.
  21421. Returns 0 if the co-ordinates are inside a non-Juce window.
  21422. */
  21423. Component* findComponentAt (const Point<int>& screenPosition) const;
  21424. /** Returns the number of MouseInputSource objects the system has at its disposal.
  21425. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21426. system, there could be one input source per potential finger.
  21427. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  21428. @see getMouseSource
  21429. */
  21430. int getNumMouseSources() const throw() { return mouseSources.size(); }
  21431. /** Returns one of the system's MouseInputSource objects.
  21432. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  21433. a null pointer.
  21434. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21435. system, there could be one input source per potential finger.
  21436. */
  21437. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  21438. /** Returns the main mouse input device that the system is using.
  21439. @see getNumMouseSources()
  21440. */
  21441. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  21442. /** Returns the number of mouse-sources that are currently being dragged.
  21443. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  21444. juce component has the button down on it. In a multi-touch system, this could
  21445. be any number from 0 to the number of simultaneous touches that can be detected.
  21446. */
  21447. int getNumDraggingMouseSources() const throw();
  21448. /** Returns one of the mouse sources that's currently being dragged.
  21449. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  21450. out of range, or if no mice or fingers are down, this will return a null pointer.
  21451. */
  21452. MouseInputSource* getDraggingMouseSource (int index) const throw();
  21453. juce_UseDebuggingNewOperator
  21454. /** Tells this object to refresh its idea of what the screen resolution is.
  21455. (Called internally by the native code).
  21456. */
  21457. void refreshMonitorSizes();
  21458. /** True if the OS supports semitransparent windows */
  21459. static bool canUseSemiTransparentWindows() throw();
  21460. private:
  21461. static Desktop* instance;
  21462. friend class Component;
  21463. friend class ComponentPeer;
  21464. friend class MouseInputSource;
  21465. friend class MouseInputSourceInternal;
  21466. friend class DeletedAtShutdown;
  21467. friend class TopLevelWindowManager;
  21468. OwnedArray <MouseInputSource> mouseSources;
  21469. void createMouseInputSources();
  21470. ListenerList <MouseListener> mouseListeners;
  21471. ListenerList <FocusChangeListener> focusListeners;
  21472. Array <Component*> desktopComponents;
  21473. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  21474. Point<int> lastFakeMouseMove;
  21475. void sendMouseMove();
  21476. int mouseClickCounter;
  21477. void incrementMouseClickCounter() throw();
  21478. Component* kioskModeComponent;
  21479. Rectangle<int> kioskComponentOriginalBounds;
  21480. void timerCallback();
  21481. void resetTimer();
  21482. int getNumDisplayMonitors() const throw();
  21483. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  21484. void addDesktopComponent (Component* c);
  21485. void removeDesktopComponent (Component* c);
  21486. void componentBroughtToFront (Component* c);
  21487. void triggerFocusCallback();
  21488. void handleAsyncUpdate();
  21489. Desktop();
  21490. ~Desktop();
  21491. Desktop (const Desktop&);
  21492. Desktop& operator= (const Desktop&);
  21493. };
  21494. #endif // __JUCE_DESKTOP_JUCEHEADER__
  21495. /*** End of inlined file: juce_Desktop.h ***/
  21496. class KeyPressMappingSet;
  21497. class ApplicationCommandManagerListener;
  21498. /**
  21499. One of these objects holds a list of all the commands your app can perform,
  21500. and despatches these commands when needed.
  21501. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  21502. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  21503. to invoke automatically, which means you don't have to handle the result of a menu
  21504. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  21505. which can choose which events they want to handle.
  21506. This architecture also allows for nested ApplicationCommandTargets, so that for example
  21507. you could have two different objects, one inside the other, both of which can respond to
  21508. a "delete" command. Depending on which one has focus, the command will be sent to the
  21509. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  21510. method.
  21511. To set up your app to use commands, you'll need to do the following:
  21512. - Create a global ApplicationCommandManager to hold the list of all possible
  21513. commands. (This will also manage a set of key-mappings for them).
  21514. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  21515. This allows the object to provide a list of commands that it can perform, and
  21516. to handle them.
  21517. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  21518. or ApplicationCommandManager::registerCommand().
  21519. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  21520. method to access the key-mapper object, which you will need to register as a key-listener
  21521. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  21522. about setting this up.
  21523. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  21524. cause these commands to be invoked automatically.
  21525. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  21526. When a command is invoked, the ApplicationCommandManager will try to choose the best
  21527. ApplicationCommandTarget to receive the specified command. To do this it will use the
  21528. current keyboard focus to see which component might be interested, and will search the
  21529. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  21530. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  21531. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  21532. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  21533. point if the command still hasn't been performed, it will be passed to the current
  21534. JUCEApplication object (which is itself an ApplicationCommandTarget).
  21535. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  21536. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  21537. the object yourself.
  21538. @see ApplicationCommandTarget, ApplicationCommandInfo
  21539. */
  21540. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  21541. private FocusChangeListener
  21542. {
  21543. public:
  21544. /** Creates an ApplicationCommandManager.
  21545. Once created, you'll need to register all your app's commands with it, using
  21546. ApplicationCommandManager::registerAllCommandsForTarget() or
  21547. ApplicationCommandManager::registerCommand().
  21548. */
  21549. ApplicationCommandManager();
  21550. /** Destructor.
  21551. Make sure that you don't delete this if pointers to it are still being used by
  21552. objects such as PopupMenus or Buttons.
  21553. */
  21554. virtual ~ApplicationCommandManager();
  21555. /** Clears the current list of all commands.
  21556. Note that this will also clear the contents of the KeyPressMappingSet.
  21557. */
  21558. void clearCommands();
  21559. /** Adds a command to the list of registered commands.
  21560. @see registerAllCommandsForTarget
  21561. */
  21562. void registerCommand (const ApplicationCommandInfo& newCommand);
  21563. /** Adds all the commands that this target publishes to the manager's list.
  21564. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  21565. to get details about all the commands that this target can do, and will call
  21566. registerCommand() to add each one to the manger's list.
  21567. @see registerCommand
  21568. */
  21569. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  21570. /** Removes the command with a specified ID.
  21571. Note that this will also remove any key mappings that are mapped to the command.
  21572. */
  21573. void removeCommand (CommandID commandID);
  21574. /** This should be called to tell the manager that one of its registered commands may have changed
  21575. its active status.
  21576. Because the command manager only finds out whether a command is active or inactive by querying
  21577. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  21578. allows things like buttons to update their enablement, etc.
  21579. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  21580. for any registered listeners.
  21581. */
  21582. void commandStatusChanged();
  21583. /** Returns the number of commands that have been registered.
  21584. @see registerCommand
  21585. */
  21586. int getNumCommands() const throw() { return commands.size(); }
  21587. /** Returns the details about one of the registered commands.
  21588. The index is between 0 and (getNumCommands() - 1).
  21589. */
  21590. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  21591. /** Returns the details about a given command ID.
  21592. This will search the list of registered commands for one with the given command
  21593. ID number, and return its associated info. If no matching command is found, this
  21594. will return 0.
  21595. */
  21596. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  21597. /** Returns the name field for a command.
  21598. An empty string is returned if no command with this ID has been registered.
  21599. @see getDescriptionOfCommand
  21600. */
  21601. const String getNameOfCommand (CommandID commandID) const throw();
  21602. /** Returns the description field for a command.
  21603. An empty string is returned if no command with this ID has been registered. If the
  21604. command has no description, this will return its short name field instead.
  21605. @see getNameOfCommand
  21606. */
  21607. const String getDescriptionOfCommand (CommandID commandID) const throw();
  21608. /** Returns the list of categories.
  21609. This will go through all registered commands, and return a list of all the distict
  21610. categoryName values from their ApplicationCommandInfo structure.
  21611. @see getCommandsInCategory()
  21612. */
  21613. const StringArray getCommandCategories() const throw();
  21614. /** Returns a list of all the command UIDs in a particular category.
  21615. @see getCommandCategories()
  21616. */
  21617. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  21618. /** Returns the manager's internal set of key mappings.
  21619. This object can be used to edit the keypresses. To actually link this object up
  21620. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  21621. class.
  21622. @see KeyPressMappingSet
  21623. */
  21624. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  21625. /** Invokes the given command directly, sending it to the default target.
  21626. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  21627. structure.
  21628. */
  21629. bool invokeDirectly (CommandID commandID, bool asynchronously);
  21630. /** Sends a command to the default target.
  21631. This will choose a target using getFirstCommandTarget(), and send the specified command
  21632. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  21633. first target can't handle the command, it will be passed on to targets further down the
  21634. chain (see ApplicationCommandTarget::invoke() for more info).
  21635. @param invocationInfo this must be correctly filled-in, describing the context for
  21636. the invocation.
  21637. @param asynchronously if false, the command will be performed before this method returns.
  21638. If true, a message will be posted so that the command will be performed
  21639. later on the message thread, and this method will return immediately.
  21640. @see ApplicationCommandTarget::invoke
  21641. */
  21642. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  21643. bool asynchronously);
  21644. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  21645. Whenever the manager needs to know which target a command should be sent to, it calls
  21646. this method to determine the first one to try.
  21647. By default, this method will return the target that was set by calling setFirstCommandTarget().
  21648. If no target is set, it will return the result of findDefaultComponentTarget().
  21649. If you need to make sure all commands go via your own custom target, then you can
  21650. either use setFirstCommandTarget() to specify a single target, or override this method
  21651. if you need more complex logic to choose one.
  21652. It may return 0 if no targets are available.
  21653. @see getTargetForCommand, invoke, invokeDirectly
  21654. */
  21655. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  21656. /** Sets a target to be returned by getFirstCommandTarget().
  21657. If this is set to 0, then getFirstCommandTarget() will by default return the
  21658. result of findDefaultComponentTarget().
  21659. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  21660. deleting the target object.
  21661. */
  21662. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  21663. /** Tries to find the best target to use to perform a given command.
  21664. This will call getFirstCommandTarget() to find the preferred target, and will
  21665. check whether that target can handle the given command. If it can't, then it'll use
  21666. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  21667. so on until no more are available.
  21668. If no targets are found that can perform the command, this method will return 0.
  21669. If a target is found, then it will get the target to fill-in the upToDateInfo
  21670. structure with the latest info about that command, so that the caller can see
  21671. whether the command is disabled, ticked, etc.
  21672. */
  21673. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  21674. ApplicationCommandInfo& upToDateInfo);
  21675. /** Registers a listener that will be called when various events occur. */
  21676. void addListener (ApplicationCommandManagerListener* listener) throw();
  21677. /** Deregisters a previously-added listener. */
  21678. void removeListener (ApplicationCommandManagerListener* listener) throw();
  21679. /** Looks for a suitable command target based on which Components have the keyboard focus.
  21680. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  21681. but is exposed here in case it's useful.
  21682. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  21683. windows, etc., and using the findTargetForComponent() method.
  21684. */
  21685. static ApplicationCommandTarget* findDefaultComponentTarget();
  21686. /** Examines this component and all its parents in turn, looking for the first one
  21687. which is a ApplicationCommandTarget.
  21688. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  21689. that class.
  21690. */
  21691. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  21692. juce_UseDebuggingNewOperator
  21693. private:
  21694. OwnedArray <ApplicationCommandInfo> commands;
  21695. ListenerList <ApplicationCommandManagerListener> listeners;
  21696. ScopedPointer <KeyPressMappingSet> keyMappings;
  21697. ApplicationCommandTarget* firstTarget;
  21698. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  21699. void handleAsyncUpdate();
  21700. void globalFocusChanged (Component*);
  21701. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  21702. // version of this method.
  21703. virtual short getFirstCommandTarget() { return 0; }
  21704. ApplicationCommandManager (const ApplicationCommandManager&);
  21705. ApplicationCommandManager& operator= (const ApplicationCommandManager&);
  21706. };
  21707. /**
  21708. A listener that receives callbacks from an ApplicationCommandManager when
  21709. commands are invoked or the command list is changed.
  21710. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  21711. */
  21712. class JUCE_API ApplicationCommandManagerListener
  21713. {
  21714. public:
  21715. /** Destructor. */
  21716. virtual ~ApplicationCommandManagerListener() {}
  21717. /** Called when an app command is about to be invoked. */
  21718. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  21719. /** Called when commands are registered or deregistered from the
  21720. command manager, or when commands are made active or inactive.
  21721. Note that if you're using this to watch for changes to whether a command is disabled,
  21722. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  21723. whenever the status of your command might have changed.
  21724. */
  21725. virtual void applicationCommandListChanged() = 0;
  21726. };
  21727. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21728. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  21729. #endif
  21730. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  21731. #endif
  21732. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21733. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  21734. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21735. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21736. /*** Start of inlined file: juce_PropertiesFile.h ***/
  21737. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  21738. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  21739. /** Wrapper on a file that stores a list of key/value data pairs.
  21740. Useful for storing application settings, etc. See the PropertySet class for
  21741. the interfaces that read and write values.
  21742. Not designed for very large amounts of data, as it keeps all the values in
  21743. memory and writes them out to disk lazily when they are changed.
  21744. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  21745. with it, and these will be signalled when a value changes.
  21746. @see PropertySet
  21747. */
  21748. class JUCE_API PropertiesFile : public PropertySet,
  21749. public ChangeBroadcaster,
  21750. private Timer
  21751. {
  21752. public:
  21753. enum FileFormatOptions
  21754. {
  21755. ignoreCaseOfKeyNames = 1,
  21756. storeAsBinary = 2,
  21757. storeAsCompressedBinary = 4,
  21758. storeAsXML = 8
  21759. };
  21760. /**
  21761. Creates a PropertiesFile object.
  21762. @param file the file to use
  21763. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  21764. is changed, the object will wait for this amount
  21765. of time and then save the file. If zero, the file
  21766. will be written to disk immediately on being changed
  21767. (which might be slow, as it'll re-write synchronously
  21768. each time a value-change method is called). If it is
  21769. less than zero, the file won't be saved until
  21770. save() or saveIfNeeded() are explicitly called.
  21771. @param optionFlags a combination of the flags in the FileFormatOptions
  21772. enum, which specify the type of file to save, and other
  21773. options.
  21774. @param processLock an optional InterprocessLock object that will be used to
  21775. prevent multiple threads or processes from writing to the file
  21776. at the same time. The PropertiesFile will keep a pointer to
  21777. this object but will not take ownership of it - the caller is
  21778. responsible for making sure that the lock doesn't get deleted
  21779. before the PropertiesFile has been deleted.
  21780. */
  21781. PropertiesFile (const File& file,
  21782. int millisecondsBeforeSaving,
  21783. int optionFlags,
  21784. InterProcessLock* processLock = 0);
  21785. /** Destructor.
  21786. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  21787. */
  21788. ~PropertiesFile();
  21789. /** Returns true if this file was created from a valid (or non-existent) file.
  21790. If the file failed to load correctly because it was corrupt or had insufficient
  21791. access, this will be false.
  21792. */
  21793. bool isValidFile() const throw() { return loadedOk; }
  21794. /** This will flush all the values to disk if they've changed since the last
  21795. time they were saved.
  21796. Returns false if it fails to write to the file for some reason (maybe because
  21797. it's read-only or the directory doesn't exist or something).
  21798. @see save
  21799. */
  21800. bool saveIfNeeded();
  21801. /** This will force a write-to-disk of the current values, regardless of whether
  21802. anything has changed since the last save.
  21803. Returns false if it fails to write to the file for some reason (maybe because
  21804. it's read-only or the directory doesn't exist or something).
  21805. @see saveIfNeeded
  21806. */
  21807. bool save();
  21808. /** Returns true if the properties have been altered since the last time they were saved.
  21809. The file is flagged as needing to be saved when you change a value, but you can
  21810. explicitly set this flag with setNeedsToBeSaved().
  21811. */
  21812. bool needsToBeSaved() const;
  21813. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  21814. @see needsToBeSaved
  21815. */
  21816. void setNeedsToBeSaved (bool needsToBeSaved);
  21817. /** Returns the file that's being used. */
  21818. const File getFile() const { return file; }
  21819. /** Handy utility to create a properties file in whatever the standard OS-specific
  21820. location is for these things.
  21821. This uses getDefaultAppSettingsFile() to decide what file to create, then
  21822. creates a PropertiesFile object with the specified properties. See
  21823. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  21824. what the parameters do.
  21825. @see getDefaultAppSettingsFile
  21826. */
  21827. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  21828. const String& fileNameSuffix,
  21829. const String& folderName,
  21830. bool commonToAllUsers,
  21831. int millisecondsBeforeSaving,
  21832. int propertiesFileOptions,
  21833. InterProcessLock* processLock = 0);
  21834. /** Handy utility to choose a file in the standard OS-dependent location for application
  21835. settings files.
  21836. So on a Mac, this will return a file called:
  21837. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  21838. On Windows it'll return something like:
  21839. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  21840. On Linux it'll return
  21841. ~/.[folderName]/[applicationName].[fileNameSuffix]
  21842. If you pass an empty string as the folder name, it'll use the app name for this (or
  21843. omit the folder name on the Mac).
  21844. If commonToAllUsers is true, then this will return the same file for all users of the
  21845. computer, regardless of the current user. If it is false, the file will be specific to
  21846. only the current user. Use this to choose whether you're saving settings that are common
  21847. or user-specific.
  21848. */
  21849. static const File getDefaultAppSettingsFile (const String& applicationName,
  21850. const String& fileNameSuffix,
  21851. const String& folderName,
  21852. bool commonToAllUsers);
  21853. juce_UseDebuggingNewOperator
  21854. protected:
  21855. virtual void propertyChanged();
  21856. private:
  21857. File file;
  21858. int timerInterval;
  21859. const int options;
  21860. bool loadedOk, needsWriting;
  21861. InterProcessLock* processLock;
  21862. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  21863. InterProcessLock::ScopedLockType* createProcessLock() const;
  21864. void timerCallback();
  21865. PropertiesFile (const PropertiesFile&);
  21866. PropertiesFile& operator= (const PropertiesFile&);
  21867. };
  21868. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  21869. /*** End of inlined file: juce_PropertiesFile.h ***/
  21870. /**
  21871. Manages a collection of properties.
  21872. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  21873. as a singleton.
  21874. It holds two different PropertiesFile objects internally, one for user-specific
  21875. settings (stored in your user directory), and one for settings that are common to
  21876. all users (stored in a folder accessible to all users).
  21877. The class manages the creation of these files on-demand, allowing access via the
  21878. getUserSettings() and getCommonSettings() methods. It also has a few handy
  21879. methods like testWriteAccess() to check that the files can be saved.
  21880. If you're using one of these as a singleton, then your app's start-up code should
  21881. first of all call setStorageParameters() to tell it the parameters to use to create
  21882. the properties files.
  21883. @see PropertiesFile
  21884. */
  21885. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  21886. {
  21887. public:
  21888. /**
  21889. Creates an ApplicationProperties object.
  21890. Before using it, you must call setStorageParameters() to give it the info
  21891. it needs to create the property files.
  21892. */
  21893. ApplicationProperties() throw();
  21894. /** Destructor.
  21895. */
  21896. ~ApplicationProperties();
  21897. juce_DeclareSingleton (ApplicationProperties, false)
  21898. /** Gives the object the information it needs to create the appropriate properties files.
  21899. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  21900. info about how these parameters are used.
  21901. */
  21902. void setStorageParameters (const String& applicationName,
  21903. const String& fileNameSuffix,
  21904. const String& folderName,
  21905. int millisecondsBeforeSaving,
  21906. int propertiesFileOptions) throw();
  21907. /** Tests whether the files can be successfully written to, and can show
  21908. an error message if not.
  21909. Returns true if none of the tests fail.
  21910. @param testUserSettings if true, the user settings file will be tested
  21911. @param testCommonSettings if true, the common settings file will be tested
  21912. @param showWarningDialogOnFailure if true, the method will show a helpful error
  21913. message box if either of the tests fail
  21914. */
  21915. bool testWriteAccess (bool testUserSettings,
  21916. bool testCommonSettings,
  21917. bool showWarningDialogOnFailure);
  21918. /** Returns the user settings file.
  21919. The first time this is called, it will create and load the properties file.
  21920. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  21921. the common settings are used as a second-chance place to look. This is done via the
  21922. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  21923. to the fallback for the user settings.
  21924. @see getCommonSettings
  21925. */
  21926. PropertiesFile* getUserSettings() throw();
  21927. /** Returns the common settings file.
  21928. The first time this is called, it will create and load the properties file.
  21929. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  21930. read-only (e.g. because the user doesn't have permission to write
  21931. to shared files), then this will return the user settings instead,
  21932. (like getUserSettings() would do). This is handy if you'd like to
  21933. write a value to the common settings, but if that's no possible,
  21934. then you'd rather write to the user settings than none at all.
  21935. If returnUserPropsIfReadOnly is false, this method will always return
  21936. the common settings, even if any changes to them can't be saved.
  21937. @see getUserSettings
  21938. */
  21939. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly) throw();
  21940. /** Saves both files if they need to be saved.
  21941. @see PropertiesFile::saveIfNeeded
  21942. */
  21943. bool saveIfNeeded();
  21944. /** Flushes and closes both files if they are open.
  21945. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  21946. and closes both files. They will then be re-opened the next time getUserSettings()
  21947. or getCommonSettings() is called.
  21948. */
  21949. void closeFiles();
  21950. juce_UseDebuggingNewOperator
  21951. private:
  21952. ScopedPointer <PropertiesFile> userProps, commonProps;
  21953. String appName, fileSuffix, folderName;
  21954. int msBeforeSaving, options;
  21955. int commonSettingsAreReadOnly;
  21956. ApplicationProperties (const ApplicationProperties&);
  21957. ApplicationProperties& operator= (const ApplicationProperties&);
  21958. void openFiles() throw();
  21959. };
  21960. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21961. /*** End of inlined file: juce_ApplicationProperties.h ***/
  21962. #endif
  21963. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21964. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  21965. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21966. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21967. /*** Start of inlined file: juce_AudioFormat.h ***/
  21968. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  21969. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  21970. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  21971. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21972. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21973. class AudioFormat;
  21974. /**
  21975. Reads samples from an audio file stream.
  21976. A subclass that reads a specific type of audio format will be created by
  21977. an AudioFormat object.
  21978. @see AudioFormat, AudioFormatWriter
  21979. */
  21980. class JUCE_API AudioFormatReader
  21981. {
  21982. protected:
  21983. /** Creates an AudioFormatReader object.
  21984. @param sourceStream the stream to read from - this will be deleted
  21985. by this object when it is no longer needed. (Some
  21986. specialised readers might not use this parameter and
  21987. can leave it as 0).
  21988. @param formatName the description that will be returned by the getFormatName()
  21989. method
  21990. */
  21991. AudioFormatReader (InputStream* sourceStream,
  21992. const String& formatName);
  21993. public:
  21994. /** Destructor. */
  21995. virtual ~AudioFormatReader();
  21996. /** Returns a description of what type of format this is.
  21997. E.g. "AIFF"
  21998. */
  21999. const String getFormatName() const throw() { return formatName; }
  22000. /** Reads samples from the stream.
  22001. @param destSamples an array of buffers into which the sample data for each
  22002. channel will be written.
  22003. If the format is fixed-point, each channel will be written
  22004. as an array of 32-bit signed integers using the full
  22005. range -0x80000000 to 0x7fffffff, regardless of the source's
  22006. bit-depth. If it is a floating-point format, you should cast
  22007. the resulting array to a (float**) to get the values (in the
  22008. range -1.0 to 1.0 or beyond)
  22009. If the format is stereo, then destSamples[0] is the left channel
  22010. data, and destSamples[1] is the right channel.
  22011. The numDestChannels parameter indicates how many pointers this array
  22012. contains, but some of these pointers can be null if you don't want to
  22013. read data for some of the channels
  22014. @param numDestChannels the number of array elements in the destChannels array
  22015. @param startSampleInSource the position in the audio file or stream at which the samples
  22016. should be read, as a number of samples from the start of the
  22017. stream. It's ok for this to be beyond the start or end of the
  22018. available data - any samples that are out-of-range will be returned
  22019. as zeros.
  22020. @param numSamplesToRead the number of samples to read. If this is greater than the number
  22021. of samples that the file or stream contains. the result will be padded
  22022. with zeros
  22023. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  22024. for some of the channels that you pass in, then they should be filled with
  22025. copies of valid source channels.
  22026. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  22027. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  22028. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  22029. was false, then only the first channel would be filled with the file's contents, and
  22030. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  22031. from a stereo file, then the last 3 would all end up with copies of the same data.
  22032. @returns true if the operation succeeded, false if there was an error. Note
  22033. that reading sections of data beyond the extent of the stream isn't an
  22034. error - the reader should just return zeros for these regions
  22035. @see readMaxLevels
  22036. */
  22037. bool read (int** destSamples,
  22038. int numDestChannels,
  22039. int64 startSampleInSource,
  22040. int numSamplesToRead,
  22041. bool fillLeftoverChannelsWithCopies);
  22042. /** Finds the highest and lowest sample levels from a section of the audio stream.
  22043. This will read a block of samples from the stream, and measure the
  22044. highest and lowest sample levels from the channels in that section, returning
  22045. these as normalised floating-point levels.
  22046. @param startSample the offset into the audio stream to start reading from. It's
  22047. ok for this to be beyond the start or end of the stream.
  22048. @param numSamples how many samples to read
  22049. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  22050. @param highestLeft on return, this is the highest absolute sample from the left channel
  22051. @param lowestRight on return, this is the lowest absolute sample from the right
  22052. channel (if there is one)
  22053. @param highestRight on return, this is the highest absolute sample from the right
  22054. channel (if there is one)
  22055. @see read
  22056. */
  22057. virtual void readMaxLevels (int64 startSample,
  22058. int64 numSamples,
  22059. float& lowestLeft,
  22060. float& highestLeft,
  22061. float& lowestRight,
  22062. float& highestRight);
  22063. /** Scans the source looking for a sample whose magnitude is in a specified range.
  22064. This will read from the source, either forwards or backwards between two sample
  22065. positions, until it finds a sample whose magnitude lies between two specified levels.
  22066. If it finds a suitable sample, it returns its position; if not, it will return -1.
  22067. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  22068. points when you're searching for a continuous range of samples
  22069. @param startSample the first sample to look at
  22070. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  22071. the search will go backwards
  22072. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  22073. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  22074. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  22075. of this many consecutive samples, all of which lie
  22076. within the target range. When it finds such a sequence,
  22077. it returns the position of the first in-range sample
  22078. it found (i.e. the earliest one if scanning forwards, the
  22079. latest one if scanning backwards)
  22080. */
  22081. int64 searchForLevel (int64 startSample,
  22082. int64 numSamplesToSearch,
  22083. double magnitudeRangeMinimum,
  22084. double magnitudeRangeMaximum,
  22085. int minimumConsecutiveSamples);
  22086. /** The sample-rate of the stream. */
  22087. double sampleRate;
  22088. /** The number of bits per sample, e.g. 16, 24, 32. */
  22089. unsigned int bitsPerSample;
  22090. /** The total number of samples in the audio stream. */
  22091. int64 lengthInSamples;
  22092. /** The total number of channels in the audio stream. */
  22093. unsigned int numChannels;
  22094. /** Indicates whether the data is floating-point or fixed. */
  22095. bool usesFloatingPointData;
  22096. /** A set of metadata values that the reader has pulled out of the stream.
  22097. Exactly what these values are depends on the format, so you can
  22098. check out the format implementation code to see what kind of stuff
  22099. they understand.
  22100. */
  22101. StringPairArray metadataValues;
  22102. /** The input stream, for use by subclasses. */
  22103. InputStream* input;
  22104. /** Subclasses must implement this method to perform the low-level read operation.
  22105. Callers should use read() instead of calling this directly.
  22106. @param destSamples the array of destination buffers to fill. Some of these
  22107. pointers may be null
  22108. @param numDestChannels the number of items in the destSamples array. This
  22109. value is guaranteed not to be greater than the number of
  22110. channels that this reader object contains
  22111. @param startOffsetInDestBuffer the number of samples from the start of the
  22112. dest data at which to begin writing
  22113. @param startSampleInFile the number of samples into the source data at which
  22114. to begin reading. This value is guaranteed to be >= 0.
  22115. @param numSamples the number of samples to read
  22116. */
  22117. virtual bool readSamples (int** destSamples,
  22118. int numDestChannels,
  22119. int startOffsetInDestBuffer,
  22120. int64 startSampleInFile,
  22121. int numSamples) = 0;
  22122. juce_UseDebuggingNewOperator
  22123. private:
  22124. String formatName;
  22125. AudioFormatReader (const AudioFormatReader&);
  22126. AudioFormatReader& operator= (const AudioFormatReader&);
  22127. };
  22128. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22129. /*** End of inlined file: juce_AudioFormatReader.h ***/
  22130. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  22131. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22132. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22133. /*** Start of inlined file: juce_AudioSource.h ***/
  22134. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  22135. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  22136. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  22137. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22138. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22139. class AudioFormatReader;
  22140. class AudioFormatWriter;
  22141. /**
  22142. A multi-channel buffer of 32-bit floating point audio samples.
  22143. */
  22144. class JUCE_API AudioSampleBuffer
  22145. {
  22146. public:
  22147. /** Creates a buffer with a specified number of channels and samples.
  22148. The contents of the buffer will initially be undefined, so use clear() to
  22149. set all the samples to zero.
  22150. The buffer will allocate its memory internally, and this will be released
  22151. when the buffer is deleted.
  22152. */
  22153. AudioSampleBuffer (int numChannels,
  22154. int numSamples) throw();
  22155. /** Creates a buffer using a pre-allocated block of memory.
  22156. Note that if the buffer is resized or its number of channels is changed, it
  22157. will re-allocate memory internally and copy the existing data to this new area,
  22158. so it will then stop directly addressing this memory.
  22159. @param dataToReferTo a pre-allocated array containing pointers to the data
  22160. for each channel that should be used by this buffer. The
  22161. buffer will only refer to this memory, it won't try to delete
  22162. it when the buffer is deleted or resized.
  22163. @param numChannels the number of channels to use - this must correspond to the
  22164. number of elements in the array passed in
  22165. @param numSamples the number of samples to use - this must correspond to the
  22166. size of the arrays passed in
  22167. */
  22168. AudioSampleBuffer (float** dataToReferTo,
  22169. int numChannels,
  22170. int numSamples) throw();
  22171. /** Copies another buffer.
  22172. This buffer will make its own copy of the other's data, unless the buffer was created
  22173. using an external data buffer, in which case boths buffers will just point to the same
  22174. shared block of data.
  22175. */
  22176. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  22177. /** Copies another buffer onto this one.
  22178. This buffer's size will be changed to that of the other buffer.
  22179. */
  22180. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  22181. /** Destructor.
  22182. This will free any memory allocated by the buffer.
  22183. */
  22184. virtual ~AudioSampleBuffer() throw();
  22185. /** Returns the number of channels of audio data that this buffer contains.
  22186. @see getSampleData
  22187. */
  22188. int getNumChannels() const throw() { return numChannels; }
  22189. /** Returns the number of samples allocated in each of the buffer's channels.
  22190. @see getSampleData
  22191. */
  22192. int getNumSamples() const throw() { return size; }
  22193. /** Returns a pointer one of the buffer's channels.
  22194. For speed, this doesn't check whether the channel number is out of range,
  22195. so be careful when using it!
  22196. */
  22197. float* getSampleData (const int channelNumber) const throw()
  22198. {
  22199. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  22200. return channels [channelNumber];
  22201. }
  22202. /** Returns a pointer to a sample in one of the buffer's channels.
  22203. For speed, this doesn't check whether the channel and sample number
  22204. are out-of-range, so be careful when using it!
  22205. */
  22206. float* getSampleData (const int channelNumber,
  22207. const int sampleOffset) const throw()
  22208. {
  22209. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  22210. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  22211. return channels [channelNumber] + sampleOffset;
  22212. }
  22213. /** Returns an array of pointers to the channels in the buffer.
  22214. Don't modify any of the pointers that are returned, and bear in mind that
  22215. these will become invalid if the buffer is resized.
  22216. */
  22217. float** getArrayOfChannels() const throw() { return channels; }
  22218. /** Chages the buffer's size or number of channels.
  22219. This can expand or contract the buffer's length, and add or remove channels.
  22220. If keepExistingContent is true, it will try to preserve as much of the
  22221. old data as it can in the new buffer.
  22222. If clearExtraSpace is true, then any extra channels or space that is
  22223. allocated will be also be cleared. If false, then this space is left
  22224. uninitialised.
  22225. If avoidReallocating is true, then changing the buffer's size won't reduce the
  22226. amount of memory that is currently allocated (but it will still increase it if
  22227. the new size is bigger than the amount it currently has). If this is false, then
  22228. a new allocation will be done so that the buffer uses takes up the minimum amount
  22229. of memory that it needs.
  22230. */
  22231. void setSize (int newNumChannels,
  22232. int newNumSamples,
  22233. bool keepExistingContent = false,
  22234. bool clearExtraSpace = false,
  22235. bool avoidReallocating = false) throw();
  22236. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  22237. There's also a constructor that lets you specify arrays like this, but this
  22238. lets you change the channels dynamically.
  22239. Note that if the buffer is resized or its number of channels is changed, it
  22240. will re-allocate memory internally and copy the existing data to this new area,
  22241. so it will then stop directly addressing this memory.
  22242. @param dataToReferTo a pre-allocated array containing pointers to the data
  22243. for each channel that should be used by this buffer. The
  22244. buffer will only refer to this memory, it won't try to delete
  22245. it when the buffer is deleted or resized.
  22246. @param numChannels the number of channels to use - this must correspond to the
  22247. number of elements in the array passed in
  22248. @param numSamples the number of samples to use - this must correspond to the
  22249. size of the arrays passed in
  22250. */
  22251. void setDataToReferTo (float** dataToReferTo,
  22252. int numChannels,
  22253. int numSamples) throw();
  22254. /** Clears all the samples in all channels. */
  22255. void clear() throw();
  22256. /** Clears a specified region of all the channels.
  22257. For speed, this doesn't check whether the channel and sample number
  22258. are in-range, so be careful!
  22259. */
  22260. void clear (int startSample,
  22261. int numSamples) throw();
  22262. /** Clears a specified region of just one channel.
  22263. For speed, this doesn't check whether the channel and sample number
  22264. are in-range, so be careful!
  22265. */
  22266. void clear (int channel,
  22267. int startSample,
  22268. int numSamples) throw();
  22269. /** Applies a gain multiple to a region of one channel.
  22270. For speed, this doesn't check whether the channel and sample number
  22271. are in-range, so be careful!
  22272. */
  22273. void applyGain (int channel,
  22274. int startSample,
  22275. int numSamples,
  22276. float gain) throw();
  22277. /** Applies a gain multiple to a region of all the channels.
  22278. For speed, this doesn't check whether the sample numbers
  22279. are in-range, so be careful!
  22280. */
  22281. void applyGain (int startSample,
  22282. int numSamples,
  22283. float gain) throw();
  22284. /** Applies a range of gains to a region of a channel.
  22285. The gain that is applied to each sample will vary from
  22286. startGain on the first sample to endGain on the last Sample,
  22287. so it can be used to do basic fades.
  22288. For speed, this doesn't check whether the sample numbers
  22289. are in-range, so be careful!
  22290. */
  22291. void applyGainRamp (int channel,
  22292. int startSample,
  22293. int numSamples,
  22294. float startGain,
  22295. float endGain) throw();
  22296. /** Adds samples from another buffer to this one.
  22297. @param destChannel the channel within this buffer to add the samples to
  22298. @param destStartSample the start sample within this buffer's channel
  22299. @param source the source buffer to add from
  22300. @param sourceChannel the channel within the source buffer to read from
  22301. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22302. @param numSamples the number of samples to process
  22303. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22304. added to this buffer's samples
  22305. @see copyFrom
  22306. */
  22307. void addFrom (int destChannel,
  22308. int destStartSample,
  22309. const AudioSampleBuffer& source,
  22310. int sourceChannel,
  22311. int sourceStartSample,
  22312. int numSamples,
  22313. float gainToApplyToSource = 1.0f) throw();
  22314. /** Adds samples from an array of floats to one of the channels.
  22315. @param destChannel the channel within this buffer to add the samples to
  22316. @param destStartSample the start sample within this buffer's channel
  22317. @param source the source data to use
  22318. @param numSamples the number of samples to process
  22319. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22320. added to this buffer's samples
  22321. @see copyFrom
  22322. */
  22323. void addFrom (int destChannel,
  22324. int destStartSample,
  22325. const float* source,
  22326. int numSamples,
  22327. float gainToApplyToSource = 1.0f) throw();
  22328. /** Adds samples from an array of floats, applying a gain ramp to them.
  22329. @param destChannel the channel within this buffer to add the samples to
  22330. @param destStartSample the start sample within this buffer's channel
  22331. @param source the source data to use
  22332. @param numSamples the number of samples to process
  22333. @param startGain the gain to apply to the first sample (this is multiplied with
  22334. the source samples before they are added to this buffer)
  22335. @param endGain the gain to apply to the final sample. The gain is linearly
  22336. interpolated between the first and last samples.
  22337. */
  22338. void addFromWithRamp (int destChannel,
  22339. int destStartSample,
  22340. const float* source,
  22341. int numSamples,
  22342. float startGain,
  22343. float endGain) throw();
  22344. /** Copies samples from another buffer to this one.
  22345. @param destChannel the channel within this buffer to copy the samples to
  22346. @param destStartSample the start sample within this buffer's channel
  22347. @param source the source buffer to read from
  22348. @param sourceChannel the channel within the source buffer to read from
  22349. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22350. @param numSamples the number of samples to process
  22351. @see addFrom
  22352. */
  22353. void copyFrom (int destChannel,
  22354. int destStartSample,
  22355. const AudioSampleBuffer& source,
  22356. int sourceChannel,
  22357. int sourceStartSample,
  22358. int numSamples) throw();
  22359. /** Copies samples from an array of floats into one of the channels.
  22360. @param destChannel the channel within this buffer to copy the samples to
  22361. @param destStartSample the start sample within this buffer's channel
  22362. @param source the source buffer to read from
  22363. @param numSamples the number of samples to process
  22364. @see addFrom
  22365. */
  22366. void copyFrom (int destChannel,
  22367. int destStartSample,
  22368. const float* source,
  22369. int numSamples) throw();
  22370. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  22371. @param destChannel the channel within this buffer to copy the samples to
  22372. @param destStartSample the start sample within this buffer's channel
  22373. @param source the source buffer to read from
  22374. @param numSamples the number of samples to process
  22375. @param gain the gain to apply
  22376. @see addFrom
  22377. */
  22378. void copyFrom (int destChannel,
  22379. int destStartSample,
  22380. const float* source,
  22381. int numSamples,
  22382. float gain) throw();
  22383. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  22384. @param destChannel the channel within this buffer to copy the samples to
  22385. @param destStartSample the start sample within this buffer's channel
  22386. @param source the source buffer to read from
  22387. @param numSamples the number of samples to process
  22388. @param startGain the gain to apply to the first sample (this is multiplied with
  22389. the source samples before they are copied to this buffer)
  22390. @param endGain the gain to apply to the final sample. The gain is linearly
  22391. interpolated between the first and last samples.
  22392. @see addFrom
  22393. */
  22394. void copyFromWithRamp (int destChannel,
  22395. int destStartSample,
  22396. const float* source,
  22397. int numSamples,
  22398. float startGain,
  22399. float endGain) throw();
  22400. /** Finds the highest and lowest sample values in a given range.
  22401. @param channel the channel to read from
  22402. @param startSample the start sample within the channel
  22403. @param numSamples the number of samples to check
  22404. @param minVal on return, the lowest value that was found
  22405. @param maxVal on return, the highest value that was found
  22406. */
  22407. void findMinMax (int channel,
  22408. int startSample,
  22409. int numSamples,
  22410. float& minVal,
  22411. float& maxVal) const throw();
  22412. /** Finds the highest absolute sample value within a region of a channel.
  22413. */
  22414. float getMagnitude (int channel,
  22415. int startSample,
  22416. int numSamples) const throw();
  22417. /** Finds the highest absolute sample value within a region on all channels.
  22418. */
  22419. float getMagnitude (int startSample,
  22420. int numSamples) const throw();
  22421. /** Returns the root mean squared level for a region of a channel.
  22422. */
  22423. float getRMSLevel (int channel,
  22424. int startSample,
  22425. int numSamples) const throw();
  22426. /** Fills a section of the buffer using an AudioReader as its source.
  22427. This will convert the reader's fixed- or floating-point data to
  22428. the buffer's floating-point format, and will try to intelligently
  22429. cope with mismatches between the number of channels in the reader
  22430. and the buffer.
  22431. @see writeToAudioWriter
  22432. */
  22433. void readFromAudioReader (AudioFormatReader* reader,
  22434. int startSample,
  22435. int numSamples,
  22436. int readerStartSample,
  22437. bool useReaderLeftChan,
  22438. bool useReaderRightChan);
  22439. /** Writes a section of this buffer to an audio writer.
  22440. This saves you having to mess about with channels or floating/fixed
  22441. point conversion.
  22442. @see readFromAudioReader
  22443. */
  22444. void writeToAudioWriter (AudioFormatWriter* writer,
  22445. int startSample,
  22446. int numSamples) const;
  22447. juce_UseDebuggingNewOperator
  22448. private:
  22449. int numChannels, size;
  22450. size_t allocatedBytes;
  22451. float** channels;
  22452. HeapBlock <char> allocatedData;
  22453. float* preallocatedChannelSpace [32];
  22454. void allocateData();
  22455. void allocateChannels (float** dataToReferTo);
  22456. };
  22457. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22458. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  22459. /**
  22460. Used by AudioSource::getNextAudioBlock().
  22461. */
  22462. struct JUCE_API AudioSourceChannelInfo
  22463. {
  22464. /** The destination buffer to fill with audio data.
  22465. When the AudioSource::getNextAudioBlock() method is called, the active section
  22466. of this buffer should be filled with whatever output the source produces.
  22467. Only the samples specified by the startSample and numSamples members of this structure
  22468. should be affected by the call.
  22469. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  22470. method can be treated as the input if the source is performing some kind of filter operation,
  22471. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  22472. a handy way of doing this.
  22473. The number of channels in the buffer could be anything, so the AudioSource
  22474. must cope with this in whatever way is appropriate for its function.
  22475. */
  22476. AudioSampleBuffer* buffer;
  22477. /** The first sample in the buffer from which the callback is expected
  22478. to write data. */
  22479. int startSample;
  22480. /** The number of samples in the buffer which the callback is expected to
  22481. fill with data. */
  22482. int numSamples;
  22483. /** Convenient method to clear the buffer if the source is not producing any data. */
  22484. void clearActiveBufferRegion() const
  22485. {
  22486. if (buffer != 0)
  22487. buffer->clear (startSample, numSamples);
  22488. }
  22489. };
  22490. /**
  22491. Base class for objects that can produce a continuous stream of audio.
  22492. @see AudioFormatReaderSource, ResamplingAudioSource
  22493. */
  22494. class JUCE_API AudioSource
  22495. {
  22496. protected:
  22497. /** Creates an AudioSource. */
  22498. AudioSource() throw() {}
  22499. public:
  22500. /** Destructor. */
  22501. virtual ~AudioSource() {}
  22502. /** Tells the source to prepare for playing.
  22503. The source can use this opportunity to initialise anything it needs to.
  22504. Note that this method could be called more than once in succession without
  22505. a matching call to releaseResources(), so make sure your code is robust and
  22506. can handle that kind of situation.
  22507. @param samplesPerBlockExpected the number of samples that the source
  22508. will be expected to supply each time its
  22509. getNextAudioBlock() method is called. This
  22510. number may vary slightly, because it will be dependent
  22511. on audio hardware callbacks, and these aren't
  22512. guaranteed to always use a constant block size, so
  22513. the source should be able to cope with small variations.
  22514. @param sampleRate the sample rate that the output will be used at - this
  22515. is needed by sources such as tone generators.
  22516. @see releaseResources, getNextAudioBlock
  22517. */
  22518. virtual void prepareToPlay (int samplesPerBlockExpected,
  22519. double sampleRate) = 0;
  22520. /** Allows the source to release anything it no longer needs after playback has stopped.
  22521. This will be called when the source is no longer going to have its getNextAudioBlock()
  22522. method called, so it should release any spare memory, etc. that it might have
  22523. allocated during the prepareToPlay() call.
  22524. Note that there's no guarantee that prepareToPlay() will actually have been called before
  22525. releaseResources(), and it may be called more than once in succession, so make sure your
  22526. code is robust and doesn't make any assumptions about when it will be called.
  22527. @see prepareToPlay, getNextAudioBlock
  22528. */
  22529. virtual void releaseResources() = 0;
  22530. /** Called repeatedly to fetch subsequent blocks of audio data.
  22531. After calling the prepareToPlay() method, this callback will be made each
  22532. time the audio playback hardware (or whatever other destination the audio
  22533. data is going to) needs another block of data.
  22534. It will generally be called on a high-priority system thread, or possibly even
  22535. an interrupt, so be careful not to do too much work here, as that will cause
  22536. audio glitches!
  22537. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  22538. */
  22539. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  22540. };
  22541. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  22542. /*** End of inlined file: juce_AudioSource.h ***/
  22543. /**
  22544. Writes samples to an audio file stream.
  22545. A subclass that writes a specific type of audio format will be created by
  22546. an AudioFormat object.
  22547. After creating one of these with the AudioFormat::createWriterFor() method
  22548. you can call its write() method to store the samples, and then delete it.
  22549. @see AudioFormat, AudioFormatReader
  22550. */
  22551. class JUCE_API AudioFormatWriter
  22552. {
  22553. protected:
  22554. /** Creates an AudioFormatWriter object.
  22555. @param destStream the stream to write to - this will be deleted
  22556. by this object when it is no longer needed
  22557. @param formatName the description that will be returned by the getFormatName()
  22558. method
  22559. @param sampleRate the sample rate to use - the base class just stores
  22560. this value, it doesn't do anything with it
  22561. @param numberOfChannels the number of channels to write - the base class just stores
  22562. this value, it doesn't do anything with it
  22563. @param bitsPerSample the bit depth of the stream - the base class just stores
  22564. this value, it doesn't do anything with it
  22565. */
  22566. AudioFormatWriter (OutputStream* destStream,
  22567. const String& formatName,
  22568. double sampleRate,
  22569. unsigned int numberOfChannels,
  22570. unsigned int bitsPerSample);
  22571. public:
  22572. /** Destructor. */
  22573. virtual ~AudioFormatWriter();
  22574. /** Returns a description of what type of format this is.
  22575. E.g. "AIFF file"
  22576. */
  22577. const String getFormatName() const throw() { return formatName; }
  22578. /** Writes a set of samples to the audio stream.
  22579. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  22580. can use AudioSampleBuffer::writeToAudioWriter().
  22581. @param samplesToWrite an array of arrays containing the sample data for
  22582. each channel to write. This is a zero-terminated
  22583. array of arrays, and can contain a different number
  22584. of channels than the actual stream uses, and the
  22585. writer should do its best to cope with this.
  22586. If the format is fixed-point, each channel will be formatted
  22587. as an array of signed integers using the full 32-bit
  22588. range -0x80000000 to 0x7fffffff, regardless of the source's
  22589. bit-depth. If it is a floating-point format, you should treat
  22590. the arrays as arrays of floats, and just cast it to an (int**)
  22591. to pass it into the method.
  22592. @param numSamples the number of samples to write
  22593. */
  22594. virtual bool write (const int** samplesToWrite,
  22595. int numSamples) = 0;
  22596. /** Reads a section of samples from an AudioFormatReader, and writes these to
  22597. the output.
  22598. This will take care of any floating-point conversion that's required to convert
  22599. between the two formats. It won't deal with sample-rate conversion, though.
  22600. If numSamplesToRead < 0, it will write the entire length of the reader.
  22601. @returns false if it can't read or write properly during the operation
  22602. */
  22603. bool writeFromAudioReader (AudioFormatReader& reader,
  22604. int64 startSample,
  22605. int64 numSamplesToRead);
  22606. /** Reads some samples from an AudioSource, and writes these to the output.
  22607. The source must already have been initialised with the AudioSource::prepareToPlay() method
  22608. @param source the source to read from
  22609. @param numSamplesToRead total number of samples to read and write
  22610. @param samplesPerBlock the maximum number of samples to fetch from the source
  22611. @returns false if it can't read or write properly during the operation
  22612. */
  22613. bool writeFromAudioSource (AudioSource& source,
  22614. int numSamplesToRead,
  22615. int samplesPerBlock = 2048);
  22616. /** Returns the sample rate being used. */
  22617. double getSampleRate() const throw() { return sampleRate; }
  22618. /** Returns the number of channels being written. */
  22619. int getNumChannels() const throw() { return numChannels; }
  22620. /** Returns the bit-depth of the data being written. */
  22621. int getBitsPerSample() const throw() { return bitsPerSample; }
  22622. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  22623. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  22624. juce_UseDebuggingNewOperator
  22625. protected:
  22626. /** The sample rate of the stream. */
  22627. double sampleRate;
  22628. /** The number of channels being written to the stream. */
  22629. unsigned int numChannels;
  22630. /** The bit depth of the file. */
  22631. unsigned int bitsPerSample;
  22632. /** True if it's a floating-point format, false if it's fixed-point. */
  22633. bool usesFloatingPointData;
  22634. /** The output stream for Use by subclasses. */
  22635. OutputStream* output;
  22636. private:
  22637. String formatName;
  22638. AudioFormatWriter (const AudioFormatWriter&);
  22639. AudioFormatWriter& operator= (const AudioFormatWriter&);
  22640. };
  22641. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22642. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  22643. /**
  22644. Subclasses of AudioFormat are used to read and write different audio
  22645. file formats.
  22646. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  22647. */
  22648. class JUCE_API AudioFormat
  22649. {
  22650. public:
  22651. /** Destructor. */
  22652. virtual ~AudioFormat();
  22653. /** Returns the name of this format.
  22654. e.g. "WAV file" or "AIFF file"
  22655. */
  22656. const String& getFormatName() const;
  22657. /** Returns all the file extensions that might apply to a file of this format.
  22658. The first item will be the one that's preferred when creating a new file.
  22659. So for a wav file this might just return ".wav"; for an AIFF file it might
  22660. return two items, ".aif" and ".aiff"
  22661. */
  22662. const StringArray& getFileExtensions() const;
  22663. /** Returns true if this the given file can be read by this format.
  22664. Subclasses shouldn't do too much work here, just check the extension or
  22665. file type. The base class implementation just checks the file's extension
  22666. against one of the ones that was registered in the constructor.
  22667. */
  22668. virtual bool canHandleFile (const File& fileToTest);
  22669. /** Returns a set of sample rates that the format can read and write. */
  22670. virtual const Array <int> getPossibleSampleRates() = 0;
  22671. /** Returns a set of bit depths that the format can read and write. */
  22672. virtual const Array <int> getPossibleBitDepths() = 0;
  22673. /** Returns true if the format can do 2-channel audio. */
  22674. virtual bool canDoStereo() = 0;
  22675. /** Returns true if the format can do 1-channel audio. */
  22676. virtual bool canDoMono() = 0;
  22677. /** Returns true if the format uses compressed data. */
  22678. virtual bool isCompressed();
  22679. /** Returns a list of different qualities that can be used when writing.
  22680. Non-compressed formats will just return an empty array, but for something
  22681. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  22682. When calling createWriterFor(), an index from this array is passed in to
  22683. tell the format which option is required.
  22684. */
  22685. virtual const StringArray getQualityOptions();
  22686. /** Tries to create an object that can read from a stream containing audio
  22687. data in this format.
  22688. The reader object that is returned can be used to read from the stream, and
  22689. should then be deleted by the caller.
  22690. @param sourceStream the stream to read from - the AudioFormatReader object
  22691. that is returned will delete this stream when it no longer
  22692. needs it.
  22693. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  22694. should delete the stream object that was passed-in. (If a valid
  22695. reader is returned, it will always be in charge of deleting the
  22696. stream, so this parameter is ignored)
  22697. @see AudioFormatReader
  22698. */
  22699. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22700. const bool deleteStreamIfOpeningFails) = 0;
  22701. /** Tries to create an object that can write to a stream with this audio format.
  22702. The writer object that is returned can be used to write to the stream, and
  22703. should then be deleted by the caller.
  22704. If the stream can't be created for some reason (e.g. the parameters passed in
  22705. here aren't suitable), this will return 0.
  22706. @param streamToWriteTo the stream that the data will go to - this will be
  22707. deleted by the AudioFormatWriter object when it's no longer
  22708. needed. If no AudioFormatWriter can be created by this method,
  22709. the stream will NOT be deleted, so that the caller can re-use it
  22710. to try to open a different format, etc
  22711. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  22712. returned by getPossibleSampleRates()
  22713. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  22714. the choice will depend on the results of canDoMono() and
  22715. canDoStereo()
  22716. @param bitsPerSample the bits per sample to use - this must be one of the values
  22717. returned by getPossibleBitDepths()
  22718. @param metadataValues a set of metadata values that the writer should try to write
  22719. to the stream. Exactly what these are depends on the format,
  22720. and the subclass doesn't actually have to do anything with
  22721. them if it doesn't want to. Have a look at the specific format
  22722. implementation classes to see possible values that can be
  22723. used
  22724. @param qualityOptionIndex the index of one of compression qualities returned by the
  22725. getQualityOptions() method. If there aren't any quality options
  22726. for this format, just pass 0 in this parameter, as it'll be
  22727. ignored
  22728. @see AudioFormatWriter
  22729. */
  22730. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22731. double sampleRateToUse,
  22732. unsigned int numberOfChannels,
  22733. int bitsPerSample,
  22734. const StringPairArray& metadataValues,
  22735. int qualityOptionIndex) = 0;
  22736. protected:
  22737. /** Creates an AudioFormat object.
  22738. @param formatName this sets the value that will be returned by getFormatName()
  22739. @param fileExtensions a zero-terminated list of file extensions - this is what will
  22740. be returned by getFileExtension()
  22741. */
  22742. AudioFormat (const String& formatName,
  22743. const StringArray& fileExtensions);
  22744. private:
  22745. String formatName;
  22746. StringArray fileExtensions;
  22747. };
  22748. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  22749. /*** End of inlined file: juce_AudioFormat.h ***/
  22750. /**
  22751. Reads and Writes AIFF format audio files.
  22752. @see AudioFormat
  22753. */
  22754. class JUCE_API AiffAudioFormat : public AudioFormat
  22755. {
  22756. public:
  22757. /** Creates an format object. */
  22758. AiffAudioFormat();
  22759. /** Destructor. */
  22760. ~AiffAudioFormat();
  22761. const Array <int> getPossibleSampleRates();
  22762. const Array <int> getPossibleBitDepths();
  22763. bool canDoStereo();
  22764. bool canDoMono();
  22765. #if JUCE_MAC
  22766. bool canHandleFile (const File& fileToTest);
  22767. #endif
  22768. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22769. const bool deleteStreamIfOpeningFails);
  22770. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22771. double sampleRateToUse,
  22772. unsigned int numberOfChannels,
  22773. int bitsPerSample,
  22774. const StringPairArray& metadataValues,
  22775. int qualityOptionIndex);
  22776. juce_UseDebuggingNewOperator
  22777. };
  22778. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22779. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  22780. #endif
  22781. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22782. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  22783. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22784. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22785. #if JUCE_USE_CDBURNER || DOXYGEN
  22786. /**
  22787. */
  22788. class AudioCDBurner : public ChangeBroadcaster
  22789. {
  22790. public:
  22791. /** Returns a list of available optical drives.
  22792. Use openDevice() to open one of the items from this list.
  22793. */
  22794. static const StringArray findAvailableDevices();
  22795. /** Tries to open one of the optical drives.
  22796. The deviceIndex is an index into the array returned by findAvailableDevices().
  22797. */
  22798. static AudioCDBurner* openDevice (const int deviceIndex);
  22799. /** Destructor. */
  22800. ~AudioCDBurner();
  22801. enum DiskState
  22802. {
  22803. unknown, /**< An error condition, if the device isn't responding. */
  22804. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  22805. may seem to be permanently open. */
  22806. noDisc, /**< The drive has no disk in it. */
  22807. writableDiskPresent, /**< The drive contains a writeable disk. */
  22808. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  22809. };
  22810. /** Returns the current status of the device.
  22811. To get informed when the drive's status changes, attach a ChangeListener to
  22812. the AudioCDBurner.
  22813. */
  22814. DiskState getDiskState() const;
  22815. /** Returns true if there's a writable disk in the drive. */
  22816. bool isDiskPresent() const;
  22817. /** Sends an eject signal to the drive.
  22818. The eject will happen asynchronously, so you can use getDiskState() and
  22819. waitUntilStateChange() to monitor its progress.
  22820. */
  22821. bool openTray();
  22822. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  22823. @returns the device's new state
  22824. */
  22825. DiskState waitUntilStateChange (int timeOutMilliseconds);
  22826. /** Returns the set of possible write speeds that the device can handle.
  22827. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  22828. Note that if there's no media present in the drive, this value may be unavailable!
  22829. @see setWriteSpeed, getWriteSpeed
  22830. */
  22831. const Array<int> getAvailableWriteSpeeds() const;
  22832. /** Tries to enable or disable buffer underrun safety on devices that support it.
  22833. @returns true if it's now enabled. If the device doesn't support it, this
  22834. will always return false.
  22835. */
  22836. bool setBufferUnderrunProtection (const bool shouldBeEnabled);
  22837. /** Returns the number of free blocks on the disk.
  22838. There are 75 blocks per second, at 44100Hz.
  22839. */
  22840. int getNumAvailableAudioBlocks() const;
  22841. /** Adds a track to be written.
  22842. The source passed-in here will be kept by this object, and it will
  22843. be used and deleted at some point in the future, either during the
  22844. burn() method or when this AudioCDBurner object is deleted. Your caller
  22845. method shouldn't keep a reference to it or use it again after passing
  22846. it in here.
  22847. */
  22848. bool addAudioTrack (AudioSource* source, int numSamples);
  22849. /** Receives progress callbacks during a cd-burn operation.
  22850. @see AudioCDBurner::burn()
  22851. */
  22852. class BurnProgressListener
  22853. {
  22854. public:
  22855. BurnProgressListener() throw() {}
  22856. virtual ~BurnProgressListener() {}
  22857. /** Called at intervals to report on the progress of the AudioCDBurner.
  22858. To cancel the burn, return true from this method.
  22859. */
  22860. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  22861. };
  22862. /** Runs the burn process.
  22863. This method will block until the operation is complete.
  22864. @param listener the object to receive callbacks about progress
  22865. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  22866. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  22867. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  22868. 0 or less to mean the fastest speed.
  22869. */
  22870. const String burn (BurnProgressListener* listener,
  22871. bool ejectDiscAfterwards,
  22872. bool performFakeBurnForTesting,
  22873. int writeSpeed);
  22874. /** If a burn operation is currently in progress, this tells it to stop
  22875. as soon as possible.
  22876. It's also possible to stop the burn process by returning true from
  22877. BurnProgressListener::audioCDBurnProgress()
  22878. */
  22879. void abortBurn();
  22880. juce_UseDebuggingNewOperator
  22881. private:
  22882. AudioCDBurner (const int deviceIndex);
  22883. class Pimpl;
  22884. friend class ScopedPointer<Pimpl>;
  22885. ScopedPointer<Pimpl> pimpl;
  22886. };
  22887. #endif
  22888. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22889. /*** End of inlined file: juce_AudioCDBurner.h ***/
  22890. #endif
  22891. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22892. /*** Start of inlined file: juce_AudioCDReader.h ***/
  22893. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22894. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  22895. #if JUCE_USE_CDREADER || DOXYGEN
  22896. #if JUCE_MAC
  22897. #endif
  22898. /**
  22899. A type of AudioFormatReader that reads from an audio CD.
  22900. One of these can be used to read a CD as if it's one big audio stream. Use the
  22901. getPositionOfTrackStart() method to find where the individual tracks are
  22902. within the stream.
  22903. @see AudioFormatReader
  22904. */
  22905. class JUCE_API AudioCDReader : public AudioFormatReader
  22906. {
  22907. public:
  22908. /** Returns a list of names of Audio CDs currently available for reading.
  22909. If there's a CD drive but no CD in it, this might return an empty list, or
  22910. possibly a device that can be opened but which has no tracks, depending
  22911. on the platform.
  22912. @see createReaderForCD
  22913. */
  22914. static const StringArray getAvailableCDNames();
  22915. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  22916. @param index the index of one of the available CDs - use getAvailableCDNames()
  22917. to find out how many there are.
  22918. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  22919. caller will be responsible for deleting the object returned.
  22920. */
  22921. static AudioCDReader* createReaderForCD (const int index);
  22922. /** Destructor. */
  22923. ~AudioCDReader();
  22924. /** Implementation of the AudioFormatReader method. */
  22925. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  22926. int64 startSampleInFile, int numSamples);
  22927. /** Checks whether the CD has been removed from the drive.
  22928. */
  22929. bool isCDStillPresent() const;
  22930. /** Returns the total number of tracks (audio + data).
  22931. */
  22932. int getNumTracks() const;
  22933. /** Finds the sample offset of the start of a track.
  22934. @param trackNum the track number, where 0 is the first track.
  22935. */
  22936. int getPositionOfTrackStart (int trackNum) const;
  22937. /** Returns true if a given track is an audio track.
  22938. @param trackNum the track number, where 0 is the first track.
  22939. */
  22940. bool isTrackAudio (int trackNum) const;
  22941. /** Refreshes the object's table of contents.
  22942. If the disc has been ejected and a different one put in since this
  22943. object was created, this will cause it to update its idea of how many tracks
  22944. there are, etc.
  22945. */
  22946. void refreshTrackLengths();
  22947. /** Enables scanning for indexes within tracks.
  22948. @see getLastIndex
  22949. */
  22950. void enableIndexScanning (bool enabled);
  22951. /** Returns the index number found during the last read() call.
  22952. Index scanning is turned off by default - turn it on with enableIndexScanning().
  22953. Then when the read() method is called, if it comes across an index within that
  22954. block, the index number is stored and returned by this method.
  22955. Some devices might not support indexes, of course.
  22956. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  22957. @see enableIndexScanning
  22958. */
  22959. int getLastIndex() const;
  22960. /** Scans a track to find the position of any indexes within it.
  22961. @param trackNumber the track to look in, where 0 is the first track on the disc
  22962. @returns an array of sample positions of any index points found (not including
  22963. the index that marks the start of the track)
  22964. */
  22965. const Array <int> findIndexesInTrack (const int trackNumber);
  22966. /** Returns the CDDB id number for the CD.
  22967. It's not a great way of identifying a disc, but it's traditional.
  22968. */
  22969. int getCDDBId();
  22970. /** Tries to eject the disk.
  22971. Of course this might not be possible, if some other process is using it.
  22972. */
  22973. void ejectDisk();
  22974. juce_UseDebuggingNewOperator
  22975. private:
  22976. #if JUCE_MAC
  22977. File volumeDir;
  22978. Array<File> tracks;
  22979. Array<int> trackStartSamples;
  22980. int currentReaderTrack;
  22981. ScopedPointer <AudioFormatReader> reader;
  22982. AudioCDReader (const File& volume);
  22983. public:
  22984. static int compareElements (const File&, const File&);
  22985. private:
  22986. #elif JUCE_WINDOWS
  22987. int numTracks;
  22988. int trackStarts[100];
  22989. bool audioTracks [100];
  22990. void* handle;
  22991. bool indexingEnabled;
  22992. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  22993. MemoryBlock buffer;
  22994. AudioCDReader (void* handle);
  22995. int getIndexAt (int samplePos);
  22996. #elif JUCE_LINUX
  22997. AudioCDReader();
  22998. #endif
  22999. AudioCDReader (const AudioCDReader&);
  23000. AudioCDReader& operator= (const AudioCDReader&);
  23001. };
  23002. #endif
  23003. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  23004. /*** End of inlined file: juce_AudioCDReader.h ***/
  23005. #endif
  23006. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  23007. #endif
  23008. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23009. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  23010. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23011. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23012. /**
  23013. A class for keeping a list of available audio formats, and for deciding which
  23014. one to use to open a given file.
  23015. You can either use this class as a singleton object, or create instances of it
  23016. yourself. Once created, use its registerFormat() method to tell it which
  23017. formats it should use.
  23018. @see AudioFormat
  23019. */
  23020. class JUCE_API AudioFormatManager
  23021. {
  23022. public:
  23023. /** Creates an empty format manager.
  23024. Before it'll be any use, you'll need to call registerFormat() with all the
  23025. formats you want it to be able to recognise.
  23026. */
  23027. AudioFormatManager();
  23028. /** Destructor. */
  23029. ~AudioFormatManager();
  23030. juce_DeclareSingleton (AudioFormatManager, false);
  23031. /** Adds a format to the manager's list of available file types.
  23032. The object passed-in will be deleted by this object, so don't keep a pointer
  23033. to it!
  23034. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  23035. return this one when called.
  23036. */
  23037. void registerFormat (AudioFormat* newFormat,
  23038. bool makeThisTheDefaultFormat);
  23039. /** Handy method to make it easy to register the formats that come with Juce.
  23040. Currently, this will add WAV and AIFF to the list.
  23041. */
  23042. void registerBasicFormats();
  23043. /** Clears the list of known formats. */
  23044. void clearFormats();
  23045. /** Returns the number of currently registered file formats. */
  23046. int getNumKnownFormats() const;
  23047. /** Returns one of the registered file formats. */
  23048. AudioFormat* getKnownFormat (int index) const;
  23049. /** Looks for which of the known formats is listed as being for a given file
  23050. extension.
  23051. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  23052. */
  23053. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  23054. /** Returns the format which has been set as the default one.
  23055. You can set a format as being the default when it is registered. It's useful
  23056. when you want to write to a file, because the best format may change between
  23057. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  23058. If none has been set as the default, this method will just return the first
  23059. one in the list.
  23060. */
  23061. AudioFormat* getDefaultFormat() const;
  23062. /** Returns a set of wildcards for file-matching that contains the extensions for
  23063. all known formats.
  23064. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  23065. */
  23066. const String getWildcardForAllFormats() const;
  23067. /** Searches through the known formats to try to create a suitable reader for
  23068. this file.
  23069. If none of the registered formats can open the file, it'll return 0. If it
  23070. returns a reader, it's the caller's responsibility to delete the reader.
  23071. */
  23072. AudioFormatReader* createReaderFor (const File& audioFile);
  23073. /** Searches through the known formats to try to create a suitable reader for
  23074. this stream.
  23075. The stream object that is passed-in will be deleted by this method or by the
  23076. reader that is returned, so the caller should not keep any references to it.
  23077. The stream that is passed-in must be capable of being repositioned so
  23078. that all the formats can have a go at opening it.
  23079. If none of the registered formats can open the stream, it'll return 0. If it
  23080. returns a reader, it's the caller's responsibility to delete the reader.
  23081. */
  23082. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  23083. juce_UseDebuggingNewOperator
  23084. private:
  23085. OwnedArray<AudioFormat> knownFormats;
  23086. int defaultFormatIndex;
  23087. };
  23088. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23089. /*** End of inlined file: juce_AudioFormatManager.h ***/
  23090. #endif
  23091. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23092. #endif
  23093. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  23094. #endif
  23095. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23096. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  23097. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23098. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23099. /**
  23100. This class is used to wrap an AudioFormatReader and only read from a
  23101. subsection of the file.
  23102. So if you have a reader which can read a 1000 sample file, you could wrap it
  23103. in one of these to only access, e.g. samples 100 to 200, and any samples
  23104. outside that will come back as 0. Accessing sample 0 from this reader will
  23105. actually read the first sample from the other's subsection, which might
  23106. be at a non-zero position.
  23107. @see AudioFormatReader
  23108. */
  23109. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  23110. {
  23111. public:
  23112. /** Creates a AudioSubsectionReader for a given data source.
  23113. @param sourceReader the source reader from which we'll be taking data
  23114. @param subsectionStartSample the sample within the source reader which will be
  23115. mapped onto sample 0 for this reader.
  23116. @param subsectionLength the number of samples from the source that will
  23117. make up the subsection. If this reader is asked for
  23118. any samples beyond this region, it will return zero.
  23119. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  23120. this object is deleted.
  23121. */
  23122. AudioSubsectionReader (AudioFormatReader* sourceReader,
  23123. int64 subsectionStartSample,
  23124. int64 subsectionLength,
  23125. bool deleteSourceWhenDeleted);
  23126. /** Destructor. */
  23127. ~AudioSubsectionReader();
  23128. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  23129. int64 startSampleInFile, int numSamples);
  23130. void readMaxLevels (int64 startSample,
  23131. int64 numSamples,
  23132. float& lowestLeft,
  23133. float& highestLeft,
  23134. float& lowestRight,
  23135. float& highestRight);
  23136. juce_UseDebuggingNewOperator
  23137. private:
  23138. AudioFormatReader* const source;
  23139. int64 startSample, length;
  23140. const bool deleteSourceWhenDeleted;
  23141. AudioSubsectionReader (const AudioSubsectionReader&);
  23142. AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  23143. };
  23144. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23145. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  23146. #endif
  23147. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23148. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  23149. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23150. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23151. class AudioThumbnailCache;
  23152. /**
  23153. Makes it easy to quickly draw scaled views of the waveform shape of an
  23154. audio file.
  23155. To use this class, just create an AudioThumbNail class for the file you want
  23156. to draw, call setSource to tell it which file or resource to use, then call
  23157. drawChannel() to draw it.
  23158. The class will asynchronously scan the wavefile to create its scaled-down view,
  23159. so you should make your UI repaint itself as this data comes in. To do this, the
  23160. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  23161. listeners should repaint themselves.
  23162. The thumbnail stores an internal low-res version of the wave data, and this can
  23163. be loaded and saved to avoid having to scan the file again.
  23164. @see AudioThumbnailCache
  23165. */
  23166. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  23167. public TimeSliceClient,
  23168. private Timer
  23169. {
  23170. public:
  23171. /** Creates an audio thumbnail.
  23172. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  23173. of the audio data, this is the scale at which it should be done. (This
  23174. number is the number of original samples that will be averaged for each
  23175. low-res sample)
  23176. @param formatManagerToUse the audio format manager that is used to open the file
  23177. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  23178. thread and storage that is used to by the thumbnail, and the cache
  23179. object can be shared between multiple thumbnails
  23180. */
  23181. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  23182. AudioFormatManager& formatManagerToUse,
  23183. AudioThumbnailCache& cacheToUse);
  23184. /** Destructor. */
  23185. ~AudioThumbnail();
  23186. /** Specifies the file or stream that contains the audio file.
  23187. For a file, just call
  23188. @code
  23189. setSource (new FileInputSource (file))
  23190. @endcode
  23191. You can pass a zero in here to clear the thumbnail.
  23192. The source that is passed in will be deleted by this object when it is no
  23193. longer needed
  23194. */
  23195. void setSource (InputSource* newSource);
  23196. /** Reloads the low res thumbnail data from an input stream.
  23197. The thumb will automatically attempt to reload itself from its
  23198. AudioThumbnailCache.
  23199. */
  23200. void loadFrom (InputStream& input);
  23201. /** Saves the low res thumbnail data to an output stream.
  23202. The thumb will automatically attempt to save itself to its
  23203. AudioThumbnailCache after it finishes scanning the wave file.
  23204. */
  23205. void saveTo (OutputStream& output) const;
  23206. /** Returns the number of channels in the file.
  23207. */
  23208. int getNumChannels() const throw();
  23209. /** Returns the length of the audio file, in seconds.
  23210. */
  23211. double getTotalLength() const throw();
  23212. /** Renders the waveform shape for a channel.
  23213. The waveform will be drawn within the specified rectangle, where startTime
  23214. and endTime specify the times within the audio file that should be positioned
  23215. at the left and right edges of the rectangle.
  23216. The waveform will be scaled vertically so that a full-volume sample will fill
  23217. the rectangle vertically, but you can also specify an extra vertical scale factor
  23218. with the verticalZoomFactor parameter.
  23219. */
  23220. void drawChannel (Graphics& g,
  23221. int x, int y, int w, int h,
  23222. double startTimeSeconds,
  23223. double endTimeSeconds,
  23224. int channelNum,
  23225. float verticalZoomFactor);
  23226. /** Returns true if the low res preview is fully generated.
  23227. */
  23228. bool isFullyLoaded() const throw();
  23229. /** @internal */
  23230. bool useTimeSlice();
  23231. /** @internal */
  23232. void timerCallback();
  23233. juce_UseDebuggingNewOperator
  23234. private:
  23235. AudioFormatManager& formatManagerToUse;
  23236. AudioThumbnailCache& cache;
  23237. ScopedPointer <InputSource> source;
  23238. CriticalSection readerLock;
  23239. ScopedPointer <AudioFormatReader> reader;
  23240. MemoryBlock data, cachedLevels;
  23241. int orginalSamplesPerThumbnailSample;
  23242. int numChannelsCached, numSamplesCached;
  23243. double cachedStart, cachedTimePerPixel;
  23244. bool cacheNeedsRefilling;
  23245. void clear();
  23246. AudioFormatReader* createReader() const;
  23247. void generateSection (AudioFormatReader& reader, int64 startSample, int numSamples);
  23248. char* getChannelData (int channel) const;
  23249. void refillCache (int numSamples, double startTime, double timePerPixel);
  23250. friend class AudioThumbnailCache;
  23251. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  23252. bool initialiseFromAudioFile (AudioFormatReader& reader);
  23253. // returns true if more needs to be read
  23254. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  23255. };
  23256. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23257. /*** End of inlined file: juce_AudioThumbnail.h ***/
  23258. #endif
  23259. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23260. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  23261. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23262. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23263. struct ThumbnailCacheEntry;
  23264. /**
  23265. An instance of this class is used to manage multiple AudioThumbnail objects.
  23266. The cache runs a single background thread that is shared by all the thumbnails
  23267. that need it, and it maintains a set of low-res previews in memory, to avoid
  23268. having to re-scan audio files too often.
  23269. @see AudioThumbnail
  23270. */
  23271. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  23272. {
  23273. public:
  23274. /** Creates a cache object.
  23275. The maxNumThumbsToStore parameter lets you specify how many previews should
  23276. be kept in memory at once.
  23277. */
  23278. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  23279. /** Destructor. */
  23280. ~AudioThumbnailCache();
  23281. /** Clears out any stored thumbnails.
  23282. */
  23283. void clear();
  23284. /** Reloads the specified thumb if this cache contains the appropriate stored
  23285. data.
  23286. This is called automatically by the AudioThumbnail class, so you shouldn't
  23287. normally need to call it directly.
  23288. */
  23289. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  23290. /** Stores the cachable data from the specified thumb in this cache.
  23291. This is called automatically by the AudioThumbnail class, so you shouldn't
  23292. normally need to call it directly.
  23293. */
  23294. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  23295. juce_UseDebuggingNewOperator
  23296. private:
  23297. OwnedArray <ThumbnailCacheEntry> thumbs;
  23298. int maxNumThumbsToStore;
  23299. friend class AudioThumbnail;
  23300. void addThumbnail (AudioThumbnail* thumb);
  23301. void removeThumbnail (AudioThumbnail* thumb);
  23302. };
  23303. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23304. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  23305. #endif
  23306. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23307. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  23308. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23309. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23310. #if JUCE_USE_FLAC || defined (DOXYGEN)
  23311. /**
  23312. Reads and writes the lossless-compression FLAC audio format.
  23313. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  23314. and make sure your include search path and library search path are set up to find
  23315. the FLAC header files and static libraries.
  23316. @see AudioFormat
  23317. */
  23318. class JUCE_API FlacAudioFormat : public AudioFormat
  23319. {
  23320. public:
  23321. FlacAudioFormat();
  23322. ~FlacAudioFormat();
  23323. const Array <int> getPossibleSampleRates();
  23324. const Array <int> getPossibleBitDepths();
  23325. bool canDoStereo();
  23326. bool canDoMono();
  23327. bool isCompressed();
  23328. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23329. const bool deleteStreamIfOpeningFails);
  23330. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23331. double sampleRateToUse,
  23332. unsigned int numberOfChannels,
  23333. int bitsPerSample,
  23334. const StringPairArray& metadataValues,
  23335. int qualityOptionIndex);
  23336. juce_UseDebuggingNewOperator
  23337. };
  23338. #endif
  23339. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23340. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  23341. #endif
  23342. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23343. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  23344. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23345. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23346. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  23347. /**
  23348. Reads and writes the Ogg-Vorbis audio format.
  23349. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  23350. and make sure your include search path and library search path are set up to find
  23351. the Vorbis and Ogg header files and static libraries.
  23352. @see AudioFormat,
  23353. */
  23354. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  23355. {
  23356. public:
  23357. OggVorbisAudioFormat();
  23358. ~OggVorbisAudioFormat();
  23359. const Array <int> getPossibleSampleRates();
  23360. const Array <int> getPossibleBitDepths();
  23361. bool canDoStereo();
  23362. bool canDoMono();
  23363. bool isCompressed();
  23364. const StringArray getQualityOptions();
  23365. /** Tries to estimate the quality level of an ogg file based on its size.
  23366. If it can't read the file for some reason, this will just return 1 (medium quality),
  23367. otherwise it will return the approximate quality setting that would have been used
  23368. to create the file.
  23369. @see getQualityOptions
  23370. */
  23371. int estimateOggFileQuality (const File& source);
  23372. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23373. const bool deleteStreamIfOpeningFails);
  23374. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23375. double sampleRateToUse,
  23376. unsigned int numberOfChannels,
  23377. int bitsPerSample,
  23378. const StringPairArray& metadataValues,
  23379. int qualityOptionIndex);
  23380. juce_UseDebuggingNewOperator
  23381. };
  23382. #endif
  23383. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23384. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  23385. #endif
  23386. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23387. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  23388. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23389. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23390. #if JUCE_QUICKTIME
  23391. /**
  23392. Uses QuickTime to read the audio track a movie or media file.
  23393. As well as QuickTime movies, this should also manage to open other audio
  23394. files that quicktime can understand, like mp3, m4a, etc.
  23395. @see AudioFormat
  23396. */
  23397. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  23398. {
  23399. public:
  23400. /** Creates a format object. */
  23401. QuickTimeAudioFormat();
  23402. /** Destructor. */
  23403. ~QuickTimeAudioFormat();
  23404. const Array <int> getPossibleSampleRates();
  23405. const Array <int> getPossibleBitDepths();
  23406. bool canDoStereo();
  23407. bool canDoMono();
  23408. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23409. const bool deleteStreamIfOpeningFails);
  23410. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23411. double sampleRateToUse,
  23412. unsigned int numberOfChannels,
  23413. int bitsPerSample,
  23414. const StringPairArray& metadataValues,
  23415. int qualityOptionIndex);
  23416. juce_UseDebuggingNewOperator
  23417. };
  23418. #endif
  23419. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23420. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  23421. #endif
  23422. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23423. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  23424. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23425. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23426. /**
  23427. Reads and Writes WAV format audio files.
  23428. @see AudioFormat
  23429. */
  23430. class JUCE_API WavAudioFormat : public AudioFormat
  23431. {
  23432. public:
  23433. /** Creates a format object. */
  23434. WavAudioFormat();
  23435. /** Destructor. */
  23436. ~WavAudioFormat();
  23437. /** Metadata property name used by wav readers and writers for adding
  23438. a BWAV chunk to the file.
  23439. @see AudioFormatReader::metadataValues, createWriterFor
  23440. */
  23441. static const char* const bwavDescription;
  23442. /** Metadata property name used by wav readers and writers for adding
  23443. a BWAV chunk to the file.
  23444. @see AudioFormatReader::metadataValues, createWriterFor
  23445. */
  23446. static const char* const bwavOriginator;
  23447. /** Metadata property name used by wav readers and writers for adding
  23448. a BWAV chunk to the file.
  23449. @see AudioFormatReader::metadataValues, createWriterFor
  23450. */
  23451. static const char* const bwavOriginatorRef;
  23452. /** Metadata property name used by wav readers and writers for adding
  23453. a BWAV chunk to the file.
  23454. Date format is: yyyy-mm-dd
  23455. @see AudioFormatReader::metadataValues, createWriterFor
  23456. */
  23457. static const char* const bwavOriginationDate;
  23458. /** Metadata property name used by wav readers and writers for adding
  23459. a BWAV chunk to the file.
  23460. Time format is: hh-mm-ss
  23461. @see AudioFormatReader::metadataValues, createWriterFor
  23462. */
  23463. static const char* const bwavOriginationTime;
  23464. /** Metadata property name used by wav readers and writers for adding
  23465. a BWAV chunk to the file.
  23466. This is the number of samples from the start of an edit that the
  23467. file is supposed to begin at. Seems like an obvious mistake to
  23468. only allow a file to occur in an edit once, but that's the way
  23469. it is..
  23470. @see AudioFormatReader::metadataValues, createWriterFor
  23471. */
  23472. static const char* const bwavTimeReference;
  23473. /** Metadata property name used by wav readers and writers for adding
  23474. a BWAV chunk to the file.
  23475. This is a
  23476. @see AudioFormatReader::metadataValues, createWriterFor
  23477. */
  23478. static const char* const bwavCodingHistory;
  23479. /** Utility function to fill out the appropriate metadata for a BWAV file.
  23480. This just makes it easier than using the property names directly, and it
  23481. fills out the time and date in the right format.
  23482. */
  23483. static const StringPairArray createBWAVMetadata (const String& description,
  23484. const String& originator,
  23485. const String& originatorRef,
  23486. const Time& dateAndTime,
  23487. const int64 timeReferenceSamples,
  23488. const String& codingHistory);
  23489. const Array <int> getPossibleSampleRates();
  23490. const Array <int> getPossibleBitDepths();
  23491. bool canDoStereo();
  23492. bool canDoMono();
  23493. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23494. const bool deleteStreamIfOpeningFails);
  23495. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23496. double sampleRateToUse,
  23497. unsigned int numberOfChannels,
  23498. int bitsPerSample,
  23499. const StringPairArray& metadataValues,
  23500. int qualityOptionIndex);
  23501. /** Utility function to replace the metadata in a wav file with a new set of values.
  23502. If possible, this cheats by overwriting just the metadata region of the file, rather
  23503. than by copying the whole file again.
  23504. */
  23505. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  23506. juce_UseDebuggingNewOperator
  23507. };
  23508. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23509. /*** End of inlined file: juce_WavAudioFormat.h ***/
  23510. #endif
  23511. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23512. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  23513. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23514. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23515. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  23516. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23517. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23518. /**
  23519. A type of AudioSource which can be repositioned.
  23520. The basic AudioSource just streams continuously with no idea of a current
  23521. time or length, so the PositionableAudioSource is used for a finite stream
  23522. that has a current read position.
  23523. @see AudioSource, AudioTransportSource
  23524. */
  23525. class JUCE_API PositionableAudioSource : public AudioSource
  23526. {
  23527. protected:
  23528. /** Creates the PositionableAudioSource. */
  23529. PositionableAudioSource() throw() {}
  23530. public:
  23531. /** Destructor */
  23532. ~PositionableAudioSource() {}
  23533. /** Tells the stream to move to a new position.
  23534. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23535. should return samples from this position.
  23536. Note that this may be called on a different thread to getNextAudioBlock(),
  23537. so the subclass should make sure it's synchronised.
  23538. */
  23539. virtual void setNextReadPosition (int newPosition) = 0;
  23540. /** Returns the position from which the next block will be returned.
  23541. @see setNextReadPosition
  23542. */
  23543. virtual int getNextReadPosition() const = 0;
  23544. /** Returns the total length of the stream (in samples). */
  23545. virtual int getTotalLength() const = 0;
  23546. /** Returns true if this source is actually playing in a loop. */
  23547. virtual bool isLooping() const = 0;
  23548. };
  23549. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23550. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  23551. /**
  23552. A type of AudioSource that will read from an AudioFormatReader.
  23553. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23554. */
  23555. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23556. {
  23557. public:
  23558. /** Creates an AudioFormatReaderSource for a given reader.
  23559. @param sourceReader the reader to use as the data source
  23560. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23561. when this object is deleted; if false it will be
  23562. left up to the caller to manage its lifetime
  23563. */
  23564. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23565. const bool deleteReaderWhenThisIsDeleted);
  23566. /** Destructor. */
  23567. ~AudioFormatReaderSource();
  23568. /** Toggles loop-mode.
  23569. If set to true, it will continuously loop the input source. If false,
  23570. it will just emit silence after the source has finished.
  23571. @see isLooping
  23572. */
  23573. void setLooping (const bool shouldLoop) throw();
  23574. /** Returns whether loop-mode is turned on or not. */
  23575. bool isLooping() const { return looping; }
  23576. /** Returns the reader that's being used. */
  23577. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23578. /** Implementation of the AudioSource method. */
  23579. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23580. /** Implementation of the AudioSource method. */
  23581. void releaseResources();
  23582. /** Implementation of the AudioSource method. */
  23583. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23584. /** Implements the PositionableAudioSource method. */
  23585. void setNextReadPosition (int newPosition);
  23586. /** Implements the PositionableAudioSource method. */
  23587. int getNextReadPosition() const;
  23588. /** Implements the PositionableAudioSource method. */
  23589. int getTotalLength() const;
  23590. juce_UseDebuggingNewOperator
  23591. private:
  23592. AudioFormatReader* reader;
  23593. bool deleteReader;
  23594. int volatile nextPlayPos;
  23595. bool volatile looping;
  23596. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23597. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23598. AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23599. };
  23600. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23601. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  23602. #endif
  23603. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23604. #endif
  23605. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23606. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  23607. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23608. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23609. /*** Start of inlined file: juce_AudioIODevice.h ***/
  23610. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23611. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23612. class AudioIODevice;
  23613. /**
  23614. One of these is passed to an AudioIODevice object to stream the audio data
  23615. in and out.
  23616. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  23617. method on its own high-priority audio thread, when it needs to send or receive
  23618. the next block of data.
  23619. @see AudioIODevice, AudioDeviceManager
  23620. */
  23621. class JUCE_API AudioIODeviceCallback
  23622. {
  23623. public:
  23624. /** Destructor. */
  23625. virtual ~AudioIODeviceCallback() {}
  23626. /** Processes a block of incoming and outgoing audio data.
  23627. The subclass's implementation should use the incoming audio for whatever
  23628. purposes it needs to, and must fill all the output channels with the next
  23629. block of output data before returning.
  23630. The channel data is arranged with the same array indices as the channel name
  23631. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  23632. that aren't specified in AudioIODevice::open() will have a null pointer for their
  23633. associated channel, so remember to check for this.
  23634. @param inputChannelData a set of arrays containing the audio data for each
  23635. incoming channel - this data is valid until the function
  23636. returns. There will be one channel of data for each input
  23637. channel that was enabled when the audio device was opened
  23638. (see AudioIODevice::open())
  23639. @param numInputChannels the number of pointers to channel data in the
  23640. inputChannelData array.
  23641. @param outputChannelData a set of arrays which need to be filled with the data
  23642. that should be sent to each outgoing channel of the device.
  23643. There will be one channel of data for each output channel
  23644. that was enabled when the audio device was opened (see
  23645. AudioIODevice::open())
  23646. The initial contents of the array is undefined, so the
  23647. callback function must fill all the channels with zeros if
  23648. its output is silence. Failing to do this could cause quite
  23649. an unpleasant noise!
  23650. @param numOutputChannels the number of pointers to channel data in the
  23651. outputChannelData array.
  23652. @param numSamples the number of samples in each channel of the input and
  23653. output arrays. The number of samples will depend on the
  23654. audio device's buffer size and will usually remain constant,
  23655. although this isn't guaranteed, so make sure your code can
  23656. cope with reasonable changes in the buffer size from one
  23657. callback to the next.
  23658. */
  23659. virtual void audioDeviceIOCallback (const float** inputChannelData,
  23660. int numInputChannels,
  23661. float** outputChannelData,
  23662. int numOutputChannels,
  23663. int numSamples) = 0;
  23664. /** Called to indicate that the device is about to start calling back.
  23665. This will be called just before the audio callbacks begin, either when this
  23666. callback has just been added to an audio device, or after the device has been
  23667. restarted because of a sample-rate or block-size change.
  23668. You can use this opportunity to find out the sample rate and block size
  23669. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  23670. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  23671. @param device the audio IO device that will be used to drive the callback.
  23672. Note that if you're going to store this this pointer, it is
  23673. only valid until the next time that audioDeviceStopped is called.
  23674. */
  23675. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  23676. /** Called to indicate that the device has stopped.
  23677. */
  23678. virtual void audioDeviceStopped() = 0;
  23679. };
  23680. /**
  23681. Base class for an audio device with synchronised input and output channels.
  23682. Subclasses of this are used to implement different protocols such as DirectSound,
  23683. ASIO, CoreAudio, etc.
  23684. To create one of these, you'll need to use the AudioIODeviceType class - see the
  23685. documentation for that class for more info.
  23686. For an easier way of managing audio devices and their settings, have a look at the
  23687. AudioDeviceManager class.
  23688. @see AudioIODeviceType, AudioDeviceManager
  23689. */
  23690. class JUCE_API AudioIODevice
  23691. {
  23692. public:
  23693. /** Destructor. */
  23694. virtual ~AudioIODevice();
  23695. /** Returns the device's name, (as set in the constructor). */
  23696. const String& getName() const throw() { return name; }
  23697. /** Returns the type of the device.
  23698. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  23699. */
  23700. const String& getTypeName() const throw() { return typeName; }
  23701. /** Returns the names of all the available output channels on this device.
  23702. To find out which of these are currently in use, call getActiveOutputChannels().
  23703. */
  23704. virtual const StringArray getOutputChannelNames() = 0;
  23705. /** Returns the names of all the available input channels on this device.
  23706. To find out which of these are currently in use, call getActiveInputChannels().
  23707. */
  23708. virtual const StringArray getInputChannelNames() = 0;
  23709. /** Returns the number of sample-rates this device supports.
  23710. To find out which rates are available on this device, use this method to
  23711. find out how many there are, and getSampleRate() to get the rates.
  23712. @see getSampleRate
  23713. */
  23714. virtual int getNumSampleRates() = 0;
  23715. /** Returns one of the sample-rates this device supports.
  23716. To find out which rates are available on this device, use getNumSampleRates() to
  23717. find out how many there are, and getSampleRate() to get the individual rates.
  23718. The sample rate is set by the open() method.
  23719. (Note that for DirectSound some rates might not work, depending on combinations
  23720. of i/o channels that are being opened).
  23721. @see getNumSampleRates
  23722. */
  23723. virtual double getSampleRate (int index) = 0;
  23724. /** Returns the number of sizes of buffer that are available.
  23725. @see getBufferSizeSamples, getDefaultBufferSize
  23726. */
  23727. virtual int getNumBufferSizesAvailable() = 0;
  23728. /** Returns one of the possible buffer-sizes.
  23729. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  23730. @returns a number of samples
  23731. @see getNumBufferSizesAvailable, getDefaultBufferSize
  23732. */
  23733. virtual int getBufferSizeSamples (int index) = 0;
  23734. /** Returns the default buffer-size to use.
  23735. @returns a number of samples
  23736. @see getNumBufferSizesAvailable, getBufferSizeSamples
  23737. */
  23738. virtual int getDefaultBufferSize() = 0;
  23739. /** Tries to open the device ready to play.
  23740. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  23741. input channel should be enabled
  23742. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  23743. output channel should be enabled
  23744. @param sampleRate the sample rate to try to use - to find out which rates are
  23745. available, see getNumSampleRates() and getSampleRate()
  23746. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  23747. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  23748. @returns an error description if there's a problem, or an empty string if it succeeds in
  23749. opening the device
  23750. @see close
  23751. */
  23752. virtual const String open (const BigInteger& inputChannels,
  23753. const BigInteger& outputChannels,
  23754. double sampleRate,
  23755. int bufferSizeSamples) = 0;
  23756. /** Closes and releases the device if it's open. */
  23757. virtual void close() = 0;
  23758. /** Returns true if the device is still open.
  23759. A device might spontaneously close itself if something goes wrong, so this checks if
  23760. it's still open.
  23761. */
  23762. virtual bool isOpen() = 0;
  23763. /** Starts the device actually playing.
  23764. This must be called after the device has been opened.
  23765. @param callback the callback to use for streaming the data.
  23766. @see AudioIODeviceCallback, open
  23767. */
  23768. virtual void start (AudioIODeviceCallback* callback) = 0;
  23769. /** Stops the device playing.
  23770. Once a device has been started, this will stop it. Any pending calls to the
  23771. callback class will be flushed before this method returns.
  23772. */
  23773. virtual void stop() = 0;
  23774. /** Returns true if the device is still calling back.
  23775. The device might mysteriously stop, so this checks whether it's
  23776. still playing.
  23777. */
  23778. virtual bool isPlaying() = 0;
  23779. /** Returns the last error that happened if anything went wrong. */
  23780. virtual const String getLastError() = 0;
  23781. /** Returns the buffer size that the device is currently using.
  23782. If the device isn't actually open, this value doesn't really mean much.
  23783. */
  23784. virtual int getCurrentBufferSizeSamples() = 0;
  23785. /** Returns the sample rate that the device is currently using.
  23786. If the device isn't actually open, this value doesn't really mean much.
  23787. */
  23788. virtual double getCurrentSampleRate() = 0;
  23789. /** Returns the device's current physical bit-depth.
  23790. If the device isn't actually open, this value doesn't really mean much.
  23791. */
  23792. virtual int getCurrentBitDepth() = 0;
  23793. /** Returns a mask showing which of the available output channels are currently
  23794. enabled.
  23795. @see getOutputChannelNames
  23796. */
  23797. virtual const BigInteger getActiveOutputChannels() const = 0;
  23798. /** Returns a mask showing which of the available input channels are currently
  23799. enabled.
  23800. @see getInputChannelNames
  23801. */
  23802. virtual const BigInteger getActiveInputChannels() const = 0;
  23803. /** Returns the device's output latency.
  23804. This is the delay in samples between a callback getting a block of data, and
  23805. that data actually getting played.
  23806. */
  23807. virtual int getOutputLatencyInSamples() = 0;
  23808. /** Returns the device's input latency.
  23809. This is the delay in samples between some audio actually arriving at the soundcard,
  23810. and the callback getting passed this block of data.
  23811. */
  23812. virtual int getInputLatencyInSamples() = 0;
  23813. /** True if this device can show a pop-up control panel for editing its settings.
  23814. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  23815. to display it.
  23816. */
  23817. virtual bool hasControlPanel() const;
  23818. /** Shows a device-specific control panel if there is one.
  23819. This should only be called for devices which return true from hasControlPanel().
  23820. */
  23821. virtual bool showControlPanel();
  23822. protected:
  23823. /** Creates a device, setting its name and type member variables. */
  23824. AudioIODevice (const String& deviceName,
  23825. const String& typeName);
  23826. /** @internal */
  23827. String name, typeName;
  23828. };
  23829. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23830. /*** End of inlined file: juce_AudioIODevice.h ***/
  23831. /**
  23832. Wrapper class to continuously stream audio from an audio source to an
  23833. AudioIODevice.
  23834. This object acts as an AudioIODeviceCallback, so can be attached to an
  23835. output device, and will stream audio from an AudioSource.
  23836. */
  23837. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23838. {
  23839. public:
  23840. /** Creates an empty AudioSourcePlayer. */
  23841. AudioSourcePlayer();
  23842. /** Destructor.
  23843. Make sure this object isn't still being used by an AudioIODevice before
  23844. deleting it!
  23845. */
  23846. virtual ~AudioSourcePlayer();
  23847. /** Changes the current audio source to play from.
  23848. If the source passed in is already being used, this method will do nothing.
  23849. If the source is not null, its prepareToPlay() method will be called
  23850. before it starts being used for playback.
  23851. If there's another source currently playing, its releaseResources() method
  23852. will be called after it has been swapped for the new one.
  23853. @param newSource the new source to use - this will NOT be deleted
  23854. by this object when no longer needed, so it's the
  23855. caller's responsibility to manage it.
  23856. */
  23857. void setSource (AudioSource* newSource);
  23858. /** Returns the source that's playing.
  23859. May return 0 if there's no source.
  23860. */
  23861. AudioSource* getCurrentSource() const throw() { return source; }
  23862. /** Sets a gain to apply to the audio data.
  23863. @see getGain
  23864. */
  23865. void setGain (const float newGain) throw();
  23866. /** Returns the current gain.
  23867. @see setGain
  23868. */
  23869. float getGain() const throw() { return gain; }
  23870. /** Implementation of the AudioIODeviceCallback method. */
  23871. void audioDeviceIOCallback (const float** inputChannelData,
  23872. int totalNumInputChannels,
  23873. float** outputChannelData,
  23874. int totalNumOutputChannels,
  23875. int numSamples);
  23876. /** Implementation of the AudioIODeviceCallback method. */
  23877. void audioDeviceAboutToStart (AudioIODevice* device);
  23878. /** Implementation of the AudioIODeviceCallback method. */
  23879. void audioDeviceStopped();
  23880. juce_UseDebuggingNewOperator
  23881. private:
  23882. CriticalSection readLock;
  23883. AudioSource* source;
  23884. double sampleRate;
  23885. int bufferSize;
  23886. float* channels [128];
  23887. float* outputChans [128];
  23888. const float* inputChans [128];
  23889. AudioSampleBuffer tempBuffer;
  23890. float lastGain, gain;
  23891. AudioSourcePlayer (const AudioSourcePlayer&);
  23892. AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23893. };
  23894. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23895. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  23896. #endif
  23897. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23898. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  23899. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23900. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23901. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  23902. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23903. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23904. /**
  23905. An AudioSource which takes another source as input, and buffers it using a thread.
  23906. Create this as a wrapper around another thread, and it will read-ahead with
  23907. a background thread to smooth out playback. You can either create one of these
  23908. directly, or use it indirectly using an AudioTransportSource.
  23909. @see PositionableAudioSource, AudioTransportSource
  23910. */
  23911. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23912. {
  23913. public:
  23914. /** Creates a BufferingAudioSource.
  23915. @param source the input source to read from
  23916. @param deleteSourceWhenDeleted if true, then the input source object will
  23917. be deleted when this object is deleted
  23918. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23919. */
  23920. BufferingAudioSource (PositionableAudioSource* source,
  23921. const bool deleteSourceWhenDeleted,
  23922. int numberOfSamplesToBuffer);
  23923. /** Destructor.
  23924. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23925. flag was set in the constructor.
  23926. */
  23927. ~BufferingAudioSource();
  23928. /** Implementation of the AudioSource method. */
  23929. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23930. /** Implementation of the AudioSource method. */
  23931. void releaseResources();
  23932. /** Implementation of the AudioSource method. */
  23933. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23934. /** Implements the PositionableAudioSource method. */
  23935. void setNextReadPosition (int newPosition);
  23936. /** Implements the PositionableAudioSource method. */
  23937. int getNextReadPosition() const;
  23938. /** Implements the PositionableAudioSource method. */
  23939. int getTotalLength() const { return source->getTotalLength(); }
  23940. /** Implements the PositionableAudioSource method. */
  23941. bool isLooping() const { return source->isLooping(); }
  23942. juce_UseDebuggingNewOperator
  23943. private:
  23944. PositionableAudioSource* source;
  23945. bool deleteSourceWhenDeleted;
  23946. int numberOfSamplesToBuffer;
  23947. AudioSampleBuffer buffer;
  23948. CriticalSection bufferStartPosLock;
  23949. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23950. bool wasSourceLooping;
  23951. double volatile sampleRate;
  23952. friend class SharedBufferingAudioSourceThread;
  23953. bool readNextBufferChunk();
  23954. void readBufferSection (int start, int length, int bufferOffset);
  23955. BufferingAudioSource (const BufferingAudioSource&);
  23956. BufferingAudioSource& operator= (const BufferingAudioSource&);
  23957. };
  23958. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23959. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  23960. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  23961. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23962. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23963. /**
  23964. A type of AudioSource that takes an input source and changes its sample rate.
  23965. @see AudioSource
  23966. */
  23967. class JUCE_API ResamplingAudioSource : public AudioSource
  23968. {
  23969. public:
  23970. /** Creates a ResamplingAudioSource for a given input source.
  23971. @param inputSource the input source to read from
  23972. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23973. this object is deleted
  23974. @param numChannels the number of channels to process
  23975. */
  23976. ResamplingAudioSource (AudioSource* const inputSource,
  23977. const bool deleteInputWhenDeleted,
  23978. int numChannels = 2);
  23979. /** Destructor. */
  23980. ~ResamplingAudioSource();
  23981. /** Changes the resampling ratio.
  23982. (This value can be changed at any time, even while the source is running).
  23983. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23984. values will speed it up; lower values will slow it
  23985. down. The ratio must be greater than 0
  23986. */
  23987. void setResamplingRatio (const double samplesInPerOutputSample);
  23988. /** Returns the current resampling ratio.
  23989. This is the value that was set by setResamplingRatio().
  23990. */
  23991. double getResamplingRatio() const throw() { return ratio; }
  23992. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23993. void releaseResources();
  23994. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23995. juce_UseDebuggingNewOperator
  23996. private:
  23997. AudioSource* const input;
  23998. const bool deleteInputWhenDeleted;
  23999. double ratio, lastRatio;
  24000. AudioSampleBuffer buffer;
  24001. int bufferPos, sampsInBuffer;
  24002. double subSampleOffset;
  24003. double coefficients[6];
  24004. CriticalSection ratioLock;
  24005. const int numChannels;
  24006. HeapBlock<float*> destBuffers, srcBuffers;
  24007. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  24008. void createLowPass (const double proportionalRate);
  24009. struct FilterState
  24010. {
  24011. double x1, x2, y1, y2;
  24012. };
  24013. HeapBlock<FilterState> filterStates;
  24014. void resetFilters();
  24015. void applyFilter (float* samples, int num, FilterState& fs);
  24016. ResamplingAudioSource (const ResamplingAudioSource&);
  24017. ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  24018. };
  24019. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24020. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  24021. /**
  24022. An AudioSource that takes a PositionableAudioSource and allows it to be
  24023. played, stopped, started, etc.
  24024. This can also be told use a buffer and background thread to read ahead, and
  24025. if can correct for different sample-rates.
  24026. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  24027. to control playback of an audio file.
  24028. @see AudioSource, AudioSourcePlayer
  24029. */
  24030. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  24031. public ChangeBroadcaster
  24032. {
  24033. public:
  24034. /** Creates an AudioTransportSource.
  24035. After creating one of these, use the setSource() method to select an input source.
  24036. */
  24037. AudioTransportSource();
  24038. /** Destructor. */
  24039. ~AudioTransportSource();
  24040. /** Sets the reader that is being used as the input source.
  24041. This will stop playback, reset the position to 0 and change to the new reader.
  24042. The source passed in will not be deleted by this object, so must be managed by
  24043. the caller.
  24044. @param newSource the new input source to use. This may be zero
  24045. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  24046. is zero, no reading ahead will be done; if it's
  24047. greater than zero, a BufferingAudioSource will be used
  24048. to do the reading-ahead
  24049. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  24050. rate of the source, and playback will be sample-rate
  24051. adjusted to maintain playback at the correct pitch. If
  24052. this is 0, no sample-rate adjustment will be performed
  24053. */
  24054. void setSource (PositionableAudioSource* const newSource,
  24055. int readAheadBufferSize = 0,
  24056. double sourceSampleRateToCorrectFor = 0.0);
  24057. /** Changes the current playback position in the source stream.
  24058. The next time the getNextAudioBlock() method is called, this
  24059. is the time from which it'll read data.
  24060. @see getPosition
  24061. */
  24062. void setPosition (double newPosition);
  24063. /** Returns the position that the next data block will be read from
  24064. This is a time in seconds.
  24065. */
  24066. double getCurrentPosition() const;
  24067. /** Returns true if the player has stopped because its input stream ran out of data.
  24068. */
  24069. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  24070. /** Starts playing (if a source has been selected).
  24071. If it starts playing, this will send a message to any ChangeListeners
  24072. that are registered with this object.
  24073. */
  24074. void start();
  24075. /** Stops playing.
  24076. If it's actually playing, this will send a message to any ChangeListeners
  24077. that are registered with this object.
  24078. */
  24079. void stop();
  24080. /** Returns true if it's currently playing. */
  24081. bool isPlaying() const throw() { return playing; }
  24082. /** Changes the gain to apply to the output.
  24083. @param newGain a factor by which to multiply the outgoing samples,
  24084. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  24085. */
  24086. void setGain (const float newGain) throw();
  24087. /** Returns the current gain setting.
  24088. @see setGain
  24089. */
  24090. float getGain() const throw() { return gain; }
  24091. /** Implementation of the AudioSource method. */
  24092. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24093. /** Implementation of the AudioSource method. */
  24094. void releaseResources();
  24095. /** Implementation of the AudioSource method. */
  24096. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24097. /** Implements the PositionableAudioSource method. */
  24098. void setNextReadPosition (int newPosition);
  24099. /** Implements the PositionableAudioSource method. */
  24100. int getNextReadPosition() const;
  24101. /** Implements the PositionableAudioSource method. */
  24102. int getTotalLength() const;
  24103. /** Implements the PositionableAudioSource method. */
  24104. bool isLooping() const;
  24105. juce_UseDebuggingNewOperator
  24106. private:
  24107. PositionableAudioSource* source;
  24108. ResamplingAudioSource* resamplerSource;
  24109. BufferingAudioSource* bufferingSource;
  24110. PositionableAudioSource* positionableSource;
  24111. AudioSource* masterSource;
  24112. CriticalSection callbackLock;
  24113. float volatile gain, lastGain;
  24114. bool volatile playing, stopped;
  24115. double sampleRate, sourceSampleRate;
  24116. int blockSize, readAheadBufferSize;
  24117. bool isPrepared, inputStreamEOF;
  24118. AudioTransportSource (const AudioTransportSource&);
  24119. AudioTransportSource& operator= (const AudioTransportSource&);
  24120. };
  24121. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24122. /*** End of inlined file: juce_AudioTransportSource.h ***/
  24123. #endif
  24124. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24125. #endif
  24126. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24127. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  24128. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24129. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24130. /**
  24131. An AudioSource that takes the audio from another source, and re-maps its
  24132. input and output channels to a different arrangement.
  24133. You can use this to increase or decrease the number of channels that an
  24134. audio source uses, or to re-order those channels.
  24135. Call the reset() method before using it to set up a default mapping, and then
  24136. the setInputChannelMapping() and setOutputChannelMapping() methods to
  24137. create an appropriate mapping, otherwise no channels will be connected and
  24138. it'll produce silence.
  24139. @see AudioSource
  24140. */
  24141. class ChannelRemappingAudioSource : public AudioSource
  24142. {
  24143. public:
  24144. /** Creates a remapping source that will pass on audio from the given input.
  24145. @param source the input source to use. Make sure that this doesn't
  24146. get deleted before the ChannelRemappingAudioSource object
  24147. @param deleteSourceWhenDeleted if true, the input source will be deleted
  24148. when this object is deleted, if false, the caller is
  24149. responsible for its deletion
  24150. */
  24151. ChannelRemappingAudioSource (AudioSource* const source,
  24152. const bool deleteSourceWhenDeleted);
  24153. /** Destructor. */
  24154. ~ChannelRemappingAudioSource();
  24155. /** Specifies a number of channels that this audio source must produce from its
  24156. getNextAudioBlock() callback.
  24157. */
  24158. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  24159. /** Clears any mapped channels.
  24160. After this, no channels are mapped, so this object will produce silence. Create
  24161. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  24162. */
  24163. void clearAllMappings() throw();
  24164. /** Creates an input channel mapping.
  24165. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  24166. data will be sent to destChannelIndex of our input source.
  24167. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  24168. source specified when this object was created).
  24169. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  24170. during our getNextAudioBlock() callback
  24171. */
  24172. void setInputChannelMapping (const int destChannelIndex,
  24173. const int sourceChannelIndex) throw();
  24174. /** Creates an output channel mapping.
  24175. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  24176. our input audio source will be copied to channel destChannelIndex of the final buffer.
  24177. @param sourceChannelIndex the index of an output channel coming from our input audio source
  24178. (i.e. the source specified when this object was created).
  24179. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  24180. during our getNextAudioBlock() callback
  24181. */
  24182. void setOutputChannelMapping (const int sourceChannelIndex,
  24183. const int destChannelIndex) throw();
  24184. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  24185. our input audio source.
  24186. */
  24187. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  24188. /** Returns the output channel to which channel outputChannelIndex of our input audio
  24189. source will be sent to.
  24190. */
  24191. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  24192. /** Returns an XML object to encapsulate the state of the mappings.
  24193. @see restoreFromXml
  24194. */
  24195. XmlElement* createXml() const throw();
  24196. /** Restores the mappings from an XML object created by createXML().
  24197. @see createXml
  24198. */
  24199. void restoreFromXml (const XmlElement& e) throw();
  24200. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24201. void releaseResources();
  24202. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24203. juce_UseDebuggingNewOperator
  24204. private:
  24205. int requiredNumberOfChannels;
  24206. Array <int> remappedInputs, remappedOutputs;
  24207. AudioSource* const source;
  24208. const bool deleteSourceWhenDeleted;
  24209. AudioSampleBuffer buffer;
  24210. AudioSourceChannelInfo remappedInfo;
  24211. CriticalSection lock;
  24212. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  24213. ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  24214. };
  24215. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24216. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  24217. #endif
  24218. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24219. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  24220. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24221. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24222. /*** Start of inlined file: juce_IIRFilter.h ***/
  24223. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  24224. #define __JUCE_IIRFILTER_JUCEHEADER__
  24225. /**
  24226. An IIR filter that can perform low, high, or band-pass filtering on an
  24227. audio signal.
  24228. @see IIRFilterAudioSource
  24229. */
  24230. class JUCE_API IIRFilter
  24231. {
  24232. public:
  24233. /** Creates a filter.
  24234. Initially the filter is inactive, so will have no effect on samples that
  24235. you process with it. Use the appropriate method to turn it into the type
  24236. of filter needed.
  24237. */
  24238. IIRFilter();
  24239. /** Creates a copy of another filter. */
  24240. IIRFilter (const IIRFilter& other);
  24241. /** Destructor. */
  24242. ~IIRFilter();
  24243. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  24244. Note that this clears the processing state, but the type of filter and
  24245. its coefficients aren't changed. To put a filter into an inactive state, use
  24246. the makeInactive() method.
  24247. */
  24248. void reset() throw();
  24249. /** Performs the filter operation on the given set of samples.
  24250. */
  24251. void processSamples (float* samples,
  24252. int numSamples) throw();
  24253. /** Processes a single sample, without any locking or checking.
  24254. Use this if you need fast processing of a single value, but be aware that
  24255. this isn't thread-safe in the way that processSamples() is.
  24256. */
  24257. float processSingleSampleRaw (float sample) throw();
  24258. /** Sets the filter up to act as a low-pass filter.
  24259. */
  24260. void makeLowPass (double sampleRate,
  24261. double frequency) throw();
  24262. /** Sets the filter up to act as a high-pass filter.
  24263. */
  24264. void makeHighPass (double sampleRate,
  24265. double frequency) throw();
  24266. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  24267. The gain is a scale factor that the low frequencies are multiplied by, so values
  24268. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  24269. attenuate them.
  24270. */
  24271. void makeLowShelf (double sampleRate,
  24272. double cutOffFrequency,
  24273. double Q,
  24274. float gainFactor) throw();
  24275. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  24276. The gain is a scale factor that the high frequencies are multiplied by, so values
  24277. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  24278. attenuate them.
  24279. */
  24280. void makeHighShelf (double sampleRate,
  24281. double cutOffFrequency,
  24282. double Q,
  24283. float gainFactor) throw();
  24284. /** Sets the filter up to act as a band pass filter centred around a
  24285. frequency, with a variable Q and gain.
  24286. The gain is a scale factor that the centre frequencies are multiplied by, so
  24287. values greater than 1.0 will boost the centre frequencies, values less than
  24288. 1.0 will attenuate them.
  24289. */
  24290. void makeBandPass (double sampleRate,
  24291. double centreFrequency,
  24292. double Q,
  24293. float gainFactor) throw();
  24294. /** Clears the filter's coefficients so that it becomes inactive.
  24295. */
  24296. void makeInactive() throw();
  24297. /** Makes this filter duplicate the set-up of another one.
  24298. */
  24299. void copyCoefficientsFrom (const IIRFilter& other) throw();
  24300. juce_UseDebuggingNewOperator
  24301. protected:
  24302. CriticalSection processLock;
  24303. void setCoefficients (double c1, double c2, double c3,
  24304. double c4, double c5, double c6) throw();
  24305. bool active;
  24306. float coefficients[6];
  24307. float x1, x2, y1, y2;
  24308. // (use the copyCoefficientsFrom() method instead of this operator)
  24309. IIRFilter& operator= (const IIRFilter&);
  24310. };
  24311. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  24312. /*** End of inlined file: juce_IIRFilter.h ***/
  24313. /**
  24314. An AudioSource that performs an IIR filter on another source.
  24315. */
  24316. class JUCE_API IIRFilterAudioSource : public AudioSource
  24317. {
  24318. public:
  24319. /** Creates a IIRFilterAudioSource for a given input source.
  24320. @param inputSource the input source to read from
  24321. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24322. this object is deleted
  24323. */
  24324. IIRFilterAudioSource (AudioSource* const inputSource,
  24325. const bool deleteInputWhenDeleted);
  24326. /** Destructor. */
  24327. ~IIRFilterAudioSource();
  24328. /** Changes the filter to use the same parameters as the one being passed in.
  24329. */
  24330. void setFilterParameters (const IIRFilter& newSettings);
  24331. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24332. void releaseResources();
  24333. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24334. juce_UseDebuggingNewOperator
  24335. private:
  24336. AudioSource* const input;
  24337. const bool deleteInputWhenDeleted;
  24338. OwnedArray <IIRFilter> iirFilters;
  24339. IIRFilterAudioSource (const IIRFilterAudioSource&);
  24340. IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  24341. };
  24342. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24343. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  24344. #endif
  24345. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24346. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  24347. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24348. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24349. /**
  24350. An AudioSource that mixes together the output of a set of other AudioSources.
  24351. Input sources can be added and removed while the mixer is running as long as their
  24352. prepareToPlay() and releaseResources() methods are called before and after adding
  24353. them to the mixer.
  24354. */
  24355. class JUCE_API MixerAudioSource : public AudioSource
  24356. {
  24357. public:
  24358. /** Creates a MixerAudioSource.
  24359. */
  24360. MixerAudioSource();
  24361. /** Destructor. */
  24362. ~MixerAudioSource();
  24363. /** Adds an input source to the mixer.
  24364. If the mixer is running you'll need to make sure that the input source
  24365. is ready to play by calling its prepareToPlay() method before adding it.
  24366. If the mixer is stopped, then its input sources will be automatically
  24367. prepared when the mixer's prepareToPlay() method is called.
  24368. @param newInput the source to add to the mixer
  24369. @param deleteWhenRemoved if true, then this source will be deleted when
  24370. the mixer is deleted or when removeAllInputs() is
  24371. called (unless the source is previously removed
  24372. with the removeInputSource method)
  24373. */
  24374. void addInputSource (AudioSource* newInput,
  24375. const bool deleteWhenRemoved);
  24376. /** Removes an input source.
  24377. If the mixer is running, this will remove the source but not call its
  24378. releaseResources() method, so the caller might want to do this manually.
  24379. @param input the source to remove
  24380. @param deleteSource whether to delete this source after it's been removed
  24381. */
  24382. void removeInputSource (AudioSource* input,
  24383. const bool deleteSource);
  24384. /** Removes all the input sources.
  24385. If the mixer is running, this will remove the sources but not call their
  24386. releaseResources() method, so the caller might want to do this manually.
  24387. Any sources which were added with the deleteWhenRemoved flag set will be
  24388. deleted by this method.
  24389. */
  24390. void removeAllInputs();
  24391. /** Implementation of the AudioSource method.
  24392. This will call prepareToPlay() on all its input sources.
  24393. */
  24394. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24395. /** Implementation of the AudioSource method.
  24396. This will call releaseResources() on all its input sources.
  24397. */
  24398. void releaseResources();
  24399. /** Implementation of the AudioSource method. */
  24400. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24401. juce_UseDebuggingNewOperator
  24402. private:
  24403. Array <AudioSource*> inputs;
  24404. BigInteger inputsToDelete;
  24405. CriticalSection lock;
  24406. AudioSampleBuffer tempBuffer;
  24407. double currentSampleRate;
  24408. int bufferSizeExpected;
  24409. MixerAudioSource (const MixerAudioSource&);
  24410. MixerAudioSource& operator= (const MixerAudioSource&);
  24411. };
  24412. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24413. /*** End of inlined file: juce_MixerAudioSource.h ***/
  24414. #endif
  24415. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24416. #endif
  24417. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24418. #endif
  24419. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24420. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24421. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24422. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24423. /**
  24424. A simple AudioSource that generates a sine wave.
  24425. */
  24426. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24427. {
  24428. public:
  24429. /** Creates a ToneGeneratorAudioSource. */
  24430. ToneGeneratorAudioSource();
  24431. /** Destructor. */
  24432. ~ToneGeneratorAudioSource();
  24433. /** Sets the signal's amplitude. */
  24434. void setAmplitude (const float newAmplitude);
  24435. /** Sets the signal's frequency. */
  24436. void setFrequency (const double newFrequencyHz);
  24437. /** Implementation of the AudioSource method. */
  24438. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24439. /** Implementation of the AudioSource method. */
  24440. void releaseResources();
  24441. /** Implementation of the AudioSource method. */
  24442. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24443. juce_UseDebuggingNewOperator
  24444. private:
  24445. double frequency, sampleRate;
  24446. double currentPhase, phasePerSample;
  24447. float amplitude;
  24448. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24449. ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24450. };
  24451. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24452. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24453. #endif
  24454. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24455. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  24456. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24457. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24458. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  24459. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24460. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24461. class AudioDeviceManager;
  24462. class Component;
  24463. /**
  24464. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24465. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  24466. method. Each of the objects returned can then be used to list the available
  24467. devices of that type. E.g.
  24468. @code
  24469. OwnedArray <AudioIODeviceType> types;
  24470. myAudioDeviceManager.createAudioDeviceTypes (types);
  24471. for (int i = 0; i < types.size(); ++i)
  24472. {
  24473. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24474. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24475. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24476. for (int j = 0; j < deviceNames.size(); ++j)
  24477. {
  24478. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24479. ...
  24480. }
  24481. }
  24482. @endcode
  24483. For an easier way of managing audio devices and their settings, have a look at the
  24484. AudioDeviceManager class.
  24485. @see AudioIODevice, AudioDeviceManager
  24486. */
  24487. class JUCE_API AudioIODeviceType
  24488. {
  24489. public:
  24490. /** Returns the name of this type of driver that this object manages.
  24491. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24492. */
  24493. const String& getTypeName() const throw() { return typeName; }
  24494. /** Refreshes the object's cached list of known devices.
  24495. This must be called at least once before calling getDeviceNames() or any of
  24496. the other device creation methods.
  24497. */
  24498. virtual void scanForDevices() = 0;
  24499. /** Returns the list of available devices of this type.
  24500. The scanForDevices() method must have been called to create this list.
  24501. @param wantInputNames only really used by DirectSound where devices are split up
  24502. into inputs and outputs, this indicates whether to use
  24503. the input or output name to refer to a pair of devices.
  24504. */
  24505. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  24506. /** Returns the name of the default device.
  24507. This will be one of the names from the getDeviceNames() list.
  24508. @param forInput if true, this means that a default input device should be
  24509. returned; if false, it should return the default output
  24510. */
  24511. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  24512. /** Returns the index of a given device in the list of device names.
  24513. If asInput is true, it shows the index in the inputs list, otherwise it
  24514. looks for it in the outputs list.
  24515. */
  24516. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  24517. /** Returns true if two different devices can be used for the input and output.
  24518. */
  24519. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24520. /** Creates one of the devices of this type.
  24521. The deviceName must be one of the strings returned by getDeviceNames(), and
  24522. scanForDevices() must have been called before this method is used.
  24523. */
  24524. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24525. const String& inputDeviceName) = 0;
  24526. struct DeviceSetupDetails
  24527. {
  24528. AudioDeviceManager* manager;
  24529. int minNumInputChannels, maxNumInputChannels;
  24530. int minNumOutputChannels, maxNumOutputChannels;
  24531. bool useStereoPairs;
  24532. };
  24533. /** Destructor. */
  24534. virtual ~AudioIODeviceType();
  24535. protected:
  24536. explicit AudioIODeviceType (const String& typeName);
  24537. private:
  24538. String typeName;
  24539. AudioIODeviceType (const AudioIODeviceType&);
  24540. AudioIODeviceType& operator= (const AudioIODeviceType&);
  24541. };
  24542. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24543. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  24544. /*** Start of inlined file: juce_MidiInput.h ***/
  24545. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  24546. #define __JUCE_MIDIINPUT_JUCEHEADER__
  24547. /*** Start of inlined file: juce_MidiMessage.h ***/
  24548. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  24549. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  24550. /**
  24551. Encapsulates a MIDI message.
  24552. @see MidiMessageSequence, MidiOutput, MidiInput
  24553. */
  24554. class JUCE_API MidiMessage
  24555. {
  24556. public:
  24557. /** Creates a 3-byte short midi message.
  24558. @param byte1 message byte 1
  24559. @param byte2 message byte 2
  24560. @param byte3 message byte 3
  24561. @param timeStamp the time to give the midi message - this value doesn't
  24562. use any particular units, so will be application-specific
  24563. */
  24564. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  24565. /** Creates a 2-byte short midi message.
  24566. @param byte1 message byte 1
  24567. @param byte2 message byte 2
  24568. @param timeStamp the time to give the midi message - this value doesn't
  24569. use any particular units, so will be application-specific
  24570. */
  24571. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  24572. /** Creates a 1-byte short midi message.
  24573. @param byte1 message byte 1
  24574. @param timeStamp the time to give the midi message - this value doesn't
  24575. use any particular units, so will be application-specific
  24576. */
  24577. MidiMessage (int byte1, double timeStamp = 0) throw();
  24578. /** Creates a midi message from a block of data. */
  24579. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  24580. /** Reads the next midi message from some data.
  24581. This will read as many bytes from a data stream as it needs to make a
  24582. complete message, and will return the number of bytes it used. This lets
  24583. you read a sequence of midi messages from a file or stream.
  24584. @param data the data to read from
  24585. @param maxBytesToUse the maximum number of bytes it's allowed to read
  24586. @param numBytesUsed returns the number of bytes that were actually needed
  24587. @param lastStatusByte in a sequence of midi messages, the initial byte
  24588. can be dropped from a message if it's the same as the
  24589. first byte of the previous message, so this lets you
  24590. supply the byte to use if the first byte of the message
  24591. has in fact been dropped.
  24592. @param timeStamp the time to give the midi message - this value doesn't
  24593. use any particular units, so will be application-specific
  24594. */
  24595. MidiMessage (const void* data, int maxBytesToUse,
  24596. int& numBytesUsed, uint8 lastStatusByte,
  24597. double timeStamp = 0);
  24598. /** Creates a copy of another midi message. */
  24599. MidiMessage (const MidiMessage& other);
  24600. /** Creates a copy of another midi message, with a different timestamp. */
  24601. MidiMessage (const MidiMessage& other, double newTimeStamp);
  24602. /** Destructor. */
  24603. ~MidiMessage();
  24604. /** Copies this message from another one. */
  24605. MidiMessage& operator= (const MidiMessage& other);
  24606. /** Returns a pointer to the raw midi data.
  24607. @see getRawDataSize
  24608. */
  24609. uint8* getRawData() const throw() { return data; }
  24610. /** Returns the number of bytes of data in the message.
  24611. @see getRawData
  24612. */
  24613. int getRawDataSize() const throw() { return size; }
  24614. /** Returns the timestamp associated with this message.
  24615. The exact meaning of this time and its units will vary, as messages are used in
  24616. a variety of different contexts.
  24617. If you're getting the message from a midi file, this could be a time in seconds, or
  24618. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  24619. If the message is being used in a MidiBuffer, it might indicate the number of
  24620. audio samples from the start of the buffer.
  24621. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  24622. for details of the way that it initialises this value.
  24623. @see setTimeStamp, addToTimeStamp
  24624. */
  24625. double getTimeStamp() const throw() { return timeStamp; }
  24626. /** Changes the message's associated timestamp.
  24627. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  24628. @see addToTimeStamp, getTimeStamp
  24629. */
  24630. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  24631. /** Adds a value to the message's timestamp.
  24632. The units for the timestamp will be application-specific.
  24633. */
  24634. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  24635. /** Returns the midi channel associated with the message.
  24636. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  24637. if it's a sysex)
  24638. @see isForChannel, setChannel
  24639. */
  24640. int getChannel() const throw();
  24641. /** Returns true if the message applies to the given midi channel.
  24642. @param channelNumber the channel number to look for, in the range 1 to 16
  24643. @see getChannel, setChannel
  24644. */
  24645. bool isForChannel (int channelNumber) const throw();
  24646. /** Changes the message's midi channel.
  24647. This won't do anything for non-channel messages like sysexes.
  24648. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  24649. */
  24650. void setChannel (int newChannelNumber) throw();
  24651. /** Returns true if this is a system-exclusive message.
  24652. */
  24653. bool isSysEx() const throw();
  24654. /** Returns a pointer to the sysex data inside the message.
  24655. If this event isn't a sysex event, it'll return 0.
  24656. @see getSysExDataSize
  24657. */
  24658. const uint8* getSysExData() const throw();
  24659. /** Returns the size of the sysex data.
  24660. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  24661. @see getSysExData
  24662. */
  24663. int getSysExDataSize() const throw();
  24664. /** Returns true if this message is a 'key-down' event.
  24665. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  24666. velocity 0, it will still be considered to be a note-on and the
  24667. method will return true. If returnTrueForVelocity0 is false, then
  24668. if this is a note-on event with velocity 0, it'll be regarded as
  24669. a note-off, and the method will return false
  24670. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  24671. */
  24672. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  24673. /** Creates a key-down message (using a floating-point velocity).
  24674. @param channel the midi channel, in the range 1 to 16
  24675. @param noteNumber the key number, 0 to 127
  24676. @param velocity in the range 0 to 1.0
  24677. @see isNoteOn
  24678. */
  24679. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  24680. /** Creates a key-down message (using an integer velocity).
  24681. @param channel the midi channel, in the range 1 to 16
  24682. @param noteNumber the key number, 0 to 127
  24683. @param velocity in the range 0 to 127
  24684. @see isNoteOn
  24685. */
  24686. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  24687. /** Returns true if this message is a 'key-up' event.
  24688. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  24689. for a note-on event with a velocity of 0.
  24690. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  24691. */
  24692. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  24693. /** Creates a key-up message.
  24694. @param channel the midi channel, in the range 1 to 16
  24695. @param noteNumber the key number, 0 to 127
  24696. @see isNoteOff
  24697. */
  24698. static const MidiMessage noteOff (int channel, int noteNumber) throw();
  24699. /** Returns true if this message is a 'key-down' or 'key-up' event.
  24700. @see isNoteOn, isNoteOff
  24701. */
  24702. bool isNoteOnOrOff() const throw();
  24703. /** Returns the midi note number for note-on and note-off messages.
  24704. If the message isn't a note-on or off, the value returned will be
  24705. meaningless.
  24706. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  24707. */
  24708. int getNoteNumber() const throw();
  24709. /** Changes the midi note number of a note-on or note-off message.
  24710. If the message isn't a note on or off, this will do nothing.
  24711. */
  24712. void setNoteNumber (int newNoteNumber) throw();
  24713. /** Returns the velocity of a note-on or note-off message.
  24714. The value returned will be in the range 0 to 127.
  24715. If the message isn't a note-on or off event, it will return 0.
  24716. @see getFloatVelocity
  24717. */
  24718. uint8 getVelocity() const throw();
  24719. /** Returns the velocity of a note-on or note-off message.
  24720. The value returned will be in the range 0 to 1.0
  24721. If the message isn't a note-on or off event, it will return 0.
  24722. @see getVelocity, setVelocity
  24723. */
  24724. float getFloatVelocity() const throw();
  24725. /** Changes the velocity of a note-on or note-off message.
  24726. If the message isn't a note on or off, this will do nothing.
  24727. @param newVelocity the new velocity, in the range 0 to 1.0
  24728. @see getFloatVelocity, multiplyVelocity
  24729. */
  24730. void setVelocity (float newVelocity) throw();
  24731. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  24732. If the message isn't a note on or off, this will do nothing.
  24733. @param scaleFactor the value by which to multiply the velocity
  24734. @see setVelocity
  24735. */
  24736. void multiplyVelocity (float scaleFactor) throw();
  24737. /** Returns true if the message is a program (patch) change message.
  24738. @see getProgramChangeNumber, getGMInstrumentName
  24739. */
  24740. bool isProgramChange() const throw();
  24741. /** Returns the new program number of a program change message.
  24742. If the message isn't a program change, the value returned will be
  24743. nonsense.
  24744. @see isProgramChange, getGMInstrumentName
  24745. */
  24746. int getProgramChangeNumber() const throw();
  24747. /** Creates a program-change message.
  24748. @param channel the midi channel, in the range 1 to 16
  24749. @param programNumber the midi program number, 0 to 127
  24750. @see isProgramChange, getGMInstrumentName
  24751. */
  24752. static const MidiMessage programChange (int channel, int programNumber) throw();
  24753. /** Returns true if the message is a pitch-wheel move.
  24754. @see getPitchWheelValue, pitchWheel
  24755. */
  24756. bool isPitchWheel() const throw();
  24757. /** Returns the pitch wheel position from a pitch-wheel move message.
  24758. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  24759. If called for messages which aren't pitch wheel events, the number returned will be
  24760. nonsense.
  24761. @see isPitchWheel
  24762. */
  24763. int getPitchWheelValue() const throw();
  24764. /** Creates a pitch-wheel move message.
  24765. @param channel the midi channel, in the range 1 to 16
  24766. @param position the wheel position, in the range 0 to 16383
  24767. @see isPitchWheel
  24768. */
  24769. static const MidiMessage pitchWheel (int channel, int position) throw();
  24770. /** Returns true if the message is an aftertouch event.
  24771. For aftertouch events, use the getNoteNumber() method to find out the key
  24772. that it applies to, and getAftertouchValue() to find out the amount. Use
  24773. getChannel() to find out the channel.
  24774. @see getAftertouchValue, getNoteNumber
  24775. */
  24776. bool isAftertouch() const throw();
  24777. /** Returns the amount of aftertouch from an aftertouch messages.
  24778. The value returned is in the range 0 to 127, and will be nonsense for messages
  24779. other than aftertouch messages.
  24780. @see isAftertouch
  24781. */
  24782. int getAfterTouchValue() const throw();
  24783. /** Creates an aftertouch message.
  24784. @param channel the midi channel, in the range 1 to 16
  24785. @param noteNumber the key number, 0 to 127
  24786. @param aftertouchAmount the amount of aftertouch, 0 to 127
  24787. @see isAftertouch
  24788. */
  24789. static const MidiMessage aftertouchChange (int channel,
  24790. int noteNumber,
  24791. int aftertouchAmount) throw();
  24792. /** Returns true if the message is a channel-pressure change event.
  24793. This is like aftertouch, but common to the whole channel rather than a specific
  24794. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  24795. to find out the channel.
  24796. @see channelPressureChange
  24797. */
  24798. bool isChannelPressure() const throw();
  24799. /** Returns the pressure from a channel pressure change message.
  24800. @returns the pressure, in the range 0 to 127
  24801. @see isChannelPressure, channelPressureChange
  24802. */
  24803. int getChannelPressureValue() const throw();
  24804. /** Creates a channel-pressure change event.
  24805. @param channel the midi channel: 1 to 16
  24806. @param pressure the pressure, 0 to 127
  24807. @see isChannelPressure
  24808. */
  24809. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  24810. /** Returns true if this is a midi controller message.
  24811. @see getControllerNumber, getControllerValue, controllerEvent
  24812. */
  24813. bool isController() const throw();
  24814. /** Returns the controller number of a controller message.
  24815. The name of the controller can be looked up using the getControllerName() method.
  24816. Note that the value returned is invalid for messages that aren't controller changes.
  24817. @see isController, getControllerName, getControllerValue
  24818. */
  24819. int getControllerNumber() const throw();
  24820. /** Returns the controller value from a controller message.
  24821. A value 0 to 127 is returned to indicate the new controller position.
  24822. Note that the value returned is invalid for messages that aren't controller changes.
  24823. @see isController, getControllerNumber
  24824. */
  24825. int getControllerValue() const throw();
  24826. /** Creates a controller message.
  24827. @param channel the midi channel, in the range 1 to 16
  24828. @param controllerType the type of controller
  24829. @param value the controller value
  24830. @see isController
  24831. */
  24832. static const MidiMessage controllerEvent (int channel,
  24833. int controllerType,
  24834. int value) throw();
  24835. /** Checks whether this message is an all-notes-off message.
  24836. @see allNotesOff
  24837. */
  24838. bool isAllNotesOff() const throw();
  24839. /** Checks whether this message is an all-sound-off message.
  24840. @see allSoundOff
  24841. */
  24842. bool isAllSoundOff() const throw();
  24843. /** Creates an all-notes-off message.
  24844. @param channel the midi channel, in the range 1 to 16
  24845. @see isAllNotesOff
  24846. */
  24847. static const MidiMessage allNotesOff (int channel) throw();
  24848. /** Creates an all-sound-off message.
  24849. @param channel the midi channel, in the range 1 to 16
  24850. @see isAllSoundOff
  24851. */
  24852. static const MidiMessage allSoundOff (int channel) throw();
  24853. /** Creates an all-controllers-off message.
  24854. @param channel the midi channel, in the range 1 to 16
  24855. */
  24856. static const MidiMessage allControllersOff (int channel) throw();
  24857. /** Returns true if this event is a meta-event.
  24858. Meta-events are things like tempo changes, track names, etc.
  24859. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24860. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24861. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24862. */
  24863. bool isMetaEvent() const throw();
  24864. /** Returns a meta-event's type number.
  24865. If the message isn't a meta-event, this will return -1.
  24866. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24867. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24868. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24869. */
  24870. int getMetaEventType() const throw();
  24871. /** Returns a pointer to the data in a meta-event.
  24872. @see isMetaEvent, getMetaEventLength
  24873. */
  24874. const uint8* getMetaEventData() const throw();
  24875. /** Returns the length of the data for a meta-event.
  24876. @see isMetaEvent, getMetaEventData
  24877. */
  24878. int getMetaEventLength() const throw();
  24879. /** Returns true if this is a 'track' meta-event. */
  24880. bool isTrackMetaEvent() const throw();
  24881. /** Returns true if this is an 'end-of-track' meta-event. */
  24882. bool isEndOfTrackMetaEvent() const throw();
  24883. /** Creates an end-of-track meta-event.
  24884. @see isEndOfTrackMetaEvent
  24885. */
  24886. static const MidiMessage endOfTrack() throw();
  24887. /** Returns true if this is an 'track name' meta-event.
  24888. You can use the getTextFromTextMetaEvent() method to get the track's name.
  24889. */
  24890. bool isTrackNameEvent() const throw();
  24891. /** Returns true if this is a 'text' meta-event.
  24892. @see getTextFromTextMetaEvent
  24893. */
  24894. bool isTextMetaEvent() const throw();
  24895. /** Returns the text from a text meta-event.
  24896. @see isTextMetaEvent
  24897. */
  24898. const String getTextFromTextMetaEvent() const;
  24899. /** Returns true if this is a 'tempo' meta-event.
  24900. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  24901. */
  24902. bool isTempoMetaEvent() const throw();
  24903. /** Returns the tick length from a tempo meta-event.
  24904. @param timeFormat the 16-bit time format value from the midi file's header.
  24905. @returns the tick length (in seconds).
  24906. @see isTempoMetaEvent
  24907. */
  24908. double getTempoMetaEventTickLength (short timeFormat) const throw();
  24909. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  24910. @see isTempoMetaEvent, getTempoMetaEventTickLength
  24911. */
  24912. double getTempoSecondsPerQuarterNote() const throw();
  24913. /** Creates a tempo meta-event.
  24914. @see isTempoMetaEvent
  24915. */
  24916. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  24917. /** Returns true if this is a 'time-signature' meta-event.
  24918. @see getTimeSignatureInfo
  24919. */
  24920. bool isTimeSignatureMetaEvent() const throw();
  24921. /** Returns the time-signature values from a time-signature meta-event.
  24922. @see isTimeSignatureMetaEvent
  24923. */
  24924. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  24925. /** Creates a time-signature meta-event.
  24926. @see isTimeSignatureMetaEvent
  24927. */
  24928. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  24929. /** Returns true if this is a 'key-signature' meta-event.
  24930. @see getKeySignatureNumberOfSharpsOrFlats
  24931. */
  24932. bool isKeySignatureMetaEvent() const throw();
  24933. /** Returns the key from a key-signature meta-event.
  24934. @see isKeySignatureMetaEvent
  24935. */
  24936. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  24937. /** Returns true if this is a 'channel' meta-event.
  24938. A channel meta-event specifies the midi channel that should be used
  24939. for subsequent meta-events.
  24940. @see getMidiChannelMetaEventChannel
  24941. */
  24942. bool isMidiChannelMetaEvent() const throw();
  24943. /** Returns the channel number from a channel meta-event.
  24944. @returns the channel, in the range 1 to 16.
  24945. @see isMidiChannelMetaEvent
  24946. */
  24947. int getMidiChannelMetaEventChannel() const throw();
  24948. /** Creates a midi channel meta-event.
  24949. @param channel the midi channel, in the range 1 to 16
  24950. @see isMidiChannelMetaEvent
  24951. */
  24952. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  24953. /** Returns true if this is an active-sense message. */
  24954. bool isActiveSense() const throw();
  24955. /** Returns true if this is a midi start event.
  24956. @see midiStart
  24957. */
  24958. bool isMidiStart() const throw();
  24959. /** Creates a midi start event. */
  24960. static const MidiMessage midiStart() throw();
  24961. /** Returns true if this is a midi continue event.
  24962. @see midiContinue
  24963. */
  24964. bool isMidiContinue() const throw();
  24965. /** Creates a midi continue event. */
  24966. static const MidiMessage midiContinue() throw();
  24967. /** Returns true if this is a midi stop event.
  24968. @see midiStop
  24969. */
  24970. bool isMidiStop() const throw();
  24971. /** Creates a midi stop event. */
  24972. static const MidiMessage midiStop() throw();
  24973. /** Returns true if this is a midi clock event.
  24974. @see midiClock, songPositionPointer
  24975. */
  24976. bool isMidiClock() const throw();
  24977. /** Creates a midi clock event. */
  24978. static const MidiMessage midiClock() throw();
  24979. /** Returns true if this is a song-position-pointer message.
  24980. @see getSongPositionPointerMidiBeat, songPositionPointer
  24981. */
  24982. bool isSongPositionPointer() const throw();
  24983. /** Returns the midi beat-number of a song-position-pointer message.
  24984. @see isSongPositionPointer, songPositionPointer
  24985. */
  24986. int getSongPositionPointerMidiBeat() const throw();
  24987. /** Creates a song-position-pointer message.
  24988. The position is a number of midi beats from the start of the song, where 1 midi
  24989. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  24990. are 4 midi beats in a quarter-note.
  24991. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  24992. */
  24993. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  24994. /** Returns true if this is a quarter-frame midi timecode message.
  24995. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  24996. */
  24997. bool isQuarterFrame() const throw();
  24998. /** Returns the sequence number of a quarter-frame midi timecode message.
  24999. This will be a value between 0 and 7.
  25000. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  25001. */
  25002. int getQuarterFrameSequenceNumber() const throw();
  25003. /** Returns the value from a quarter-frame message.
  25004. This will be the lower nybble of the message's data-byte, a value
  25005. between 0 and 15
  25006. */
  25007. int getQuarterFrameValue() const throw();
  25008. /** Creates a quarter-frame MTC message.
  25009. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  25010. @param value a value 0 to 15 for the lower nybble of the message's data byte
  25011. */
  25012. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  25013. /** SMPTE timecode types.
  25014. Used by the getFullFrameParameters() and fullFrame() methods.
  25015. */
  25016. enum SmpteTimecodeType
  25017. {
  25018. fps24 = 0,
  25019. fps25 = 1,
  25020. fps30drop = 2,
  25021. fps30 = 3
  25022. };
  25023. /** Returns true if this is a full-frame midi timecode message.
  25024. */
  25025. bool isFullFrame() const throw();
  25026. /** Extracts the timecode information from a full-frame midi timecode message.
  25027. You should only call this on messages where you've used isFullFrame() to
  25028. check that they're the right kind.
  25029. */
  25030. void getFullFrameParameters (int& hours,
  25031. int& minutes,
  25032. int& seconds,
  25033. int& frames,
  25034. SmpteTimecodeType& timecodeType) const throw();
  25035. /** Creates a full-frame MTC message.
  25036. */
  25037. static const MidiMessage fullFrame (int hours,
  25038. int minutes,
  25039. int seconds,
  25040. int frames,
  25041. SmpteTimecodeType timecodeType);
  25042. /** Types of MMC command.
  25043. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  25044. */
  25045. enum MidiMachineControlCommand
  25046. {
  25047. mmc_stop = 1,
  25048. mmc_play = 2,
  25049. mmc_deferredplay = 3,
  25050. mmc_fastforward = 4,
  25051. mmc_rewind = 5,
  25052. mmc_recordStart = 6,
  25053. mmc_recordStop = 7,
  25054. mmc_pause = 9
  25055. };
  25056. /** Checks whether this is an MMC message.
  25057. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  25058. */
  25059. bool isMidiMachineControlMessage() const throw();
  25060. /** For an MMC message, this returns its type.
  25061. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  25062. calling this method.
  25063. */
  25064. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  25065. /** Creates an MMC message.
  25066. */
  25067. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  25068. /** Checks whether this is an MMC "goto" message.
  25069. If it is, the parameters passed-in are set to the time that the message contains.
  25070. @see midiMachineControlGoto
  25071. */
  25072. bool isMidiMachineControlGoto (int& hours,
  25073. int& minutes,
  25074. int& seconds,
  25075. int& frames) const throw();
  25076. /** Creates an MMC "goto" message.
  25077. This messages tells the device to go to a specific frame.
  25078. @see isMidiMachineControlGoto
  25079. */
  25080. static const MidiMessage midiMachineControlGoto (int hours,
  25081. int minutes,
  25082. int seconds,
  25083. int frames);
  25084. /** Creates a master-volume change message.
  25085. @param volume the volume, 0 to 1.0
  25086. */
  25087. static const MidiMessage masterVolume (float volume);
  25088. /** Creates a system-exclusive message.
  25089. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  25090. */
  25091. static const MidiMessage createSysExMessage (const uint8* sysexData,
  25092. int dataSize);
  25093. /** Reads a midi variable-length integer.
  25094. @param data the data to read the number from
  25095. @param numBytesUsed on return, this will be set to the number of bytes that were read
  25096. */
  25097. static int readVariableLengthVal (const uint8* data,
  25098. int& numBytesUsed) throw();
  25099. /** Based on the first byte of a short midi message, this uses a lookup table
  25100. to return the message length (either 1, 2, or 3 bytes).
  25101. The value passed in must be 0x80 or higher.
  25102. */
  25103. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  25104. /** Returns the name of a midi note number.
  25105. E.g "C", "D#", etc.
  25106. @param noteNumber the midi note number, 0 to 127
  25107. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  25108. they'll be flattened, e.g. "Db"
  25109. @param includeOctaveNumber if true, the octave number will be appended to the string,
  25110. e.g. "C#4"
  25111. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  25112. number that will be used for middle C's octave
  25113. @see getMidiNoteInHertz
  25114. */
  25115. static const String getMidiNoteName (int noteNumber,
  25116. bool useSharps,
  25117. bool includeOctaveNumber,
  25118. int octaveNumForMiddleC) throw();
  25119. /** Returns the frequency of a midi note number.
  25120. @see getMidiNoteName
  25121. */
  25122. static const double getMidiNoteInHertz (int noteNumber) throw();
  25123. /** Returns the standard name of a GM instrument.
  25124. @param midiInstrumentNumber the program number 0 to 127
  25125. @see getProgramChangeNumber
  25126. */
  25127. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  25128. /** Returns the name of a bank of GM instruments.
  25129. @param midiBankNumber the bank, 0 to 15
  25130. */
  25131. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  25132. /** Returns the standard name of a channel 10 percussion sound.
  25133. @param midiNoteNumber the key number, 35 to 81
  25134. */
  25135. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  25136. /** Returns the name of a controller type number.
  25137. @see getControllerNumber
  25138. */
  25139. static const String getControllerName (int controllerNumber) throw();
  25140. juce_UseDebuggingNewOperator
  25141. private:
  25142. double timeStamp;
  25143. uint8* data;
  25144. int size;
  25145. union
  25146. {
  25147. uint8 asBytes[4];
  25148. uint32 asInt32;
  25149. } preallocatedData;
  25150. };
  25151. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  25152. /*** End of inlined file: juce_MidiMessage.h ***/
  25153. class MidiInput;
  25154. /**
  25155. Receives midi messages from a midi input device.
  25156. This class is overridden to handle incoming midi messages. See the MidiInput
  25157. class for more details.
  25158. @see MidiInput
  25159. */
  25160. class JUCE_API MidiInputCallback
  25161. {
  25162. public:
  25163. /** Destructor. */
  25164. virtual ~MidiInputCallback() {}
  25165. /** Receives an incoming message.
  25166. A MidiInput object will call this method when a midi event arrives. It'll be
  25167. called on a high-priority system thread, so avoid doing anything time-consuming
  25168. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  25169. for queueing incoming messages for use later.
  25170. @param source the MidiInput object that generated the message
  25171. @param message the incoming message. The message's timestamp is set to a value
  25172. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  25173. time when the message arrived.
  25174. */
  25175. virtual void handleIncomingMidiMessage (MidiInput* source,
  25176. const MidiMessage& message) = 0;
  25177. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  25178. If a long sysex message is broken up into multiple packets, this callback is made
  25179. for each packet that arrives until the message is finished, at which point
  25180. the normal handleIncomingMidiMessage() callback will be made with the entire
  25181. message.
  25182. The message passed in will contain the start of a sysex, but won't be finished
  25183. with the terminating 0xf7 byte.
  25184. */
  25185. virtual void handlePartialSysexMessage (MidiInput* source,
  25186. const uint8* messageData,
  25187. const int numBytesSoFar,
  25188. const double timestamp)
  25189. {
  25190. // (this bit is just to avoid compiler warnings about unused variables)
  25191. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  25192. }
  25193. };
  25194. /**
  25195. Represents a midi input device.
  25196. To create one of these, use the static getDevices() method to find out what inputs are
  25197. available, and then use the openDevice() method to try to open one.
  25198. @see MidiOutput
  25199. */
  25200. class JUCE_API MidiInput
  25201. {
  25202. public:
  25203. /** Returns a list of the available midi input devices.
  25204. You can open one of the devices by passing its index into the
  25205. openDevice() method.
  25206. @see getDefaultDeviceIndex, openDevice
  25207. */
  25208. static const StringArray getDevices();
  25209. /** Returns the index of the default midi input device to use.
  25210. This refers to the index in the list returned by getDevices().
  25211. */
  25212. static int getDefaultDeviceIndex();
  25213. /** Tries to open one of the midi input devices.
  25214. This will return a MidiInput object if it manages to open it. You can then
  25215. call start() and stop() on this device, and delete it when no longer needed.
  25216. If the device can't be opened, this will return a null pointer.
  25217. @param deviceIndex the index of a device from the list returned by getDevices()
  25218. @param callback the object that will receive the midi messages from this device.
  25219. @see MidiInputCallback, getDevices
  25220. */
  25221. static MidiInput* openDevice (int deviceIndex,
  25222. MidiInputCallback* callback);
  25223. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25224. /** This will try to create a new midi input device (Not available on Windows).
  25225. This will attempt to create a new midi input device with the specified name,
  25226. for other apps to connect to.
  25227. Returns 0 if a device can't be created.
  25228. @param deviceName the name to use for the new device
  25229. @param callback the object that will receive the midi messages from this device.
  25230. */
  25231. static MidiInput* createNewDevice (const String& deviceName,
  25232. MidiInputCallback* callback);
  25233. #endif
  25234. /** Destructor. */
  25235. virtual ~MidiInput();
  25236. /** Returns the name of this device.
  25237. */
  25238. virtual const String getName() const throw() { return name; }
  25239. /** Allows you to set a custom name for the device, in case you don't like the name
  25240. it was given when created.
  25241. */
  25242. virtual void setName (const String& newName) throw() { name = newName; }
  25243. /** Starts the device running.
  25244. After calling this, the device will start sending midi messages to the
  25245. MidiInputCallback object that was specified when the openDevice() method
  25246. was called.
  25247. @see stop
  25248. */
  25249. virtual void start();
  25250. /** Stops the device running.
  25251. @see start
  25252. */
  25253. virtual void stop();
  25254. juce_UseDebuggingNewOperator
  25255. protected:
  25256. String name;
  25257. void* internal;
  25258. explicit MidiInput (const String& name);
  25259. private:
  25260. MidiInput (const MidiInput&);
  25261. MidiInput& operator= (const MidiInput&);
  25262. };
  25263. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  25264. /*** End of inlined file: juce_MidiInput.h ***/
  25265. /*** Start of inlined file: juce_MidiOutput.h ***/
  25266. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25267. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  25268. /*** Start of inlined file: juce_MidiBuffer.h ***/
  25269. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  25270. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  25271. /**
  25272. Holds a sequence of time-stamped midi events.
  25273. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  25274. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  25275. @see MidiMessage
  25276. */
  25277. class JUCE_API MidiBuffer
  25278. {
  25279. public:
  25280. /** Creates an empty MidiBuffer. */
  25281. MidiBuffer() throw();
  25282. /** Creates a MidiBuffer containing a single midi message. */
  25283. explicit MidiBuffer (const MidiMessage& message) throw();
  25284. /** Creates a copy of another MidiBuffer. */
  25285. MidiBuffer (const MidiBuffer& other) throw();
  25286. /** Makes a copy of another MidiBuffer. */
  25287. MidiBuffer& operator= (const MidiBuffer& other) throw();
  25288. /** Destructor */
  25289. ~MidiBuffer() throw();
  25290. /** Removes all events from the buffer. */
  25291. void clear() throw();
  25292. /** Removes all events between two times from the buffer.
  25293. All events for which (start <= event position < start + numSamples) will
  25294. be removed.
  25295. */
  25296. void clear (const int start,
  25297. const int numSamples) throw();
  25298. /** Returns true if the buffer is empty.
  25299. To actually retrieve the events, use a MidiBuffer::Iterator object
  25300. */
  25301. bool isEmpty() const throw();
  25302. /** Counts the number of events in the buffer.
  25303. This is actually quite a slow operation, as it has to iterate through all
  25304. the events, so you might prefer to call isEmpty() if that's all you need
  25305. to know.
  25306. */
  25307. int getNumEvents() const throw();
  25308. /** Adds an event to the buffer.
  25309. The sample number will be used to determine the position of the event in
  25310. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  25311. ignored.
  25312. If an event is added whose sample position is the same as one or more events
  25313. already in the buffer, the new event will be placed after the existing ones.
  25314. To retrieve events, use a MidiBuffer::Iterator object
  25315. */
  25316. void addEvent (const MidiMessage& midiMessage,
  25317. const int sampleNumber) throw();
  25318. /** Adds an event to the buffer from raw midi data.
  25319. The sample number will be used to determine the position of the event in
  25320. the buffer, which is always kept sorted.
  25321. If an event is added whose sample position is the same as one or more events
  25322. already in the buffer, the new event will be placed after the existing ones.
  25323. The event data will be inspected to calculate the number of bytes in length that
  25324. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  25325. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  25326. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  25327. add an event at all.
  25328. To retrieve events, use a MidiBuffer::Iterator object
  25329. */
  25330. void addEvent (const uint8* const rawMidiData,
  25331. const int maxBytesOfMidiData,
  25332. const int sampleNumber) throw();
  25333. /** Adds some events from another buffer to this one.
  25334. @param otherBuffer the buffer containing the events you want to add
  25335. @param startSample the lowest sample number in the source buffer for which
  25336. events should be added. Any source events whose timestamp is
  25337. less than this will be ignored
  25338. @param numSamples the valid range of samples from the source buffer for which
  25339. events should be added - i.e. events in the source buffer whose
  25340. timestamp is greater than or equal to (startSample + numSamples)
  25341. will be ignored. If this value is less than 0, all events after
  25342. startSample will be taken.
  25343. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  25344. that are added to this buffer
  25345. */
  25346. void addEvents (const MidiBuffer& otherBuffer,
  25347. const int startSample,
  25348. const int numSamples,
  25349. const int sampleDeltaToAdd) throw();
  25350. /** Returns the sample number of the first event in the buffer.
  25351. If the buffer's empty, this will just return 0.
  25352. */
  25353. int getFirstEventTime() const throw();
  25354. /** Returns the sample number of the last event in the buffer.
  25355. If the buffer's empty, this will just return 0.
  25356. */
  25357. int getLastEventTime() const throw();
  25358. /** Exchanges the contents of this buffer with another one.
  25359. This is a quick operation, because no memory allocating or copying is done, it
  25360. just swaps the internal state of the two buffers.
  25361. */
  25362. void swapWith (MidiBuffer& other);
  25363. /** Preallocates some memory for the buffer to use.
  25364. This helps to avoid needing to reallocate space when the buffer has messages
  25365. added to it.
  25366. */
  25367. void ensureSize (size_t minimumNumBytes);
  25368. /**
  25369. Used to iterate through the events in a MidiBuffer.
  25370. Note that altering the buffer while an iterator is using it isn't a
  25371. safe operation.
  25372. @see MidiBuffer
  25373. */
  25374. class Iterator
  25375. {
  25376. public:
  25377. /** Creates an Iterator for this MidiBuffer. */
  25378. Iterator (const MidiBuffer& buffer) throw();
  25379. /** Destructor. */
  25380. ~Iterator() throw();
  25381. /** Repositions the iterator so that the next event retrieved will be the first
  25382. one whose sample position is at greater than or equal to the given position.
  25383. */
  25384. void setNextSamplePosition (const int samplePosition) throw();
  25385. /** Retrieves a copy of the next event from the buffer.
  25386. @param result on return, this will be the message (the MidiMessage's timestamp
  25387. is not set)
  25388. @param samplePosition on return, this will be the position of the event
  25389. @returns true if an event was found, or false if the iterator has reached
  25390. the end of the buffer
  25391. */
  25392. bool getNextEvent (MidiMessage& result,
  25393. int& samplePosition) throw();
  25394. /** Retrieves the next event from the buffer.
  25395. @param midiData on return, this pointer will be set to a block of data containing
  25396. the midi message. Note that to make it fast, this is a pointer
  25397. directly into the MidiBuffer's internal data, so is only valid
  25398. temporarily until the MidiBuffer is altered.
  25399. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  25400. midi message
  25401. @param samplePosition on return, this will be the position of the event
  25402. @returns true if an event was found, or false if the iterator has reached
  25403. the end of the buffer
  25404. */
  25405. bool getNextEvent (const uint8* &midiData,
  25406. int& numBytesOfMidiData,
  25407. int& samplePosition) throw();
  25408. juce_UseDebuggingNewOperator
  25409. private:
  25410. const MidiBuffer& buffer;
  25411. const uint8* data;
  25412. Iterator (const Iterator&);
  25413. Iterator& operator= (const Iterator&);
  25414. };
  25415. juce_UseDebuggingNewOperator
  25416. private:
  25417. friend class MidiBuffer::Iterator;
  25418. MemoryBlock data;
  25419. int bytesUsed;
  25420. uint8* getData() const throw();
  25421. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  25422. static int getEventTime (const void* d) throw();
  25423. static uint16 getEventDataSize (const void* d) throw();
  25424. static uint16 getEventTotalSize (const void* d) throw();
  25425. };
  25426. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  25427. /*** End of inlined file: juce_MidiBuffer.h ***/
  25428. /**
  25429. Represents a midi output device.
  25430. To create one of these, use the static getDevices() method to find out what
  25431. outputs are available, then use the openDevice() method to try to open one.
  25432. @see MidiInput
  25433. */
  25434. class JUCE_API MidiOutput : private Thread
  25435. {
  25436. public:
  25437. /** Returns a list of the available midi output devices.
  25438. You can open one of the devices by passing its index into the
  25439. openDevice() method.
  25440. @see getDefaultDeviceIndex, openDevice
  25441. */
  25442. static const StringArray getDevices();
  25443. /** Returns the index of the default midi output device to use.
  25444. This refers to the index in the list returned by getDevices().
  25445. */
  25446. static int getDefaultDeviceIndex();
  25447. /** Tries to open one of the midi output devices.
  25448. This will return a MidiOutput object if it manages to open it. You can then
  25449. send messages to this device, and delete it when no longer needed.
  25450. If the device can't be opened, this will return a null pointer.
  25451. @param deviceIndex the index of a device from the list returned by getDevices()
  25452. @see getDevices
  25453. */
  25454. static MidiOutput* openDevice (int deviceIndex);
  25455. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25456. /** This will try to create a new midi output device (Not available on Windows).
  25457. This will attempt to create a new midi output device that other apps can connect
  25458. to and use as their midi input.
  25459. Returns 0 if a device can't be created.
  25460. @param deviceName the name to use for the new device
  25461. */
  25462. static MidiOutput* createNewDevice (const String& deviceName);
  25463. #endif
  25464. /** Destructor. */
  25465. virtual ~MidiOutput();
  25466. /** Makes this device output a midi message.
  25467. @see MidiMessage
  25468. */
  25469. virtual void sendMessageNow (const MidiMessage& message);
  25470. /** Sends a midi reset to the device. */
  25471. virtual void reset();
  25472. /** Returns the current volume setting for this device. */
  25473. virtual bool getVolume (float& leftVol,
  25474. float& rightVol);
  25475. /** Changes the overall volume for this device. */
  25476. virtual void setVolume (float leftVol,
  25477. float rightVol);
  25478. /** This lets you supply a block of messages that will be sent out at some point
  25479. in the future.
  25480. The MidiOutput class has an internal thread that can send out timestamped
  25481. messages - this appends a set of messages to its internal buffer, ready for
  25482. sending.
  25483. This will only work if you've already started the thread with startBackgroundThread().
  25484. A time is supplied, at which the block of messages should be sent. This time uses
  25485. the same time base as Time::getMillisecondCounter(), and must be in the future.
  25486. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  25487. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  25488. samplesPerSecondForBuffer value is needed to convert this sample position to a
  25489. real time.
  25490. */
  25491. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  25492. double millisecondCounterToStartAt,
  25493. double samplesPerSecondForBuffer);
  25494. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  25495. */
  25496. virtual void clearAllPendingMessages();
  25497. /** Starts up a background thread so that the device can send blocks of data.
  25498. Call this to get the device ready, before using sendBlockOfMessages().
  25499. */
  25500. virtual void startBackgroundThread();
  25501. /** Stops the background thread, and clears any pending midi events.
  25502. @see startBackgroundThread
  25503. */
  25504. virtual void stopBackgroundThread();
  25505. juce_UseDebuggingNewOperator
  25506. protected:
  25507. void* internal;
  25508. struct PendingMessage
  25509. {
  25510. PendingMessage (const uint8* data, int len, double sampleNumber);
  25511. MidiMessage message;
  25512. PendingMessage* next;
  25513. juce_UseDebuggingNewOperator
  25514. };
  25515. CriticalSection lock;
  25516. PendingMessage* firstMessage;
  25517. MidiOutput();
  25518. void run();
  25519. private:
  25520. MidiOutput (const MidiOutput&);
  25521. MidiOutput& operator= (const MidiOutput&);
  25522. };
  25523. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  25524. /*** End of inlined file: juce_MidiOutput.h ***/
  25525. /*** Start of inlined file: juce_ComboBox.h ***/
  25526. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  25527. #define __JUCE_COMBOBOX_JUCEHEADER__
  25528. /*** Start of inlined file: juce_Label.h ***/
  25529. #ifndef __JUCE_LABEL_JUCEHEADER__
  25530. #define __JUCE_LABEL_JUCEHEADER__
  25531. /*** Start of inlined file: juce_TextEditor.h ***/
  25532. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  25533. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  25534. /*** Start of inlined file: juce_Viewport.h ***/
  25535. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  25536. #define __JUCE_VIEWPORT_JUCEHEADER__
  25537. /*** Start of inlined file: juce_ScrollBar.h ***/
  25538. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  25539. #define __JUCE_SCROLLBAR_JUCEHEADER__
  25540. /*** Start of inlined file: juce_Button.h ***/
  25541. #ifndef __JUCE_BUTTON_JUCEHEADER__
  25542. #define __JUCE_BUTTON_JUCEHEADER__
  25543. /*** Start of inlined file: juce_TooltipWindow.h ***/
  25544. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25545. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25546. /*** Start of inlined file: juce_TooltipClient.h ***/
  25547. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25548. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25549. /**
  25550. Components that want to use pop-up tooltips should implement this interface.
  25551. A TooltipWindow will wait for the mouse to hover over a component that
  25552. implements the TooltipClient interface, and when it finds one, it will display
  25553. the tooltip returned by its getTooltip() method.
  25554. @see TooltipWindow, SettableTooltipClient
  25555. */
  25556. class JUCE_API TooltipClient
  25557. {
  25558. public:
  25559. /** Destructor. */
  25560. virtual ~TooltipClient() {}
  25561. /** Returns the string that this object wants to show as its tooltip. */
  25562. virtual const String getTooltip() = 0;
  25563. };
  25564. /**
  25565. An implementation of TooltipClient that stores the tooltip string and a method
  25566. for changing it.
  25567. This makes it easy to add a tooltip to a custom component, by simply adding this
  25568. as a base class and calling setTooltip().
  25569. Many of the Juce widgets already use this as a base class to implement their
  25570. tooltips.
  25571. @see TooltipClient, TooltipWindow
  25572. */
  25573. class JUCE_API SettableTooltipClient : public TooltipClient
  25574. {
  25575. public:
  25576. /** Destructor. */
  25577. virtual ~SettableTooltipClient() {}
  25578. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  25579. virtual const String getTooltip() { return tooltipString; }
  25580. juce_UseDebuggingNewOperator
  25581. protected:
  25582. String tooltipString;
  25583. };
  25584. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25585. /*** End of inlined file: juce_TooltipClient.h ***/
  25586. /**
  25587. A window that displays a pop-up tooltip when the mouse hovers over another component.
  25588. To enable tooltips in your app, just create a single instance of a TooltipWindow
  25589. object.
  25590. The TooltipWindow object will then stay invisible, waiting until the mouse
  25591. hovers for the specified length of time - it will then see if it's currently
  25592. over a component which implements the TooltipClient interface, and if so,
  25593. it will make itself visible to show the tooltip in the appropriate place.
  25594. @see TooltipClient, SettableTooltipClient
  25595. */
  25596. class JUCE_API TooltipWindow : public Component,
  25597. private Timer
  25598. {
  25599. public:
  25600. /** Creates a tooltip window.
  25601. Make sure your app only creates one instance of this class, otherwise you'll
  25602. get multiple overlaid tooltips appearing. The window will initially be invisible
  25603. and will make itself visible when it needs to display a tip.
  25604. To change the style of tooltips, see the LookAndFeel class for its tooltip
  25605. methods.
  25606. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  25607. otherwise the tooltip will be added to the given parent
  25608. component.
  25609. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  25610. before a tooltip will be shown
  25611. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  25612. */
  25613. explicit TooltipWindow (Component* parentComponent = 0,
  25614. int millisecondsBeforeTipAppears = 700);
  25615. /** Destructor. */
  25616. ~TooltipWindow();
  25617. /** Changes the time before the tip appears.
  25618. This lets you change the value that was set in the constructor.
  25619. */
  25620. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  25621. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  25622. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25623. methods.
  25624. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25625. */
  25626. enum ColourIds
  25627. {
  25628. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  25629. textColourId = 0x1001c00, /**< The colour to use for the text. */
  25630. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  25631. };
  25632. juce_UseDebuggingNewOperator
  25633. private:
  25634. int millisecondsBeforeTipAppears;
  25635. Point<int> lastMousePos;
  25636. int mouseClicks;
  25637. unsigned int lastCompChangeTime, lastHideTime;
  25638. Component* lastComponentUnderMouse;
  25639. bool changedCompsSinceShown;
  25640. String tipShowing, lastTipUnderMouse;
  25641. void paint (Graphics& g);
  25642. void mouseEnter (const MouseEvent& e);
  25643. void timerCallback();
  25644. static const String getTipFor (Component* c);
  25645. void showFor (const String& tip);
  25646. void hide();
  25647. TooltipWindow (const TooltipWindow&);
  25648. TooltipWindow& operator= (const TooltipWindow&);
  25649. };
  25650. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25651. /*** End of inlined file: juce_TooltipWindow.h ***/
  25652. class Button;
  25653. /**
  25654. Used to receive callbacks when a button is clicked.
  25655. @see Button::addButtonListener, Button::removeButtonListener
  25656. */
  25657. class JUCE_API ButtonListener
  25658. {
  25659. public:
  25660. /** Destructor. */
  25661. virtual ~ButtonListener() {}
  25662. /** Called when the button is clicked. */
  25663. virtual void buttonClicked (Button* button) = 0;
  25664. /** Called when the button's state changes. */
  25665. virtual void buttonStateChanged (Button*) {}
  25666. };
  25667. /**
  25668. A base class for buttons.
  25669. This contains all the logic for button behaviours such as enabling/disabling,
  25670. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  25671. and radio groups, etc.
  25672. @see TextButton, DrawableButton, ToggleButton
  25673. */
  25674. class JUCE_API Button : public Component,
  25675. public SettableTooltipClient,
  25676. public ApplicationCommandManagerListener,
  25677. public Value::Listener,
  25678. private KeyListener
  25679. {
  25680. protected:
  25681. /** Creates a button.
  25682. @param buttonName the text to put in the button (the component's name is also
  25683. initially set to this string, but these can be changed later
  25684. using the setName() and setButtonText() methods)
  25685. */
  25686. explicit Button (const String& buttonName);
  25687. public:
  25688. /** Destructor. */
  25689. virtual ~Button();
  25690. /** Changes the button's text.
  25691. @see getButtonText
  25692. */
  25693. void setButtonText (const String& newText);
  25694. /** Returns the text displayed in the button.
  25695. @see setButtonText
  25696. */
  25697. const String getButtonText() const { return text; }
  25698. /** Returns true if the button is currently being held down by the mouse.
  25699. @see isOver
  25700. */
  25701. bool isDown() const throw();
  25702. /** Returns true if the mouse is currently over the button.
  25703. This will be also be true if the mouse is being held down.
  25704. @see isDown
  25705. */
  25706. bool isOver() const throw();
  25707. /** A button has an on/off state associated with it, and this changes that.
  25708. By default buttons are 'off' and for simple buttons that you click to perform
  25709. an action you won't change this. Toggle buttons, however will want to
  25710. change their state when turned on or off.
  25711. @param shouldBeOn whether to set the button's toggle state to be on or
  25712. off. If it's a member of a button group, this will
  25713. always try to turn it on, and to turn off any other
  25714. buttons in the group
  25715. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  25716. the button will be repainted but no notification will
  25717. be sent
  25718. @see getToggleState, setRadioGroupId
  25719. */
  25720. void setToggleState (bool shouldBeOn,
  25721. bool sendChangeNotification);
  25722. /** Returns true if the button in 'on'.
  25723. By default buttons are 'off' and for simple buttons that you click to perform
  25724. an action you won't change this. Toggle buttons, however will want to
  25725. change their state when turned on or off.
  25726. @see setToggleState
  25727. */
  25728. bool getToggleState() const throw() { return isOn.getValue(); }
  25729. /** Returns the Value object that represents the botton's toggle state.
  25730. You can use this Value object to connect the button's state to external values or setters,
  25731. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  25732. your own Value object.
  25733. @see getToggleState, Value
  25734. */
  25735. Value& getToggleStateValue() { return isOn; }
  25736. /** This tells the button to automatically flip the toggle state when
  25737. the button is clicked.
  25738. If set to true, then before the clicked() callback occurs, the toggle-state
  25739. of the button is flipped.
  25740. */
  25741. void setClickingTogglesState (bool shouldToggle) throw();
  25742. /** Returns true if this button is set to be an automatic toggle-button.
  25743. This returns the last value that was passed to setClickingTogglesState().
  25744. */
  25745. bool getClickingTogglesState() const throw();
  25746. /** Enables the button to act as a member of a mutually-exclusive group
  25747. of 'radio buttons'.
  25748. If the group ID is set to a non-zero number, then this button will
  25749. act as part of a group of buttons with the same ID, only one of
  25750. which can be 'on' at the same time. Note that when it's part of
  25751. a group, clicking a toggle-button that's 'on' won't turn it off.
  25752. To find other buttons with the same ID, this button will search through
  25753. its sibling components for ToggleButtons, so all the buttons for a
  25754. particular group must be placed inside the same parent component.
  25755. Set the group ID back to zero if you want it to act as a normal toggle
  25756. button again.
  25757. @see getRadioGroupId
  25758. */
  25759. void setRadioGroupId (int newGroupId);
  25760. /** Returns the ID of the group to which this button belongs.
  25761. (See setRadioGroupId() for an explanation of this).
  25762. */
  25763. int getRadioGroupId() const throw() { return radioGroupId; }
  25764. /** Registers a listener to receive events when this button's state changes.
  25765. If the listener is already registered, this will not register it again.
  25766. @see removeButtonListener
  25767. */
  25768. void addButtonListener (ButtonListener* newListener);
  25769. /** Removes a previously-registered button listener
  25770. @see addButtonListener
  25771. */
  25772. void removeButtonListener (ButtonListener* listener);
  25773. /** Causes the button to act as if it's been clicked.
  25774. This will asynchronously make the button draw itself going down and up, and
  25775. will then call back the clicked() method as if mouse was clicked on it.
  25776. @see clicked
  25777. */
  25778. virtual void triggerClick();
  25779. /** Sets a command ID for this button to automatically invoke when it's clicked.
  25780. When the button is pressed, it will use the given manager to trigger the
  25781. command ID.
  25782. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  25783. before this button is. To disable the command triggering, call this method and
  25784. pass 0 for the parameters.
  25785. If generateTooltip is true, then the button's tooltip will be automatically
  25786. generated based on the name of this command and its current shortcut key.
  25787. @see addShortcut, getCommandID
  25788. */
  25789. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  25790. int commandID,
  25791. bool generateTooltip);
  25792. /** Returns the command ID that was set by setCommandToTrigger().
  25793. */
  25794. int getCommandID() const throw() { return commandID; }
  25795. /** Assigns a shortcut key to trigger the button.
  25796. The button registers itself with its top-level parent component for keypresses.
  25797. Note that a different way of linking buttons to keypresses is by using the
  25798. setCommandToTrigger() method to invoke a command.
  25799. @see clearShortcuts
  25800. */
  25801. void addShortcut (const KeyPress& key);
  25802. /** Removes all key shortcuts that had been set for this button.
  25803. @see addShortcut
  25804. */
  25805. void clearShortcuts();
  25806. /** Returns true if the given keypress is a shortcut for this button.
  25807. @see addShortcut
  25808. */
  25809. bool isRegisteredForShortcut (const KeyPress& key) const;
  25810. /** Sets an auto-repeat speed for the button when it is held down.
  25811. (Auto-repeat is disabled by default).
  25812. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  25813. triggering the next click. If this is zero, auto-repeat
  25814. is disabled
  25815. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  25816. triggered
  25817. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  25818. get faster, the longer the button is held down, up to the
  25819. minimum interval specified here
  25820. */
  25821. void setRepeatSpeed (int initialDelayInMillisecs,
  25822. int repeatDelayInMillisecs,
  25823. int minimumDelayInMillisecs = -1) throw();
  25824. /** Sets whether the button click should happen when the mouse is pressed or released.
  25825. By default the button is only considered to have been clicked when the mouse is
  25826. released, but setting this to true will make it call the clicked() method as soon
  25827. as the button is pressed.
  25828. This is useful if the button is being used to show a pop-up menu, as it allows
  25829. the click to be used as a drag onto the menu.
  25830. */
  25831. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  25832. /** Returns the number of milliseconds since the last time the button
  25833. went into the 'down' state.
  25834. */
  25835. uint32 getMillisecondsSinceButtonDown() const throw();
  25836. /** (overridden from Component to do special stuff). */
  25837. void setVisible (bool shouldBeVisible);
  25838. /** Sets the tooltip for this button.
  25839. @see TooltipClient, TooltipWindow
  25840. */
  25841. void setTooltip (const String& newTooltip);
  25842. // (implementation of the TooltipClient method)
  25843. const String getTooltip();
  25844. /** A combination of these flags are used by setConnectedEdges().
  25845. */
  25846. enum ConnectedEdgeFlags
  25847. {
  25848. ConnectedOnLeft = 1,
  25849. ConnectedOnRight = 2,
  25850. ConnectedOnTop = 4,
  25851. ConnectedOnBottom = 8
  25852. };
  25853. /** Hints about which edges of the button might be connected to adjoining buttons.
  25854. The value passed in is a bitwise combination of any of the values in the
  25855. ConnectedEdgeFlags enum.
  25856. E.g. if you are placing two buttons adjacent to each other, you could use this to
  25857. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  25858. without rounded corners on the edges that connect. It's only a hint, so the
  25859. LookAndFeel can choose to ignore it if it's not relevent for this type of
  25860. button.
  25861. */
  25862. void setConnectedEdges (int connectedEdgeFlags);
  25863. /** Returns the set of flags passed into setConnectedEdges(). */
  25864. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  25865. /** Indicates whether the button adjoins another one on its left edge.
  25866. @see setConnectedEdges
  25867. */
  25868. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  25869. /** Indicates whether the button adjoins another one on its right edge.
  25870. @see setConnectedEdges
  25871. */
  25872. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  25873. /** Indicates whether the button adjoins another one on its top edge.
  25874. @see setConnectedEdges
  25875. */
  25876. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  25877. /** Indicates whether the button adjoins another one on its bottom edge.
  25878. @see setConnectedEdges
  25879. */
  25880. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  25881. /** Used by setState(). */
  25882. enum ButtonState
  25883. {
  25884. buttonNormal,
  25885. buttonOver,
  25886. buttonDown
  25887. };
  25888. /** Can be used to force the button into a particular state.
  25889. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  25890. from happening.
  25891. The state that you set here will only last until it is automatically changed when the mouse
  25892. enters or exits the button, or the mouse-button is pressed or released.
  25893. */
  25894. void setState (const ButtonState newState);
  25895. juce_UseDebuggingNewOperator
  25896. protected:
  25897. /** This method is called when the button has been clicked.
  25898. Subclasses can override this to perform whatever they actions they need
  25899. to do.
  25900. Alternatively, a ButtonListener can be added to the button, and these listeners
  25901. will be called when the click occurs.
  25902. @see triggerClick
  25903. */
  25904. virtual void clicked();
  25905. /** This method is called when the button has been clicked.
  25906. By default it just calls clicked(), but you might want to override it to handle
  25907. things like clicking when a modifier key is pressed, etc.
  25908. @see ModifierKeys
  25909. */
  25910. virtual void clicked (const ModifierKeys& modifiers);
  25911. /** Subclasses should override this to actually paint the button's contents.
  25912. It's better to use this than the paint method, because it gives you information
  25913. about the over/down state of the button.
  25914. @param g the graphics context to use
  25915. @param isMouseOverButton true if the button is either in the 'over' or
  25916. 'down' state
  25917. @param isButtonDown true if the button should be drawn in the 'down' position
  25918. */
  25919. virtual void paintButton (Graphics& g,
  25920. bool isMouseOverButton,
  25921. bool isButtonDown) = 0;
  25922. /** Called when the button's up/down/over state changes.
  25923. Subclasses can override this if they need to do something special when the button
  25924. goes up or down.
  25925. @see isDown, isOver
  25926. */
  25927. virtual void buttonStateChanged();
  25928. /** @internal */
  25929. virtual void internalClickCallback (const ModifierKeys& modifiers);
  25930. /** @internal */
  25931. void handleCommandMessage (int commandId);
  25932. /** @internal */
  25933. void mouseEnter (const MouseEvent& e);
  25934. /** @internal */
  25935. void mouseExit (const MouseEvent& e);
  25936. /** @internal */
  25937. void mouseDown (const MouseEvent& e);
  25938. /** @internal */
  25939. void mouseDrag (const MouseEvent& e);
  25940. /** @internal */
  25941. void mouseUp (const MouseEvent& e);
  25942. /** @internal */
  25943. bool keyPressed (const KeyPress& key);
  25944. /** @internal */
  25945. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  25946. /** @internal */
  25947. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  25948. /** @internal */
  25949. void paint (Graphics& g);
  25950. /** @internal */
  25951. void parentHierarchyChanged();
  25952. /** @internal */
  25953. void focusGained (FocusChangeType cause);
  25954. /** @internal */
  25955. void focusLost (FocusChangeType cause);
  25956. /** @internal */
  25957. void enablementChanged();
  25958. /** @internal */
  25959. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  25960. /** @internal */
  25961. void applicationCommandListChanged();
  25962. /** @internal */
  25963. void valueChanged (Value& value);
  25964. private:
  25965. Array <KeyPress> shortcuts;
  25966. Component::SafePointer<Component> keySource;
  25967. String text;
  25968. ListenerList <ButtonListener> buttonListeners;
  25969. class RepeatTimer;
  25970. friend class RepeatTimer;
  25971. friend class ScopedPointer <RepeatTimer>;
  25972. ScopedPointer <RepeatTimer> repeatTimer;
  25973. uint32 buttonPressTime, lastTimeCallbackTime;
  25974. ApplicationCommandManager* commandManagerToUse;
  25975. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  25976. int radioGroupId, commandID, connectedEdgeFlags;
  25977. ButtonState buttonState;
  25978. Value isOn;
  25979. bool lastToggleState : 1;
  25980. bool clickTogglesState : 1;
  25981. bool needsToRelease : 1;
  25982. bool needsRepainting : 1;
  25983. bool isKeyDown : 1;
  25984. bool triggerOnMouseDown : 1;
  25985. bool generateTooltip : 1;
  25986. void repeatTimerCallback();
  25987. RepeatTimer& getRepeatTimer();
  25988. ButtonState updateState (const MouseEvent* const e);
  25989. bool isShortcutPressed() const;
  25990. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  25991. void flashButtonState();
  25992. void sendClickMessage (const ModifierKeys& modifiers);
  25993. void sendStateMessage();
  25994. Button (const Button&);
  25995. Button& operator= (const Button&);
  25996. };
  25997. #endif // __JUCE_BUTTON_JUCEHEADER__
  25998. /*** End of inlined file: juce_Button.h ***/
  25999. class ScrollBar;
  26000. /**
  26001. A class for receiving events from a ScrollBar.
  26002. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  26003. method, and it will be called when the bar's position changes.
  26004. @see ScrollBar::addListener, ScrollBar::removeListener
  26005. */
  26006. class JUCE_API ScrollBarListener
  26007. {
  26008. public:
  26009. /** Destructor. */
  26010. virtual ~ScrollBarListener() {}
  26011. /** Called when a ScrollBar is moved.
  26012. @param scrollBarThatHasMoved the bar that has moved
  26013. @param newRangeStart the new range start of this bar
  26014. */
  26015. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  26016. double newRangeStart) = 0;
  26017. };
  26018. /**
  26019. A scrollbar component.
  26020. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  26021. sets the range of values it can represent. Then you can use setCurrentRange() to
  26022. change the position and size of the scrollbar's 'thumb'.
  26023. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  26024. the user moves it, and you can use the getCurrentRangeStart() to find out where
  26025. they moved it to.
  26026. The scrollbar will adjust its own visibility according to whether its thumb size
  26027. allows it to actually be scrolled.
  26028. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  26029. instead of handling a scrollbar directly.
  26030. @see ScrollBarListener
  26031. */
  26032. class JUCE_API ScrollBar : public Component,
  26033. public AsyncUpdater,
  26034. private Timer
  26035. {
  26036. public:
  26037. /** Creates a Scrollbar.
  26038. @param isVertical whether it should be a vertical or horizontal bar
  26039. @param buttonsAreVisible whether to show the up/down or left/right buttons
  26040. */
  26041. ScrollBar (bool isVertical,
  26042. bool buttonsAreVisible = true);
  26043. /** Destructor. */
  26044. ~ScrollBar();
  26045. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  26046. bool isVertical() const throw() { return vertical; }
  26047. /** Changes the scrollbar's direction.
  26048. You'll also need to resize the bar appropriately - this just changes its internal
  26049. layout.
  26050. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  26051. */
  26052. void setOrientation (bool shouldBeVertical);
  26053. /** Shows or hides the scrollbar's buttons. */
  26054. void setButtonVisibility (bool buttonsAreVisible);
  26055. /** Tells the scrollbar whether to make itself invisible when not needed.
  26056. The default behaviour is for a scrollbar to become invisible when the thumb
  26057. fills the whole of its range (i.e. when it can't be moved). Setting this
  26058. value to false forces the bar to always be visible.
  26059. @see autoHides()
  26060. */
  26061. void setAutoHide (bool shouldHideWhenFullRange);
  26062. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  26063. as its maximum range.
  26064. @see setAutoHide
  26065. */
  26066. bool autoHides() const throw();
  26067. /** Sets the minimum and maximum values that the bar will move between.
  26068. The bar's thumb will always be constrained so that the entire thumb lies
  26069. within this range.
  26070. @see setCurrentRange
  26071. */
  26072. void setRangeLimits (const Range<double>& newRangeLimit);
  26073. /** Sets the minimum and maximum values that the bar will move between.
  26074. The bar's thumb will always be constrained so that the entire thumb lies
  26075. within this range.
  26076. @see setCurrentRange
  26077. */
  26078. void setRangeLimits (double minimum, double maximum);
  26079. /** Returns the current limits on the thumb position.
  26080. @see setRangeLimits
  26081. */
  26082. const Range<double> getRangeLimit() const throw() { return totalRange; }
  26083. /** Returns the lower value that the thumb can be set to.
  26084. This is the value set by setRangeLimits().
  26085. */
  26086. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  26087. /** Returns the upper value that the thumb can be set to.
  26088. This is the value set by setRangeLimits().
  26089. */
  26090. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  26091. /** Changes the position of the scrollbar's 'thumb'.
  26092. If this method call actually changes the scrollbar's position, it will trigger an
  26093. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  26094. are registered.
  26095. @see getCurrentRange. setCurrentRangeStart
  26096. */
  26097. void setCurrentRange (const Range<double>& newRange);
  26098. /** Changes the position of the scrollbar's 'thumb'.
  26099. This sets both the position and size of the thumb - to just set the position without
  26100. changing the size, you can use setCurrentRangeStart().
  26101. If this method call actually changes the scrollbar's position, it will trigger an
  26102. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  26103. are registered.
  26104. @param newStart the top (or left) of the thumb, in the range
  26105. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  26106. value is beyond these limits, it will be clipped.
  26107. @param newSize the size of the thumb, such that
  26108. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  26109. size is beyond these limits, it will be clipped.
  26110. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  26111. */
  26112. void setCurrentRange (double newStart, double newSize);
  26113. /** Moves the bar's thumb position.
  26114. This will move the thumb position without changing the thumb size. Note
  26115. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  26116. If this method call actually changes the scrollbar's position, it will trigger an
  26117. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  26118. are registered.
  26119. @see setCurrentRange
  26120. */
  26121. void setCurrentRangeStart (double newStart);
  26122. /** Returns the current thumb range.
  26123. @see getCurrentRange, setCurrentRange
  26124. */
  26125. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  26126. /** Returns the position of the top of the thumb.
  26127. @see getCurrentRange, setCurrentRangeStart
  26128. */
  26129. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  26130. /** Returns the current size of the thumb.
  26131. @see getCurrentRange, setCurrentRange
  26132. */
  26133. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  26134. /** Sets the amount by which the up and down buttons will move the bar.
  26135. The value here is in terms of the total range, and is added or subtracted
  26136. from the thumb position when the user clicks an up/down (or left/right) button.
  26137. */
  26138. void setSingleStepSize (double newSingleStepSize);
  26139. /** Moves the scrollbar by a number of single-steps.
  26140. This will move the bar by a multiple of its single-step interval (as
  26141. specified using the setSingleStepSize() method).
  26142. A positive value here will move the bar down or to the right, a negative
  26143. value moves it up or to the left.
  26144. */
  26145. void moveScrollbarInSteps (int howManySteps);
  26146. /** Moves the scroll bar up or down in pages.
  26147. This will move the bar by a multiple of its current thumb size, effectively
  26148. doing a page-up or down.
  26149. A positive value here will move the bar down or to the right, a negative
  26150. value moves it up or to the left.
  26151. */
  26152. void moveScrollbarInPages (int howManyPages);
  26153. /** Scrolls to the top (or left).
  26154. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  26155. */
  26156. void scrollToTop();
  26157. /** Scrolls to the bottom (or right).
  26158. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  26159. */
  26160. void scrollToBottom();
  26161. /** Changes the delay before the up and down buttons autorepeat when they are held
  26162. down.
  26163. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  26164. @see Button::setRepeatSpeed
  26165. */
  26166. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  26167. int repeatDelayInMillisecs,
  26168. int minimumDelayInMillisecs = -1);
  26169. /** A set of colour IDs to use to change the colour of various aspects of the component.
  26170. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26171. methods.
  26172. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26173. */
  26174. enum ColourIds
  26175. {
  26176. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  26177. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  26178. 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. */
  26179. };
  26180. /** Registers a listener that will be called when the scrollbar is moved. */
  26181. void addListener (ScrollBarListener* listener);
  26182. /** Deregisters a previously-registered listener. */
  26183. void removeListener (ScrollBarListener* listener);
  26184. /** @internal */
  26185. bool keyPressed (const KeyPress& key);
  26186. /** @internal */
  26187. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26188. /** @internal */
  26189. void lookAndFeelChanged();
  26190. /** @internal */
  26191. void handleAsyncUpdate();
  26192. /** @internal */
  26193. void mouseDown (const MouseEvent& e);
  26194. /** @internal */
  26195. void mouseDrag (const MouseEvent& e);
  26196. /** @internal */
  26197. void mouseUp (const MouseEvent& e);
  26198. /** @internal */
  26199. void paint (Graphics& g);
  26200. /** @internal */
  26201. void resized();
  26202. juce_UseDebuggingNewOperator
  26203. private:
  26204. Range <double> totalRange, visibleRange;
  26205. double singleStepSize, dragStartRange;
  26206. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  26207. int dragStartMousePos, lastMousePos;
  26208. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  26209. bool vertical, isDraggingThumb, autohides;
  26210. class ScrollbarButton;
  26211. friend class ScopedPointer<ScrollbarButton>;
  26212. ScopedPointer<ScrollbarButton> upButton, downButton;
  26213. ListenerList <ScrollBarListener> listeners;
  26214. void updateThumbPosition();
  26215. void timerCallback();
  26216. ScrollBar (const ScrollBar&);
  26217. ScrollBar& operator= (const ScrollBar&);
  26218. };
  26219. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  26220. /*** End of inlined file: juce_ScrollBar.h ***/
  26221. /**
  26222. A Viewport is used to contain a larger child component, and allows the child
  26223. to be automatically scrolled around.
  26224. To use a Viewport, just create one and set the component that goes inside it
  26225. using the setViewedComponent() method. When the child component changes size,
  26226. the Viewport will adjust its scrollbars accordingly.
  26227. A subclass of the viewport can be created which will receive calls to its
  26228. visibleAreaChanged() method when the subcomponent changes position or size.
  26229. */
  26230. class JUCE_API Viewport : public Component,
  26231. private ComponentListener,
  26232. private ScrollBarListener
  26233. {
  26234. public:
  26235. /** Creates a Viewport.
  26236. The viewport is initially empty - use the setViewedComponent() method to
  26237. add a child component for it to manage.
  26238. */
  26239. explicit Viewport (const String& componentName = String::empty);
  26240. /** Destructor. */
  26241. ~Viewport();
  26242. /** Sets the component that this viewport will contain and scroll around.
  26243. This will add the given component to this Viewport and position it at
  26244. (0, 0).
  26245. (Don't add or remove any child components directly using the normal
  26246. Component::addChildComponent() methods).
  26247. @param newViewedComponent the component to add to this viewport (this pointer
  26248. may be null). The component passed in will be deleted
  26249. by the Viewport when it's no longer needed
  26250. @see getViewedComponent
  26251. */
  26252. void setViewedComponent (Component* newViewedComponent);
  26253. /** Returns the component that's currently being used inside the Viewport.
  26254. @see setViewedComponent
  26255. */
  26256. Component* getViewedComponent() const throw() { return contentComp; }
  26257. /** Changes the position of the viewed component.
  26258. The inner component will be moved so that the pixel at the top left of
  26259. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  26260. within the inner component.
  26261. This will update the scrollbars and might cause a call to visibleAreaChanged().
  26262. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  26263. */
  26264. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  26265. /** Changes the position of the viewed component.
  26266. The inner component will be moved so that the pixel at the top left of
  26267. the viewport will be the pixel at the specified coordinates within the
  26268. inner component.
  26269. This will update the scrollbars and might cause a call to visibleAreaChanged().
  26270. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  26271. */
  26272. void setViewPosition (const Point<int>& newPosition);
  26273. /** Changes the view position as a proportion of the distance it can move.
  26274. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  26275. visible area in the top-left, and (1, 1) would put it as far down and
  26276. to the right as it's possible to go whilst keeping the child component
  26277. on-screen.
  26278. */
  26279. void setViewPositionProportionately (double proportionX, double proportionY);
  26280. /** If the specified position is at the edges of the viewport, this method scrolls
  26281. the viewport to bring that position nearer to the centre.
  26282. Call this if you're dragging an object inside a viewport and want to make it scroll
  26283. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  26284. useful when auto-scrolling.
  26285. @param mouseX the x position, relative to the Viewport's top-left
  26286. @param mouseY the y position, relative to the Viewport's top-left
  26287. @param distanceFromEdge specifies how close to an edge the position needs to be
  26288. before the viewport should scroll in that direction
  26289. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  26290. to scroll by.
  26291. @returns true if the viewport was scrolled
  26292. */
  26293. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  26294. /** Returns the position within the child component of the top-left of its visible area.
  26295. */
  26296. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  26297. /** Returns the position within the child component of the top-left of its visible area.
  26298. @see getViewWidth, setViewPosition
  26299. */
  26300. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  26301. /** Returns the position within the child component of the top-left of its visible area.
  26302. @see getViewHeight, setViewPosition
  26303. */
  26304. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  26305. /** Returns the width of the visible area of the child component.
  26306. This may be less than the width of this Viewport if there's a vertical scrollbar
  26307. or if the child component is itself smaller.
  26308. */
  26309. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  26310. /** Returns the height of the visible area of the child component.
  26311. This may be less than the height of this Viewport if there's a horizontal scrollbar
  26312. or if the child component is itself smaller.
  26313. */
  26314. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  26315. /** Returns the width available within this component for the contents.
  26316. This will be the width of the viewport component minus the width of a
  26317. vertical scrollbar (if visible).
  26318. */
  26319. int getMaximumVisibleWidth() const;
  26320. /** Returns the height available within this component for the contents.
  26321. This will be the height of the viewport component minus the space taken up
  26322. by a horizontal scrollbar (if visible).
  26323. */
  26324. int getMaximumVisibleHeight() const;
  26325. /** Callback method that is called when the visible area changes.
  26326. This will be called when the visible area is moved either be scrolling or
  26327. by calls to setViewPosition(), etc.
  26328. */
  26329. virtual void visibleAreaChanged (int visibleX, int visibleY,
  26330. int visibleW, int visibleH);
  26331. /** Turns scrollbars on or off.
  26332. If set to false, the scrollbars won't ever appear. When true (the default)
  26333. they will appear only when needed.
  26334. */
  26335. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  26336. bool showHorizontalScrollbarIfNeeded);
  26337. /** True if the vertical scrollbar is enabled.
  26338. @see setScrollBarsShown
  26339. */
  26340. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  26341. /** True if the horizontal scrollbar is enabled.
  26342. @see setScrollBarsShown
  26343. */
  26344. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  26345. /** Changes the width of the scrollbars.
  26346. If this isn't specified, the default width from the LookAndFeel class will be used.
  26347. @see LookAndFeel::getDefaultScrollbarWidth
  26348. */
  26349. void setScrollBarThickness (int thickness);
  26350. /** Returns the thickness of the scrollbars.
  26351. @see setScrollBarThickness
  26352. */
  26353. int getScrollBarThickness() const;
  26354. /** Changes the distance that a single-step click on a scrollbar button
  26355. will move the viewport.
  26356. */
  26357. void setSingleStepSizes (int stepX, int stepY);
  26358. /** Shows or hides the buttons on any scrollbars that are used.
  26359. @see ScrollBar::setButtonVisibility
  26360. */
  26361. void setScrollBarButtonVisibility (bool buttonsVisible);
  26362. /** Returns a pointer to the scrollbar component being used.
  26363. Handy if you need to customise the bar somehow.
  26364. */
  26365. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  26366. /** Returns a pointer to the scrollbar component being used.
  26367. Handy if you need to customise the bar somehow.
  26368. */
  26369. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  26370. juce_UseDebuggingNewOperator
  26371. /** @internal */
  26372. void resized();
  26373. /** @internal */
  26374. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  26375. /** @internal */
  26376. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26377. /** @internal */
  26378. bool keyPressed (const KeyPress& key);
  26379. /** @internal */
  26380. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  26381. /** @internal */
  26382. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26383. private:
  26384. Component::SafePointer<Component> contentComp;
  26385. Rectangle<int> lastVisibleArea;
  26386. int scrollBarThickness;
  26387. int singleStepX, singleStepY;
  26388. bool showHScrollbar, showVScrollbar;
  26389. Component contentHolder;
  26390. ScrollBar verticalScrollBar;
  26391. ScrollBar horizontalScrollBar;
  26392. void updateVisibleArea();
  26393. Viewport (const Viewport&);
  26394. Viewport& operator= (const Viewport&);
  26395. };
  26396. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  26397. /*** End of inlined file: juce_Viewport.h ***/
  26398. /*** Start of inlined file: juce_PopupMenu.h ***/
  26399. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  26400. #define __JUCE_POPUPMENU_JUCEHEADER__
  26401. class PopupMenuCustomComponent;
  26402. /** Creates and displays a popup-menu.
  26403. To show a popup-menu, you create one of these, add some items to it, then
  26404. call its show() method, which returns the id of the item the user selects.
  26405. E.g. @code
  26406. void MyWidget::mouseDown (const MouseEvent& e)
  26407. {
  26408. PopupMenu m;
  26409. m.addItem (1, "item 1");
  26410. m.addItem (2, "item 2");
  26411. const int result = m.show();
  26412. if (result == 0)
  26413. {
  26414. // user dismissed the menu without picking anything
  26415. }
  26416. else if (result == 1)
  26417. {
  26418. // user picked item 1
  26419. }
  26420. else if (result == 2)
  26421. {
  26422. // user picked item 2
  26423. }
  26424. }
  26425. @endcode
  26426. Submenus are easy too: @code
  26427. void MyWidget::mouseDown (const MouseEvent& e)
  26428. {
  26429. PopupMenu subMenu;
  26430. subMenu.addItem (1, "item 1");
  26431. subMenu.addItem (2, "item 2");
  26432. PopupMenu mainMenu;
  26433. mainMenu.addItem (3, "item 3");
  26434. mainMenu.addSubMenu ("other choices", subMenu);
  26435. const int result = m.show();
  26436. ...etc
  26437. }
  26438. @endcode
  26439. */
  26440. class JUCE_API PopupMenu
  26441. {
  26442. public:
  26443. /** Creates an empty popup menu. */
  26444. PopupMenu();
  26445. /** Creates a copy of another menu. */
  26446. PopupMenu (const PopupMenu& other);
  26447. /** Destructor. */
  26448. ~PopupMenu();
  26449. /** Copies this menu from another one. */
  26450. PopupMenu& operator= (const PopupMenu& other);
  26451. /** Resets the menu, removing all its items. */
  26452. void clear();
  26453. /** Appends a new text item for this menu to show.
  26454. @param itemResultId the number that will be returned from the show() method
  26455. if the user picks this item. The value should never be
  26456. zero, because that's used to indicate that the user didn't
  26457. select anything.
  26458. @param itemText the text to show.
  26459. @param isActive if false, the item will be shown 'greyed-out' and can't be
  26460. picked
  26461. @param isTicked if true, the item will be shown with a tick next to it
  26462. @param iconToUse if this is non-zero, it should be an image that will be
  26463. displayed to the left of the item. This method will take its
  26464. own copy of the image passed-in, so there's no need to keep
  26465. it hanging around.
  26466. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  26467. */
  26468. void addItem (int itemResultId,
  26469. const String& itemText,
  26470. bool isActive = true,
  26471. bool isTicked = false,
  26472. const Image& iconToUse = Image());
  26473. /** Adds an item that represents one of the commands in a command manager object.
  26474. @param commandManager the manager to use to trigger the command and get information
  26475. about it
  26476. @param commandID the ID of the command
  26477. @param displayName if this is non-empty, then this string will be used instead of
  26478. the command's registered name
  26479. */
  26480. void addCommandItem (ApplicationCommandManager* commandManager,
  26481. int commandID,
  26482. const String& displayName = String::empty);
  26483. /** Appends a text item with a special colour.
  26484. This is the same as addItem(), but specifies a colour to use for the
  26485. text, which will override the default colours that are used by the
  26486. current look-and-feel. See addItem() for a description of the parameters.
  26487. */
  26488. void addColouredItem (int itemResultId,
  26489. const String& itemText,
  26490. const Colour& itemTextColour,
  26491. bool isActive = true,
  26492. bool isTicked = false,
  26493. const Image& iconToUse = Image());
  26494. /** Appends a custom menu item.
  26495. This will add a user-defined component to use as a menu item. The component
  26496. passed in will be deleted by this menu when it's no longer needed.
  26497. @see PopupMenuCustomComponent
  26498. */
  26499. void addCustomItem (int itemResultId, PopupMenuCustomComponent* customComponent);
  26500. /** Appends a custom menu item that can't be used to trigger a result.
  26501. This will add a user-defined component to use as a menu item. Unlike the
  26502. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  26503. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  26504. delete the component when it's finished, so it's the caller's responsibility
  26505. to manage the component that is passed-in.
  26506. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  26507. detection of a mouse-click on your component, and use that to trigger the
  26508. menu ID specified in itemResultId. If this is false, the menu item can't
  26509. be triggered, so itemResultId is not used.
  26510. @see PopupMenuCustomComponent
  26511. */
  26512. void addCustomItem (int itemResultId,
  26513. Component* customComponent,
  26514. int idealWidth, int idealHeight,
  26515. bool triggerMenuItemAutomaticallyWhenClicked);
  26516. /** Appends a sub-menu.
  26517. If the menu that's passed in is empty, it will appear as an inactive item.
  26518. */
  26519. void addSubMenu (const String& subMenuName,
  26520. const PopupMenu& subMenu,
  26521. bool isActive = true,
  26522. const Image& iconToUse = Image(),
  26523. bool isTicked = false);
  26524. /** Appends a separator to the menu, to help break it up into sections.
  26525. The menu class is smart enough not to display separators at the top or bottom
  26526. of the menu, and it will replace mutliple adjacent separators with a single
  26527. one, so your code can be quite free and easy about adding these, and it'll
  26528. always look ok.
  26529. */
  26530. void addSeparator();
  26531. /** Adds a non-clickable text item to the menu.
  26532. This is a bold-font items which can be used as a header to separate the items
  26533. into named groups.
  26534. */
  26535. void addSectionHeader (const String& title);
  26536. /** Returns the number of items that the menu currently contains.
  26537. (This doesn't count separators).
  26538. */
  26539. int getNumItems() const throw();
  26540. /** Returns true if the menu contains a command item that triggers the given command. */
  26541. bool containsCommandItem (int commandID) const;
  26542. /** Returns true if the menu contains any items that can be used. */
  26543. bool containsAnyActiveItems() const throw();
  26544. /** Displays the menu and waits for the user to pick something.
  26545. This will display the menu modally, and return the ID of the item that the
  26546. user picks. If they click somewhere off the menu to get rid of it without
  26547. choosing anything, this will return 0.
  26548. The current location of the mouse will be used as the position to show the
  26549. menu - to explicitly set the menu's position, use showAt() instead. Depending
  26550. on where this point is on the screen, the menu will appear above, below or
  26551. to the side of the point.
  26552. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  26553. then when the menu first appears, it will make sure
  26554. that this item is visible. So if the menu has too many
  26555. items to fit on the screen, it will be scrolled to a
  26556. position where this item is visible.
  26557. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  26558. than this if some items are too long to fit.
  26559. @param maximumNumColumns if there are too many items to fit on-screen in a single
  26560. vertical column, the menu may be laid out as a series of
  26561. columns - this is the maximum number allowed. To use the
  26562. default value for this (probably about 7), you can pass
  26563. in zero.
  26564. @param standardItemHeight if this is non-zero, it will be used as the standard
  26565. height for menu items (apart from custom items)
  26566. @param callback if this is non-zero, the menu will be launched asynchronously,
  26567. returning immediately, and the callback will receive a
  26568. call when the menu is either dismissed or has an item
  26569. selected. This object will be owned and deleted by the
  26570. system, so make sure that it works safely and that any
  26571. pointers that it uses are safely within scope.
  26572. @see showAt
  26573. */
  26574. int show (int itemIdThatMustBeVisible = 0,
  26575. int minimumWidth = 0,
  26576. int maximumNumColumns = 0,
  26577. int standardItemHeight = 0,
  26578. ModalComponentManager::Callback* callback = 0);
  26579. /** Displays the menu at a specific location.
  26580. This is the same as show(), but uses a specific location (in global screen
  26581. co-ordinates) rather than the current mouse position.
  26582. Note that the co-ordinates don't specify the top-left of the menu - they
  26583. indicate a point of interest, and the menu will position itself nearby to
  26584. this point, trying to keep it fully on-screen.
  26585. @see show()
  26586. */
  26587. int showAt (int screenX,
  26588. int screenY,
  26589. int itemIdThatMustBeVisible = 0,
  26590. int minimumWidth = 0,
  26591. int maximumNumColumns = 0,
  26592. int standardItemHeight = 0,
  26593. ModalComponentManager::Callback* callback = 0);
  26594. /** Displays the menu as if it's attached to a component such as a button.
  26595. This is similar to showAt(), but will position it next to the given component, e.g.
  26596. so that the menu's edge is aligned with that of the component. This is intended for
  26597. things like buttons that trigger a pop-up menu.
  26598. */
  26599. int showAt (Component* componentToAttachTo,
  26600. int itemIdThatMustBeVisible = 0,
  26601. int minimumWidth = 0,
  26602. int maximumNumColumns = 0,
  26603. int standardItemHeight = 0,
  26604. ModalComponentManager::Callback* callback = 0);
  26605. /** Closes any menus that are currently open.
  26606. This might be useful if you have a situation where your window is being closed
  26607. by some means other than a user action, and you'd like to make sure that menus
  26608. aren't left hanging around.
  26609. */
  26610. static void JUCE_CALLTYPE dismissAllActiveMenus();
  26611. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  26612. This can be called before show() if you need a customised menu. Be careful
  26613. not to delete the LookAndFeel object before the menu has been deleted.
  26614. */
  26615. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  26616. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  26617. These constants can be used either via the LookAndFeel::setColour()
  26618. method for the look and feel that is set for this menu with setLookAndFeel()
  26619. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  26620. */
  26621. enum ColourIds
  26622. {
  26623. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  26624. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  26625. colour is specified when the item is added). */
  26626. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  26627. addSectionHeader() method). */
  26628. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  26629. highlighted menu item. */
  26630. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  26631. highlighted item. */
  26632. };
  26633. /**
  26634. Allows you to iterate through the items in a pop-up menu, and examine
  26635. their properties.
  26636. To use this, just create one and repeatedly call its next() method. When this
  26637. returns true, all the member variables of the iterator are filled-out with
  26638. information describing the menu item. When it returns false, the end of the
  26639. list has been reached.
  26640. */
  26641. class JUCE_API MenuItemIterator
  26642. {
  26643. public:
  26644. /** Creates an iterator that will scan through the items in the specified
  26645. menu.
  26646. Be careful not to add any items to a menu while it is being iterated,
  26647. or things could get out of step.
  26648. */
  26649. MenuItemIterator (const PopupMenu& menu);
  26650. /** Destructor. */
  26651. ~MenuItemIterator();
  26652. /** Returns true if there is another item, and sets up all this object's
  26653. member variables to reflect that item's properties.
  26654. */
  26655. bool next();
  26656. String itemName;
  26657. const PopupMenu* subMenu;
  26658. int itemId;
  26659. bool isSeparator;
  26660. bool isTicked;
  26661. bool isEnabled;
  26662. bool isCustomComponent;
  26663. bool isSectionHeader;
  26664. const Colour* customColour;
  26665. Image customImage;
  26666. ApplicationCommandManager* commandManager;
  26667. juce_UseDebuggingNewOperator
  26668. private:
  26669. const PopupMenu& menu;
  26670. int index;
  26671. MenuItemIterator (const MenuItemIterator&);
  26672. MenuItemIterator& operator= (const MenuItemIterator&);
  26673. };
  26674. juce_UseDebuggingNewOperator
  26675. private:
  26676. class Item;
  26677. class ItemComponent;
  26678. class Window;
  26679. friend class MenuItemIterator;
  26680. friend class ItemComponent;
  26681. friend class Window;
  26682. friend class PopupMenuCustomComponent;
  26683. friend class MenuBarComponent;
  26684. friend class OwnedArray <Item>;
  26685. friend class ScopedPointer <Window>;
  26686. OwnedArray <Item> items;
  26687. LookAndFeel* lookAndFeel;
  26688. bool separatorPending;
  26689. void addSeparatorIfPending();
  26690. int showMenu (const Rectangle<int>& target,
  26691. int itemIdThatMustBeVisible,
  26692. int minimumWidth,
  26693. int maximumNumColumns,
  26694. int standardItemHeight,
  26695. bool alignToRectangle,
  26696. Component* componentAttachedTo,
  26697. ModalComponentManager::Callback* callback);
  26698. };
  26699. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  26700. /*** End of inlined file: juce_PopupMenu.h ***/
  26701. /*** Start of inlined file: juce_TextInputTarget.h ***/
  26702. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26703. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26704. /** An abstract base class that is implemented by components that wish to be used
  26705. as text editors.
  26706. This class allows different types of text editor component to provide a uniform
  26707. interface, which can be used by things like OS-specific input methods, on-screen
  26708. keyboards, etc.
  26709. */
  26710. class JUCE_API TextInputTarget
  26711. {
  26712. public:
  26713. /** */
  26714. TextInputTarget() {}
  26715. /** Destructor. */
  26716. virtual ~TextInputTarget() {}
  26717. /** Returns true if this input target is currently accepting input.
  26718. For example, a text editor might return false if it's in read-only mode.
  26719. */
  26720. virtual bool isTextInputActive() const = 0;
  26721. /** Returns the extents of the selected text region, or an empty range if
  26722. nothing is selected,
  26723. */
  26724. virtual const Range<int> getHighlightedRegion() const = 0;
  26725. /** Sets the currently-selected text region.
  26726. */
  26727. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  26728. /** Returns a specified sub-section of the text.
  26729. */
  26730. virtual const String getTextInRange (const Range<int>& range) const = 0;
  26731. /** Inserts some text, overwriting the selected text region, if there is one. */
  26732. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  26733. };
  26734. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26735. /*** End of inlined file: juce_TextInputTarget.h ***/
  26736. class TextEditor;
  26737. /**
  26738. Receives callbacks from a TextEditor component when it changes.
  26739. @see TextEditor::addListener
  26740. */
  26741. class JUCE_API TextEditorListener
  26742. {
  26743. public:
  26744. /** Destructor. */
  26745. virtual ~TextEditorListener() {}
  26746. /** Called when the user changes the text in some way. */
  26747. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  26748. /** Called when the user presses the return key. */
  26749. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  26750. /** Called when the user presses the escape key. */
  26751. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  26752. /** Called when the text editor loses focus. */
  26753. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  26754. };
  26755. /**
  26756. A component containing text that can be edited.
  26757. A TextEditor can either be in single- or multi-line mode, and supports mixed
  26758. fonts and colours.
  26759. @see TextEditorListener, Label
  26760. */
  26761. class JUCE_API TextEditor : public Component,
  26762. public TextInputTarget,
  26763. public SettableTooltipClient
  26764. {
  26765. public:
  26766. /** Creates a new, empty text editor.
  26767. @param componentName the name to pass to the component for it to use as its name
  26768. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26769. for all characters that are drawn on screen - e.g. to create
  26770. a password-style textbox containing circular blobs instead of text,
  26771. you could set this value to 0x25cf, which is the unicode character
  26772. for a black splodge (not all fonts include this, though), or 0x2022,
  26773. which is a bullet (probably the best choice for linux).
  26774. */
  26775. explicit TextEditor (const String& componentName = String::empty,
  26776. juce_wchar passwordCharacter = 0);
  26777. /** Destructor. */
  26778. virtual ~TextEditor();
  26779. /** Puts the editor into either multi- or single-line mode.
  26780. By default, the editor will be in single-line mode, so use this if you need a multi-line
  26781. editor.
  26782. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  26783. on if you want a multi-line editor with line-breaks.
  26784. @see isMultiLine, setReturnKeyStartsNewLine
  26785. */
  26786. void setMultiLine (bool shouldBeMultiLine,
  26787. bool shouldWordWrap = true);
  26788. /** Returns true if the editor is in multi-line mode.
  26789. */
  26790. bool isMultiLine() const;
  26791. /** Changes the behaviour of the return key.
  26792. If set to true, the return key will insert a new-line into the text; if false
  26793. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  26794. method. By default this is set to false, and when true it will only insert
  26795. new-lines when in multi-line mode (see setMultiLine()).
  26796. */
  26797. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  26798. /** Returns the value set by setReturnKeyStartsNewLine().
  26799. See setReturnKeyStartsNewLine() for more info.
  26800. */
  26801. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  26802. /** Indicates whether the tab key should be accepted and used to input a tab character,
  26803. or whether it gets ignored.
  26804. By default the tab key is ignored, so that it can be used to switch keyboard focus
  26805. between components.
  26806. */
  26807. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  26808. /** Returns true if the tab key is being used for input.
  26809. @see setTabKeyUsedAsCharacter
  26810. */
  26811. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  26812. /** Changes the editor to read-only mode.
  26813. By default, the text editor is not read-only. If you're making it read-only, you
  26814. might also want to call setCaretVisible (false) to get rid of the caret.
  26815. The text can still be highlighted and copied when in read-only mode.
  26816. @see isReadOnly, setCaretVisible
  26817. */
  26818. void setReadOnly (bool shouldBeReadOnly);
  26819. /** Returns true if the editor is in read-only mode.
  26820. */
  26821. bool isReadOnly() const;
  26822. /** Makes the caret visible or invisible.
  26823. By default the caret is visible.
  26824. @see setCaretColour, setCaretPosition
  26825. */
  26826. void setCaretVisible (bool shouldBeVisible);
  26827. /** Returns true if the caret is enabled.
  26828. @see setCaretVisible
  26829. */
  26830. bool isCaretVisible() const { return caretVisible; }
  26831. /** Enables/disables a vertical scrollbar.
  26832. (This only applies when in multi-line mode). When the text gets too long to fit
  26833. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  26834. this is enabled, the scrollbar will be hidden unless it's needed.
  26835. By default the scrollbar is enabled.
  26836. */
  26837. void setScrollbarsShown (bool shouldBeEnabled);
  26838. /** Returns true if scrollbars are enabled.
  26839. @see setScrollbarsShown
  26840. */
  26841. bool areScrollbarsShown() const { return scrollbarVisible; }
  26842. /** Changes the password character used to disguise the text.
  26843. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26844. for all characters that are drawn on screen - e.g. to create
  26845. a password-style textbox containing circular blobs instead of text,
  26846. you could set this value to 0x25cf, which is the unicode character
  26847. for a black splodge (not all fonts include this, though), or 0x2022,
  26848. which is a bullet (probably the best choice for linux).
  26849. */
  26850. void setPasswordCharacter (juce_wchar passwordCharacter);
  26851. /** Returns the current password character.
  26852. @see setPasswordCharacter
  26853. */
  26854. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  26855. /** Allows a right-click menu to appear for the editor.
  26856. (This defaults to being enabled).
  26857. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  26858. of options such as cut/copy/paste, undo/redo, etc.
  26859. */
  26860. void setPopupMenuEnabled (bool menuEnabled);
  26861. /** Returns true if the right-click menu is enabled.
  26862. @see setPopupMenuEnabled
  26863. */
  26864. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  26865. /** Returns true if a popup-menu is currently being displayed.
  26866. */
  26867. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  26868. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  26869. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26870. methods.
  26871. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26872. */
  26873. enum ColourIds
  26874. {
  26875. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  26876. transparent if necessary. */
  26877. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  26878. that because the editor can contain multiple colours, calling this
  26879. method won't change the colour of existing text - to do that, call
  26880. applyFontToAllText() after calling this method.*/
  26881. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  26882. the text - this can be transparent if you don't want to show any
  26883. highlighting.*/
  26884. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  26885. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  26886. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  26887. the edge of the component. */
  26888. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  26889. the edge of the component when it has focus. */
  26890. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  26891. around the edge of the editor. */
  26892. };
  26893. /** Sets the font to use for newly added text.
  26894. This will change the font that will be used next time any text is added or entered
  26895. into the editor. It won't change the font of any existing text - to do that, use
  26896. applyFontToAllText() instead.
  26897. @see applyFontToAllText
  26898. */
  26899. void setFont (const Font& newFont);
  26900. /** Applies a font to all the text in the editor.
  26901. This will also set the current font to use for any new text that's added.
  26902. @see setFont
  26903. */
  26904. void applyFontToAllText (const Font& newFont);
  26905. /** Returns the font that's currently being used for new text.
  26906. @see setFont
  26907. */
  26908. const Font getFont() const;
  26909. /** If set to true, focusing on the editor will highlight all its text.
  26910. (Set to false by default).
  26911. This is useful for boxes where you expect the user to re-enter all the
  26912. text when they focus on the component, rather than editing what's already there.
  26913. */
  26914. void setSelectAllWhenFocused (bool b);
  26915. /** Sets limits on the characters that can be entered.
  26916. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  26917. limit is set
  26918. @param allowedCharacters if this is non-empty, then only characters that occur in
  26919. this string are allowed to be entered into the editor.
  26920. */
  26921. void setInputRestrictions (int maxTextLength,
  26922. const String& allowedCharacters = String::empty);
  26923. /** When the text editor is empty, it can be set to display a message.
  26924. This is handy for things like telling the user what to type in the box - the
  26925. string is only displayed, it's not taken to actually be the contents of
  26926. the editor.
  26927. */
  26928. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  26929. /** Changes the size of the scrollbars that are used.
  26930. Handy if you need smaller scrollbars for a small text box.
  26931. */
  26932. void setScrollBarThickness (int newThicknessPixels);
  26933. /** Shows or hides the buttons on any scrollbars that are used.
  26934. @see ScrollBar::setButtonVisibility
  26935. */
  26936. void setScrollBarButtonVisibility (bool buttonsVisible);
  26937. /** Registers a listener to be told when things happen to the text.
  26938. @see removeListener
  26939. */
  26940. void addListener (TextEditorListener* newListener);
  26941. /** Deregisters a listener.
  26942. @see addListener
  26943. */
  26944. void removeListener (TextEditorListener* listenerToRemove);
  26945. /** Returns the entire contents of the editor. */
  26946. const String getText() const;
  26947. /** Returns a section of the contents of the editor. */
  26948. const String getTextInRange (const Range<int>& textRange) const;
  26949. /** Returns true if there are no characters in the editor.
  26950. This is more efficient than calling getText().isEmpty().
  26951. */
  26952. bool isEmpty() const;
  26953. /** Sets the entire content of the editor.
  26954. This will clear the editor and insert the given text (using the current text colour
  26955. and font). You can set the current text colour using
  26956. @code setColour (TextEditor::textColourId, ...);
  26957. @endcode
  26958. @param newText the text to add
  26959. @param sendTextChangeMessage if true, this will cause a change message to
  26960. be sent to all the listeners.
  26961. @see insertText
  26962. */
  26963. void setText (const String& newText,
  26964. bool sendTextChangeMessage = true);
  26965. /** Returns a Value object that can be used to get or set the text.
  26966. Bear in mind that this operate quite slowly if your text box contains large
  26967. amounts of text, as it needs to dynamically build the string that's involved. It's
  26968. best used for small text boxes.
  26969. */
  26970. Value& getTextValue();
  26971. /** Inserts some text at the current cursor position.
  26972. If a section of the text is highlighted, it will be replaced by
  26973. this string, otherwise it will be inserted.
  26974. To delete a section of text, you can use setHighlightedRegion() to
  26975. highlight it, and call insertTextAtCursor (String::empty).
  26976. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  26977. */
  26978. void insertTextAtCaret (const String& textToInsert);
  26979. /** Deletes all the text from the editor. */
  26980. void clear();
  26981. /** Deletes the currently selected region, and puts it on the clipboard.
  26982. @see copy, paste, SystemClipboard
  26983. */
  26984. void cut();
  26985. /** Copies any currently selected region to the clipboard.
  26986. @see cut, paste, SystemClipboard
  26987. */
  26988. void copy();
  26989. /** Pastes the contents of the clipboard into the editor at the cursor position.
  26990. @see cut, copy, SystemClipboard
  26991. */
  26992. void paste();
  26993. /** Moves the caret to be in front of a given character.
  26994. @see getCaretPosition
  26995. */
  26996. void setCaretPosition (int newIndex);
  26997. /** Returns the current index of the caret.
  26998. @see setCaretPosition
  26999. */
  27000. int getCaretPosition() const;
  27001. /** Attempts to scroll the text editor so that the caret ends up at
  27002. a specified position.
  27003. This won't affect the caret's position within the text, it tries to scroll
  27004. the entire editor vertically and horizontally so that the caret is sitting
  27005. at the given position (relative to the top-left of this component).
  27006. Depending on the amount of text available, it might not be possible to
  27007. scroll far enough for the caret to reach this exact position, but it
  27008. will go as far as it can in that direction.
  27009. */
  27010. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  27011. /** Get the graphical position of the caret.
  27012. The rectangle returned is relative to the component's top-left corner.
  27013. @see scrollEditorToPositionCaret
  27014. */
  27015. const Rectangle<int> getCaretRectangle();
  27016. /** Selects a section of the text. */
  27017. void setHighlightedRegion (const Range<int>& newSelection);
  27018. /** Returns the range of characters that are selected.
  27019. If nothing is selected, this will return an empty range.
  27020. @see setHighlightedRegion
  27021. */
  27022. const Range<int> getHighlightedRegion() const { return selection; }
  27023. /** Returns the section of text that is currently selected. */
  27024. const String getHighlightedText() const;
  27025. /** Finds the index of the character at a given position.
  27026. The co-ordinates are relative to the component's top-left.
  27027. */
  27028. int getTextIndexAt (int x, int y);
  27029. /** Counts the number of characters in the text.
  27030. This is quicker than getting the text as a string if you just need to know
  27031. the length.
  27032. */
  27033. int getTotalNumChars() const;
  27034. /** Returns the total width of the text, as it is currently laid-out.
  27035. This may be larger than the size of the TextEditor, and can change when
  27036. the TextEditor is resized or the text changes.
  27037. */
  27038. int getTextWidth() const;
  27039. /** Returns the maximum height of the text, as it is currently laid-out.
  27040. This may be larger than the size of the TextEditor, and can change when
  27041. the TextEditor is resized or the text changes.
  27042. */
  27043. int getTextHeight() const;
  27044. /** Changes the size of the gap at the top and left-edge of the editor.
  27045. By default there's a gap of 4 pixels.
  27046. */
  27047. void setIndents (int newLeftIndent, int newTopIndent);
  27048. /** Changes the size of border left around the edge of the component.
  27049. @see getBorder
  27050. */
  27051. void setBorder (const BorderSize& border);
  27052. /** Returns the size of border around the edge of the component.
  27053. @see setBorder
  27054. */
  27055. const BorderSize getBorder() const;
  27056. /** Used to disable the auto-scrolling which keeps the cursor visible.
  27057. If true (the default), the editor will scroll when the cursor moves offscreen. If
  27058. set to false, it won't.
  27059. */
  27060. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  27061. /** @internal */
  27062. void paint (Graphics& g);
  27063. /** @internal */
  27064. void paintOverChildren (Graphics& g);
  27065. /** @internal */
  27066. void mouseDown (const MouseEvent& e);
  27067. /** @internal */
  27068. void mouseUp (const MouseEvent& e);
  27069. /** @internal */
  27070. void mouseDrag (const MouseEvent& e);
  27071. /** @internal */
  27072. void mouseDoubleClick (const MouseEvent& e);
  27073. /** @internal */
  27074. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  27075. /** @internal */
  27076. bool keyPressed (const KeyPress& key);
  27077. /** @internal */
  27078. bool keyStateChanged (bool isKeyDown);
  27079. /** @internal */
  27080. void focusGained (FocusChangeType cause);
  27081. /** @internal */
  27082. void focusLost (FocusChangeType cause);
  27083. /** @internal */
  27084. void resized();
  27085. /** @internal */
  27086. void enablementChanged();
  27087. /** @internal */
  27088. void colourChanged();
  27089. /** @internal */
  27090. bool isTextInputActive() const;
  27091. /** This adds the items to the popup menu.
  27092. By default it adds the cut/copy/paste items, but you can override this if
  27093. you need to replace these with your own items.
  27094. If you want to add your own items to the existing ones, you can override this,
  27095. call the base class's addPopupMenuItems() method, then append your own items.
  27096. When the menu has been shown, performPopupMenuAction() will be called to
  27097. perform the item that the user has chosen.
  27098. The default menu items will be added using item IDs in the range
  27099. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  27100. menu IDs.
  27101. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  27102. a pointer to the info about it, or may be null if the menu is being triggered
  27103. by some other means.
  27104. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  27105. */
  27106. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  27107. const MouseEvent* mouseClickEvent);
  27108. /** This is called to perform one of the items that was shown on the popup menu.
  27109. If you've overridden addPopupMenuItems(), you should also override this
  27110. to perform the actions that you've added.
  27111. If you've overridden addPopupMenuItems() but have still left the default items
  27112. on the menu, remember to call the superclass's performPopupMenuAction()
  27113. so that it can perform the default actions if that's what the user clicked on.
  27114. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  27115. */
  27116. virtual void performPopupMenuAction (int menuItemID);
  27117. juce_UseDebuggingNewOperator
  27118. protected:
  27119. /** Scrolls the minimum distance needed to get the caret into view. */
  27120. void scrollToMakeSureCursorIsVisible();
  27121. /** @internal */
  27122. void moveCaret (int newCaretPos);
  27123. /** @internal */
  27124. void moveCursorTo (int newPosition, bool isSelecting);
  27125. /** Used internally to dispatch a text-change message. */
  27126. void textChanged();
  27127. /** Begins a new transaction in the UndoManager.
  27128. */
  27129. void newTransaction();
  27130. /** Used internally to trigger an undo or redo. */
  27131. void doUndoRedo (bool isRedo);
  27132. /** Can be overridden to intercept return key presses directly */
  27133. virtual void returnPressed();
  27134. /** Can be overridden to intercept escape key presses directly */
  27135. virtual void escapePressed();
  27136. /** @internal */
  27137. void handleCommandMessage (int commandId);
  27138. private:
  27139. class Iterator;
  27140. class UniformTextSection;
  27141. class TextHolderComponent;
  27142. class InsertAction;
  27143. class RemoveAction;
  27144. friend class InsertAction;
  27145. friend class RemoveAction;
  27146. ScopedPointer <Viewport> viewport;
  27147. TextHolderComponent* textHolder;
  27148. BorderSize borderSize;
  27149. bool readOnly : 1;
  27150. bool multiline : 1;
  27151. bool wordWrap : 1;
  27152. bool returnKeyStartsNewLine : 1;
  27153. bool caretVisible : 1;
  27154. bool popupMenuEnabled : 1;
  27155. bool selectAllTextWhenFocused : 1;
  27156. bool scrollbarVisible : 1;
  27157. bool wasFocused : 1;
  27158. bool caretFlashState : 1;
  27159. bool keepCursorOnScreen : 1;
  27160. bool tabKeyUsed : 1;
  27161. bool menuActive : 1;
  27162. bool valueTextNeedsUpdating : 1;
  27163. UndoManager undoManager;
  27164. float cursorX, cursorY, cursorHeight;
  27165. int maxTextLength;
  27166. Range<int> selection;
  27167. int leftIndent, topIndent;
  27168. unsigned int lastTransactionTime;
  27169. Font currentFont;
  27170. mutable int totalNumChars;
  27171. int caretPosition;
  27172. Array <UniformTextSection*> sections;
  27173. String textToShowWhenEmpty;
  27174. Colour colourForTextWhenEmpty;
  27175. juce_wchar passwordCharacter;
  27176. Value textValue;
  27177. enum
  27178. {
  27179. notDragging,
  27180. draggingSelectionStart,
  27181. draggingSelectionEnd
  27182. } dragType;
  27183. String allowedCharacters;
  27184. ListenerList <TextEditorListener> listeners;
  27185. void coalesceSimilarSections();
  27186. void splitSection (int sectionIndex, int charToSplitAt);
  27187. void clearInternal (UndoManager* um);
  27188. void insert (const String& text, int insertIndex, const Font& font,
  27189. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  27190. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  27191. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  27192. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  27193. void updateCaretPosition();
  27194. void textWasChangedByValue();
  27195. int indexAtPosition (float x, float y);
  27196. int findWordBreakAfter (int position) const;
  27197. int findWordBreakBefore (int position) const;
  27198. friend class TextHolderComponent;
  27199. friend class TextEditorViewport;
  27200. void drawContent (Graphics& g);
  27201. void updateTextHolderSize();
  27202. float getWordWrapWidth() const;
  27203. void timerCallbackInt();
  27204. void repaintCaret();
  27205. void repaintText (const Range<int>& range);
  27206. UndoManager* getUndoManager() throw();
  27207. TextEditor (const TextEditor&);
  27208. TextEditor& operator= (const TextEditor&);
  27209. };
  27210. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  27211. /*** End of inlined file: juce_TextEditor.h ***/
  27212. class Label;
  27213. /**
  27214. A class for receiving events from a Label.
  27215. You can register a LabelListener with a Label using the Label::addListener()
  27216. method, and it will be called when the text of the label changes, either because
  27217. of a call to Label::setText() or by the user editing the text (if the label is
  27218. editable).
  27219. @see Label::addListener, Label::removeListener
  27220. */
  27221. class JUCE_API LabelListener
  27222. {
  27223. public:
  27224. /** Destructor. */
  27225. virtual ~LabelListener() {}
  27226. /** Called when a Label's text has changed.
  27227. */
  27228. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  27229. };
  27230. /**
  27231. A component that displays a text string, and can optionally become a text
  27232. editor when clicked.
  27233. */
  27234. class JUCE_API Label : public Component,
  27235. public SettableTooltipClient,
  27236. protected TextEditorListener,
  27237. private ComponentListener,
  27238. private Value::Listener
  27239. {
  27240. public:
  27241. /** Creates a Label.
  27242. @param componentName the name to give the component
  27243. @param labelText the text to show in the label
  27244. */
  27245. Label (const String& componentName = String::empty,
  27246. const String& labelText = String::empty);
  27247. /** Destructor. */
  27248. ~Label();
  27249. /** Changes the label text.
  27250. If broadcastChangeMessage is true and the new text is different to the current
  27251. text, then the class will broadcast a change message to any LabelListeners that
  27252. are registered.
  27253. */
  27254. void setText (const String& newText,
  27255. bool broadcastChangeMessage);
  27256. /** Returns the label's current text.
  27257. @param returnActiveEditorContents if this is true and the label is currently
  27258. being edited, then this method will return the
  27259. text as it's being shown in the editor. If false,
  27260. then the value returned here won't be updated until
  27261. the user has finished typing and pressed the return
  27262. key.
  27263. */
  27264. const String getText (bool returnActiveEditorContents = false) const throw();
  27265. /** Returns the text content as a Value object.
  27266. You can call Value::referTo() on this object to make the label read and control
  27267. a Value object that you supply.
  27268. */
  27269. Value& getTextValue() { return textValue; }
  27270. /** Changes the font to use to draw the text.
  27271. @see getFont
  27272. */
  27273. void setFont (const Font& newFont) throw();
  27274. /** Returns the font currently being used.
  27275. @see setFont
  27276. */
  27277. const Font& getFont() const throw();
  27278. /** A set of colour IDs to use to change the colour of various aspects of the label.
  27279. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27280. methods.
  27281. Note that you can also use the constants from TextEditor::ColourIds to change the
  27282. colour of the text editor that is opened when a label is editable.
  27283. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27284. */
  27285. enum ColourIds
  27286. {
  27287. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  27288. textColourId = 0x1000281, /**< The colour for the text. */
  27289. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  27290. Leave this transparent to not have an outline. */
  27291. };
  27292. /** Sets the style of justification to be used for positioning the text.
  27293. (The default is Justification::centredLeft)
  27294. */
  27295. void setJustificationType (const Justification& justification) throw();
  27296. /** Returns the type of justification, as set in setJustificationType(). */
  27297. const Justification getJustificationType() const throw() { return justification; }
  27298. /** Changes the gap that is left between the edge of the component and the text.
  27299. By default there's a small gap left at the sides of the component to allow for
  27300. the drawing of the border, but you can change this if necessary.
  27301. */
  27302. void setBorderSize (int horizontalBorder, int verticalBorder);
  27303. /** Returns the size of the horizontal gap being left around the text.
  27304. */
  27305. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  27306. /** Returns the size of the vertical gap being left around the text.
  27307. */
  27308. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  27309. /** Makes this label "stick to" another component.
  27310. This will cause the label to follow another component around, staying
  27311. either to its left or above it.
  27312. @param owner the component to follow
  27313. @param onLeft if true, the label will stay on the left of its component; if
  27314. false, it will stay above it.
  27315. */
  27316. void attachToComponent (Component* owner, bool onLeft);
  27317. /** If this label has been attached to another component using attachToComponent, this
  27318. returns the other component.
  27319. Returns 0 if the label is not attached.
  27320. */
  27321. Component* getAttachedComponent() const;
  27322. /** If the label is attached to the left of another component, this returns true.
  27323. Returns false if the label is above the other component. This is only relevent if
  27324. attachToComponent() has been called.
  27325. */
  27326. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  27327. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  27328. using ellipsis.
  27329. @see Graphics::drawFittedText
  27330. */
  27331. void setMinimumHorizontalScale (float newScale);
  27332. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  27333. /** Registers a listener that will be called when the label's text changes. */
  27334. void addListener (LabelListener* listener) throw();
  27335. /** Deregisters a previously-registered listener. */
  27336. void removeListener (LabelListener* listener) throw();
  27337. /** Makes the label turn into a TextEditor when clicked.
  27338. By default this is turned off.
  27339. If turned on, then single- or double-clicking will turn the label into
  27340. an editor. If the user then changes the text, then the ChangeBroadcaster
  27341. base class will be used to send change messages to any listeners that
  27342. have registered.
  27343. If the user changes the text, the textWasEdited() method will be called
  27344. afterwards, and subclasses can override this if they need to do anything
  27345. special.
  27346. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  27347. @param editOnDoubleClick if true, a double-click is needed to start editing
  27348. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  27349. edited will discard any changes; if false, then this will
  27350. commit the changes.
  27351. @see showEditor, setEditorColours, TextEditor
  27352. */
  27353. void setEditable (bool editOnSingleClick,
  27354. bool editOnDoubleClick = false,
  27355. bool lossOfFocusDiscardsChanges = false) throw();
  27356. /** Returns true if this option was set using setEditable(). */
  27357. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  27358. /** Returns true if this option was set using setEditable(). */
  27359. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  27360. /** Returns true if this option has been set in a call to setEditable(). */
  27361. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  27362. /** Returns true if the user can edit this label's text. */
  27363. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  27364. /** Makes the editor appear as if the label had been clicked by the user.
  27365. @see textWasEdited, setEditable
  27366. */
  27367. void showEditor();
  27368. /** Hides the editor if it was being shown.
  27369. @param discardCurrentEditorContents if true, the label's text will be
  27370. reset to whatever it was before the editor
  27371. was shown; if false, the current contents of the
  27372. editor will be used to set the label's text
  27373. before it is hidden.
  27374. */
  27375. void hideEditor (bool discardCurrentEditorContents);
  27376. /** Returns true if the editor is currently focused and active. */
  27377. bool isBeingEdited() const throw();
  27378. juce_UseDebuggingNewOperator
  27379. protected:
  27380. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  27381. Subclasses can override this if they need to customise this component in some way.
  27382. */
  27383. virtual TextEditor* createEditorComponent();
  27384. /** Called after the user changes the text.
  27385. */
  27386. virtual void textWasEdited();
  27387. /** Called when the text has been altered.
  27388. */
  27389. virtual void textWasChanged();
  27390. /** Called when the text editor has just appeared, due to a user click or other
  27391. focus change.
  27392. */
  27393. virtual void editorShown (TextEditor* editorComponent);
  27394. /** Called when the text editor is going to be deleted, after editing has finished.
  27395. */
  27396. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  27397. /** @internal */
  27398. void paint (Graphics& g);
  27399. /** @internal */
  27400. void resized();
  27401. /** @internal */
  27402. void mouseUp (const MouseEvent& e);
  27403. /** @internal */
  27404. void mouseDoubleClick (const MouseEvent& e);
  27405. /** @internal */
  27406. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  27407. /** @internal */
  27408. void componentParentHierarchyChanged (Component& component);
  27409. /** @internal */
  27410. void componentVisibilityChanged (Component& component);
  27411. /** @internal */
  27412. void inputAttemptWhenModal();
  27413. /** @internal */
  27414. void focusGained (FocusChangeType);
  27415. /** @internal */
  27416. void enablementChanged();
  27417. /** @internal */
  27418. KeyboardFocusTraverser* createFocusTraverser();
  27419. /** @internal */
  27420. void textEditorTextChanged (TextEditor& editor);
  27421. /** @internal */
  27422. void textEditorReturnKeyPressed (TextEditor& editor);
  27423. /** @internal */
  27424. void textEditorEscapeKeyPressed (TextEditor& editor);
  27425. /** @internal */
  27426. void textEditorFocusLost (TextEditor& editor);
  27427. /** @internal */
  27428. void colourChanged();
  27429. /** @internal */
  27430. void valueChanged (Value&);
  27431. private:
  27432. Value textValue;
  27433. String lastTextValue;
  27434. Font font;
  27435. Justification justification;
  27436. ScopedPointer <TextEditor> editor;
  27437. ListenerList <LabelListener> listeners;
  27438. Component::SafePointer<Component> ownerComponent;
  27439. int horizontalBorderSize, verticalBorderSize;
  27440. float minimumHorizontalScale;
  27441. bool editSingleClick : 1;
  27442. bool editDoubleClick : 1;
  27443. bool lossOfFocusDiscardsChanges : 1;
  27444. bool leftOfOwnerComp : 1;
  27445. bool updateFromTextEditorContents();
  27446. void callChangeListeners();
  27447. Label (const Label&);
  27448. Label& operator= (const Label&);
  27449. };
  27450. #endif // __JUCE_LABEL_JUCEHEADER__
  27451. /*** End of inlined file: juce_Label.h ***/
  27452. class ComboBox;
  27453. /**
  27454. A class for receiving events from a ComboBox.
  27455. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  27456. method, and it will be called when the selected item in the box changes.
  27457. @see ComboBox::addListener, ComboBox::removeListener
  27458. */
  27459. class JUCE_API ComboBoxListener
  27460. {
  27461. public:
  27462. /** Destructor. */
  27463. virtual ~ComboBoxListener() {}
  27464. /** Called when a ComboBox has its selected item changed.
  27465. */
  27466. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  27467. };
  27468. /**
  27469. A component that lets the user choose from a drop-down list of choices.
  27470. The combo-box has a list of text strings, each with an associated id number,
  27471. that will be shown in the drop-down list when the user clicks on the component.
  27472. The currently selected choice is displayed in the combo-box, and this can
  27473. either be read-only text, or editable.
  27474. To find out when the user selects a different item or edits the text, you
  27475. can register a ComboBoxListener to receive callbacks.
  27476. @see ComboBoxListener
  27477. */
  27478. class JUCE_API ComboBox : public Component,
  27479. public SettableTooltipClient,
  27480. private LabelListener,
  27481. private AsyncUpdater,
  27482. private Value::Listener
  27483. {
  27484. public:
  27485. /** Creates a combo-box.
  27486. On construction, the text field will be empty, so you should call the
  27487. setSelectedId() or setText() method to choose the initial value before
  27488. displaying it.
  27489. @param componentName the name to set for the component (see Component::setName())
  27490. */
  27491. explicit ComboBox (const String& componentName = String::empty);
  27492. /** Destructor. */
  27493. ~ComboBox();
  27494. /** Sets whether the test in the combo-box is editable.
  27495. The default state for a new ComboBox is non-editable, and can only be changed
  27496. by choosing from the drop-down list.
  27497. */
  27498. void setEditableText (bool isEditable);
  27499. /** Returns true if the text is directly editable.
  27500. @see setEditableText
  27501. */
  27502. bool isTextEditable() const throw();
  27503. /** Sets the style of justification to be used for positioning the text.
  27504. The default is Justification::centredLeft. The text is displayed using a
  27505. Label component inside the ComboBox.
  27506. */
  27507. void setJustificationType (const Justification& justification) throw();
  27508. /** Returns the current justification for the text box.
  27509. @see setJustificationType
  27510. */
  27511. const Justification getJustificationType() const throw();
  27512. /** Adds an item to be shown in the drop-down list.
  27513. @param newItemText the text of the item to show in the list
  27514. @param newItemId an associated ID number that can be set or retrieved - see
  27515. getSelectedId() and setSelectedId()
  27516. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  27517. */
  27518. void addItem (const String& newItemText,
  27519. int newItemId) throw();
  27520. /** Adds a separator line to the drop-down list.
  27521. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  27522. */
  27523. void addSeparator() throw();
  27524. /** Adds a heading to the drop-down list, so that you can group the items into
  27525. different sections.
  27526. The headings are indented slightly differently to set them apart from the
  27527. items on the list, and obviously can't be selected. You might want to add
  27528. separators between your sections too.
  27529. @see addItem, addSeparator
  27530. */
  27531. void addSectionHeading (const String& headingName) throw();
  27532. /** This allows items in the drop-down list to be selectively disabled.
  27533. When you add an item, it's enabled by default, but you can call this
  27534. method to change its status.
  27535. If you disable an item which is already selected, this won't change the
  27536. current selection - it just stops the user choosing that item from the list.
  27537. */
  27538. void setItemEnabled (int itemId,
  27539. bool shouldBeEnabled) throw();
  27540. /** Changes the text for an existing item.
  27541. */
  27542. void changeItemText (int itemId,
  27543. const String& newText) throw();
  27544. /** Removes all the items from the drop-down list.
  27545. If this call causes the content to be cleared, then a change-message
  27546. will be broadcast unless dontSendChangeMessage is true.
  27547. @see addItem, removeItem, getNumItems
  27548. */
  27549. void clear (bool dontSendChangeMessage = false);
  27550. /** Returns the number of items that have been added to the list.
  27551. Note that this doesn't include headers or separators.
  27552. */
  27553. int getNumItems() const throw();
  27554. /** Returns the text for one of the items in the list.
  27555. Note that this doesn't include headers or separators.
  27556. @param index the item's index from 0 to (getNumItems() - 1)
  27557. */
  27558. const String getItemText (int index) const throw();
  27559. /** Returns the ID for one of the items in the list.
  27560. Note that this doesn't include headers or separators.
  27561. @param index the item's index from 0 to (getNumItems() - 1)
  27562. */
  27563. int getItemId (int index) const throw();
  27564. /** Returns the index in the list of a particular item ID.
  27565. If no such ID is found, this will return -1.
  27566. */
  27567. int indexOfItemId (int itemId) const throw();
  27568. /** Returns the ID of the item that's currently shown in the box.
  27569. If no item is selected, or if the text is editable and the user
  27570. has entered something which isn't one of the items in the list, then
  27571. this will return 0.
  27572. @see setSelectedId, getSelectedItemIndex, getText
  27573. */
  27574. int getSelectedId() const throw();
  27575. /** Returns a Value object that can be used to get or set the selected item's ID.
  27576. You can call Value::referTo() on this object to make the combo box control
  27577. another Value object.
  27578. */
  27579. Value& getSelectedIdAsValue() throw() { return currentId; }
  27580. /** Sets one of the items to be the current selection.
  27581. This will set the ComboBox's text to that of the item that matches
  27582. this ID.
  27583. @param newItemId the new item to select
  27584. @param dontSendChangeMessage if set to true, this method won't trigger a
  27585. change notification
  27586. @see getSelectedId, setSelectedItemIndex, setText
  27587. */
  27588. void setSelectedId (int newItemId,
  27589. bool dontSendChangeMessage = false) throw();
  27590. /** Returns the index of the item that's currently shown in the box.
  27591. If no item is selected, or if the text is editable and the user
  27592. has entered something which isn't one of the items in the list, then
  27593. this will return -1.
  27594. @see setSelectedItemIndex, getSelectedId, getText
  27595. */
  27596. int getSelectedItemIndex() const throw();
  27597. /** Sets one of the items to be the current selection.
  27598. This will set the ComboBox's text to that of the item at the given
  27599. index in the list.
  27600. @param newItemIndex the new item to select
  27601. @param dontSendChangeMessage if set to true, this method won't trigger a
  27602. change notification
  27603. @see getSelectedItemIndex, setSelectedId, setText
  27604. */
  27605. void setSelectedItemIndex (int newItemIndex,
  27606. bool dontSendChangeMessage = false) throw();
  27607. /** Returns the text that is currently shown in the combo-box's text field.
  27608. If the ComboBox has editable text, then this text may have been edited
  27609. by the user; otherwise it will be one of the items from the list, or
  27610. possibly an empty string if nothing was selected.
  27611. @see setText, getSelectedId, getSelectedItemIndex
  27612. */
  27613. const String getText() const throw();
  27614. /** Sets the contents of the combo-box's text field.
  27615. The text passed-in will be set as the current text regardless of whether
  27616. it is one of the items in the list. If the current text isn't one of the
  27617. items, then getSelectedId() will return -1, otherwise it wil return
  27618. the approriate ID.
  27619. @param newText the text to select
  27620. @param dontSendChangeMessage if set to true, this method won't trigger a
  27621. change notification
  27622. @see getText
  27623. */
  27624. void setText (const String& newText,
  27625. bool dontSendChangeMessage = false) throw();
  27626. /** Programmatically opens the text editor to allow the user to edit the current item.
  27627. This is the same effect as when the box is clicked-on.
  27628. @see Label::showEditor();
  27629. */
  27630. void showEditor();
  27631. /** Pops up the combo box's list. */
  27632. void showPopup();
  27633. /** Registers a listener that will be called when the box's content changes. */
  27634. void addListener (ComboBoxListener* listener) throw();
  27635. /** Deregisters a previously-registered listener. */
  27636. void removeListener (ComboBoxListener* listener) throw();
  27637. /** Sets a message to display when there is no item currently selected.
  27638. @see getTextWhenNothingSelected
  27639. */
  27640. void setTextWhenNothingSelected (const String& newMessage) throw();
  27641. /** Returns the text that is shown when no item is selected.
  27642. @see setTextWhenNothingSelected
  27643. */
  27644. const String getTextWhenNothingSelected() const throw();
  27645. /** Sets the message to show when there are no items in the list, and the user clicks
  27646. on the drop-down box.
  27647. By default it just says "no choices", but this lets you change it to something more
  27648. meaningful.
  27649. */
  27650. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  27651. /** Returns the text shown when no items have been added to the list.
  27652. @see setTextWhenNoChoicesAvailable
  27653. */
  27654. const String getTextWhenNoChoicesAvailable() const throw();
  27655. /** Gives the ComboBox a tooltip. */
  27656. void setTooltip (const String& newTooltip);
  27657. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  27658. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27659. methods.
  27660. To change the colours of the menu that pops up
  27661. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27662. */
  27663. enum ColourIds
  27664. {
  27665. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  27666. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  27667. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  27668. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  27669. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  27670. };
  27671. /** @internal */
  27672. void labelTextChanged (Label*);
  27673. /** @internal */
  27674. void enablementChanged();
  27675. /** @internal */
  27676. void colourChanged();
  27677. /** @internal */
  27678. void focusGained (Component::FocusChangeType cause);
  27679. /** @internal */
  27680. void focusLost (Component::FocusChangeType cause);
  27681. /** @internal */
  27682. void handleAsyncUpdate();
  27683. /** @internal */
  27684. const String getTooltip() { return label->getTooltip(); }
  27685. /** @internal */
  27686. void mouseDown (const MouseEvent&);
  27687. /** @internal */
  27688. void mouseDrag (const MouseEvent&);
  27689. /** @internal */
  27690. void mouseUp (const MouseEvent&);
  27691. /** @internal */
  27692. void lookAndFeelChanged();
  27693. /** @internal */
  27694. void paint (Graphics&);
  27695. /** @internal */
  27696. void resized();
  27697. /** @internal */
  27698. bool keyStateChanged (bool isKeyDown);
  27699. /** @internal */
  27700. bool keyPressed (const KeyPress&);
  27701. /** @internal */
  27702. void valueChanged (Value&);
  27703. juce_UseDebuggingNewOperator
  27704. private:
  27705. struct ItemInfo
  27706. {
  27707. String name;
  27708. int itemId;
  27709. bool isEnabled : 1, isHeading : 1;
  27710. bool isSeparator() const throw();
  27711. bool isRealItem() const throw();
  27712. };
  27713. class Callback;
  27714. friend class Callback;
  27715. OwnedArray <ItemInfo> items;
  27716. Value currentId;
  27717. int lastCurrentId;
  27718. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  27719. ListenerList <ComboBoxListener> listeners;
  27720. ScopedPointer<Label> label;
  27721. String textWhenNothingSelected, noChoicesMessage;
  27722. ItemInfo* getItemForId (int itemId) const throw();
  27723. ItemInfo* getItemForIndex (int index) const throw();
  27724. ComboBox (const ComboBox&);
  27725. ComboBox& operator= (const ComboBox&);
  27726. };
  27727. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  27728. /*** End of inlined file: juce_ComboBox.h ***/
  27729. /**
  27730. Manages the state of some audio and midi i/o devices.
  27731. This class keeps tracks of a currently-selected audio device, through
  27732. with which it continuously streams data from an audio callback, as well as
  27733. one or more midi inputs.
  27734. The idea is that your application will create one global instance of this object,
  27735. and let it take care of creating and deleting specific types of audio devices
  27736. internally. So when the device is changed, your callbacks will just keep running
  27737. without having to worry about this.
  27738. The manager can save and reload all of its device settings as XML, which
  27739. makes it very easy for you to save and reload the audio setup of your
  27740. application.
  27741. And to make it easy to let the user change its settings, there's a component
  27742. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  27743. device selection/sample-rate/latency controls.
  27744. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  27745. call addAudioCallback() to register your audio callback with it, and use that to process
  27746. your audio data.
  27747. The manager also acts as a handy hub for incoming midi messages, allowing a
  27748. listener to register for messages from either a specific midi device, or from whatever
  27749. the current default midi input device is. The listener then doesn't have to worry about
  27750. re-registering with different midi devices if they are changed or deleted.
  27751. And yet another neat trick is that amount of CPU time being used is measured and
  27752. available with the getCpuUsage() method.
  27753. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  27754. listeners whenever one of its settings is changed.
  27755. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  27756. */
  27757. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  27758. {
  27759. public:
  27760. /** Creates a default AudioDeviceManager.
  27761. Initially no audio device will be selected. You should call the initialise() method
  27762. and register an audio callback with setAudioCallback() before it'll be able to
  27763. actually make any noise.
  27764. */
  27765. AudioDeviceManager();
  27766. /** Destructor. */
  27767. ~AudioDeviceManager();
  27768. /**
  27769. This structure holds a set of properties describing the current audio setup.
  27770. @see AudioDeviceManager::setAudioDeviceSetup()
  27771. */
  27772. struct JUCE_API AudioDeviceSetup
  27773. {
  27774. AudioDeviceSetup();
  27775. bool operator== (const AudioDeviceSetup& other) const;
  27776. /** The name of the audio device used for output.
  27777. The name has to be one of the ones listed by the AudioDeviceManager's currently
  27778. selected device type.
  27779. This may be the same as the input device.
  27780. */
  27781. String outputDeviceName;
  27782. /** The name of the audio device used for input.
  27783. This may be the same as the output device.
  27784. */
  27785. String inputDeviceName;
  27786. /** The current sample rate.
  27787. This rate is used for both the input and output devices.
  27788. */
  27789. double sampleRate;
  27790. /** The buffer size, in samples.
  27791. This buffer size is used for both the input and output devices.
  27792. */
  27793. int bufferSize;
  27794. /** The set of active input channels.
  27795. The bits that are set in this array indicate the channels of the
  27796. input device that are active.
  27797. */
  27798. BigInteger inputChannels;
  27799. /** If this is true, it indicates that the inputChannels array
  27800. should be ignored, and instead, the device's default channels
  27801. should be used.
  27802. */
  27803. bool useDefaultInputChannels;
  27804. /** The set of active output channels.
  27805. The bits that are set in this array indicate the channels of the
  27806. input device that are active.
  27807. */
  27808. BigInteger outputChannels;
  27809. /** If this is true, it indicates that the outputChannels array
  27810. should be ignored, and instead, the device's default channels
  27811. should be used.
  27812. */
  27813. bool useDefaultOutputChannels;
  27814. };
  27815. /** Opens a set of audio devices ready for use.
  27816. This will attempt to open either a default audio device, or one that was
  27817. previously saved as XML.
  27818. @param numInputChannelsNeeded a minimum number of input channels needed
  27819. by your app.
  27820. @param numOutputChannelsNeeded a minimum number of output channels to open
  27821. @param savedState either a previously-saved state that was produced
  27822. by createStateXml(), or 0 if you want the manager
  27823. to choose the best device to open.
  27824. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  27825. fails to open, then a default device will be used
  27826. instead. If false, then on failure, no device is
  27827. opened.
  27828. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  27829. name, then that will be used as the default device
  27830. (assuming that there wasn't one specified in the XML).
  27831. The string can actually be a simple wildcard, containing "*"
  27832. and "?" characters
  27833. @param preferredSetupOptions if this is non-null, the structure will be used as the
  27834. set of preferred settings when opening the device. If you
  27835. use this parameter, the preferredDefaultDeviceName
  27836. field will be ignored
  27837. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27838. */
  27839. const String initialise (int numInputChannelsNeeded,
  27840. int numOutputChannelsNeeded,
  27841. const XmlElement* savedState,
  27842. bool selectDefaultDeviceOnFailure,
  27843. const String& preferredDefaultDeviceName = String::empty,
  27844. const AudioDeviceSetup* preferredSetupOptions = 0);
  27845. /** Returns some XML representing the current state of the manager.
  27846. This stores the current device, its samplerate, block size, etc, and
  27847. can be restored later with initialise().
  27848. */
  27849. XmlElement* createStateXml() const;
  27850. /** Returns the current device properties that are in use.
  27851. @see setAudioDeviceSetup
  27852. */
  27853. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  27854. /** Changes the current device or its settings.
  27855. If you want to change a device property, like the current sample rate or
  27856. block size, you can call getAudioDeviceSetup() to retrieve the current
  27857. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  27858. and pass it back into this method to apply the new settings.
  27859. @param newSetup the settings that you'd like to use
  27860. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  27861. settings will be taken as having been explicitly chosen by the
  27862. user, and the next time createStateXml() is called, these settings
  27863. will be returned. If it's false, then the device is treated as a
  27864. temporary or default device, and a call to createStateXml() will
  27865. return either the last settings that were made with treatAsChosenDevice
  27866. as true, or the last XML settings that were passed into initialise().
  27867. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27868. @see getAudioDeviceSetup
  27869. */
  27870. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  27871. bool treatAsChosenDevice);
  27872. /** Returns the currently-active audio device. */
  27873. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  27874. /** Returns the type of audio device currently in use.
  27875. @see setCurrentAudioDeviceType
  27876. */
  27877. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  27878. /** Returns the currently active audio device type object.
  27879. Don't keep a copy of this pointer - it's owned by the device manager and could
  27880. change at any time.
  27881. */
  27882. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  27883. /** Changes the class of audio device being used.
  27884. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  27885. this because there's only one type: CoreAudio.
  27886. For a list of types, see getAvailableDeviceTypes().
  27887. */
  27888. void setCurrentAudioDeviceType (const String& type,
  27889. bool treatAsChosenDevice);
  27890. /** Closes the currently-open device.
  27891. You can call restartLastAudioDevice() later to reopen it in the same state
  27892. that it was just in.
  27893. */
  27894. void closeAudioDevice();
  27895. /** Tries to reload the last audio device that was running.
  27896. Note that this only reloads the last device that was running before
  27897. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  27898. and can only be called after a device has been opened with SetAudioDevice().
  27899. If a device is already open, this call will do nothing.
  27900. */
  27901. void restartLastAudioDevice();
  27902. /** Registers an audio callback to be used.
  27903. The manager will redirect callbacks from whatever audio device is currently
  27904. in use to all registered callback objects. If more than one callback is
  27905. active, they will all be given the same input data, and their outputs will
  27906. be summed.
  27907. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  27908. object before returning.
  27909. To remove a callback, use removeAudioCallback().
  27910. */
  27911. void addAudioCallback (AudioIODeviceCallback* newCallback);
  27912. /** Deregisters a previously added callback.
  27913. If necessary, this method will invoke audioDeviceStopped() on the callback
  27914. object before returning.
  27915. @see addAudioCallback
  27916. */
  27917. void removeAudioCallback (AudioIODeviceCallback* callback);
  27918. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  27919. Returns a value between 0 and 1.0
  27920. */
  27921. double getCpuUsage() const;
  27922. /** Enables or disables a midi input device.
  27923. The list of devices can be obtained with the MidiInput::getDevices() method.
  27924. Any incoming messages from enabled input devices will be forwarded on to all the
  27925. listeners that have been registered with the addMidiInputCallback() method. They
  27926. can either register for messages from a particular device, or from just the
  27927. "default" midi input.
  27928. Routing the midi input via an AudioDeviceManager means that when a listener
  27929. registers for the default midi input, this default device can be changed by the
  27930. manager without the listeners having to know about it or re-register.
  27931. It also means that a listener can stay registered for a midi input that is disabled
  27932. or not present, so that when the input is re-enabled, the listener will start
  27933. receiving messages again.
  27934. @see addMidiInputCallback, isMidiInputEnabled
  27935. */
  27936. void setMidiInputEnabled (const String& midiInputDeviceName,
  27937. bool enabled);
  27938. /** Returns true if a given midi input device is being used.
  27939. @see setMidiInputEnabled
  27940. */
  27941. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  27942. /** Registers a listener for callbacks when midi events arrive from a midi input.
  27943. The device name can be empty to indicate that it wants events from whatever the
  27944. current "default" device is. Or it can be the name of one of the midi input devices
  27945. (see MidiInput::getDevices() for the names).
  27946. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  27947. events forwarded on to listeners.
  27948. */
  27949. void addMidiInputCallback (const String& midiInputDeviceName,
  27950. MidiInputCallback* callback);
  27951. /** Removes a listener that was previously registered with addMidiInputCallback().
  27952. */
  27953. void removeMidiInputCallback (const String& midiInputDeviceName,
  27954. MidiInputCallback* callback);
  27955. /** Sets a midi output device to use as the default.
  27956. The list of devices can be obtained with the MidiOutput::getDevices() method.
  27957. The specified device will be opened automatically and can be retrieved with the
  27958. getDefaultMidiOutput() method.
  27959. Pass in an empty string to deselect all devices. For the default device, you
  27960. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  27961. @see getDefaultMidiOutput, getDefaultMidiOutputName
  27962. */
  27963. void setDefaultMidiOutput (const String& deviceName);
  27964. /** Returns the name of the default midi output.
  27965. @see setDefaultMidiOutput, getDefaultMidiOutput
  27966. */
  27967. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  27968. /** Returns the current default midi output device.
  27969. If no device has been selected, or the device can't be opened, this will
  27970. return 0.
  27971. @see getDefaultMidiOutputName
  27972. */
  27973. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  27974. /** Returns a list of the types of device supported.
  27975. */
  27976. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  27977. /** Creates a list of available types.
  27978. This will add a set of new AudioIODeviceType objects to the specified list, to
  27979. represent each available types of device.
  27980. You can override this if your app needs to do something specific, like avoid
  27981. using DirectSound devices, etc.
  27982. */
  27983. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  27984. /** Plays a beep through the current audio device.
  27985. This is here to allow the audio setup UI panels to easily include a "test"
  27986. button so that the user can check where the audio is coming from.
  27987. */
  27988. void playTestSound();
  27989. /** Turns on level-measuring.
  27990. When enabled, the device manager will measure the peak input level
  27991. across all channels, and you can get this level by calling getCurrentInputLevel().
  27992. This is mainly intended for audio setup UI panels to use to create a mic
  27993. level display, so that the user can check that they've selected the right
  27994. device.
  27995. A simple filter is used to make the level decay smoothly, but this is
  27996. only intended for giving rough feedback, and not for any kind of accurate
  27997. measurement.
  27998. */
  27999. void enableInputLevelMeasurement (bool enableMeasurement);
  28000. /** Returns the current input level.
  28001. To use this, you must first enable it by calling enableInputLevelMeasurement().
  28002. See enableInputLevelMeasurement() for more info.
  28003. */
  28004. double getCurrentInputLevel() const;
  28005. juce_UseDebuggingNewOperator
  28006. private:
  28007. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  28008. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  28009. AudioDeviceSetup currentSetup;
  28010. ScopedPointer <AudioIODevice> currentAudioDevice;
  28011. SortedSet <AudioIODeviceCallback*> callbacks;
  28012. int numInputChansNeeded, numOutputChansNeeded;
  28013. String currentDeviceType;
  28014. BigInteger inputChannels, outputChannels;
  28015. ScopedPointer <XmlElement> lastExplicitSettings;
  28016. mutable bool listNeedsScanning;
  28017. bool useInputNames;
  28018. int inputLevelMeasurementEnabledCount;
  28019. double inputLevel;
  28020. ScopedPointer <AudioSampleBuffer> testSound;
  28021. int testSoundPosition;
  28022. AudioSampleBuffer tempBuffer;
  28023. StringArray midiInsFromXml;
  28024. OwnedArray <MidiInput> enabledMidiInputs;
  28025. Array <MidiInputCallback*> midiCallbacks;
  28026. Array <MidiInput*> midiCallbackDevices;
  28027. String defaultMidiOutputName;
  28028. ScopedPointer <MidiOutput> defaultMidiOutput;
  28029. CriticalSection audioCallbackLock, midiCallbackLock;
  28030. double cpuUsageMs, timeToCpuScale;
  28031. class CallbackHandler : public AudioIODeviceCallback,
  28032. public MidiInputCallback
  28033. {
  28034. public:
  28035. AudioDeviceManager* owner;
  28036. void audioDeviceIOCallback (const float** inputChannelData,
  28037. int totalNumInputChannels,
  28038. float** outputChannelData,
  28039. int totalNumOutputChannels,
  28040. int numSamples);
  28041. void audioDeviceAboutToStart (AudioIODevice*);
  28042. void audioDeviceStopped();
  28043. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28044. };
  28045. CallbackHandler callbackHandler;
  28046. friend class CallbackHandler;
  28047. void audioDeviceIOCallbackInt (const float** inputChannelData,
  28048. int totalNumInputChannels,
  28049. float** outputChannelData,
  28050. int totalNumOutputChannels,
  28051. int numSamples);
  28052. void audioDeviceAboutToStartInt (AudioIODevice* device);
  28053. void audioDeviceStoppedInt();
  28054. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  28055. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  28056. const BigInteger& ins, const BigInteger& outs);
  28057. void stopDevice();
  28058. void updateXml();
  28059. void createDeviceTypesIfNeeded();
  28060. void scanDevicesIfNeeded();
  28061. void deleteCurrentDevice();
  28062. double chooseBestSampleRate (double preferred) const;
  28063. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  28064. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  28065. AudioDeviceManager (const AudioDeviceManager&);
  28066. AudioDeviceManager& operator= (const AudioDeviceManager&);
  28067. };
  28068. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  28069. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  28070. #endif
  28071. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28072. #endif
  28073. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  28074. #endif
  28075. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  28076. #endif
  28077. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  28078. #endif
  28079. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28080. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  28081. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28082. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28083. /**
  28084. A set of routines to convert buffers of 32-bit floating point data to and from
  28085. various integer formats.
  28086. */
  28087. class JUCE_API AudioDataConverters
  28088. {
  28089. public:
  28090. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  28091. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  28092. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  28093. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  28094. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28095. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28096. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28097. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28098. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  28099. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  28100. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  28101. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  28102. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28103. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28104. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28105. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28106. enum DataFormat
  28107. {
  28108. int16LE,
  28109. int16BE,
  28110. int24LE,
  28111. int24BE,
  28112. int32LE,
  28113. int32BE,
  28114. float32LE,
  28115. float32BE,
  28116. };
  28117. static void convertFloatToFormat (DataFormat destFormat,
  28118. const float* source, void* dest, int numSamples);
  28119. static void convertFormatToFloat (DataFormat sourceFormat,
  28120. const void* source, float* dest, int numSamples);
  28121. static void interleaveSamples (const float** source, float* dest,
  28122. int numSamples, int numChannels);
  28123. static void deinterleaveSamples (const float* source, float** dest,
  28124. int numSamples, int numChannels);
  28125. private:
  28126. AudioDataConverters();
  28127. AudioDataConverters (const AudioDataConverters&);
  28128. AudioDataConverters& operator= (const AudioDataConverters&);
  28129. };
  28130. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28131. /*** End of inlined file: juce_AudioDataConverters.h ***/
  28132. #endif
  28133. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  28134. #endif
  28135. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  28136. #endif
  28137. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  28138. #endif
  28139. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  28140. /*** Start of inlined file: juce_MidiFile.h ***/
  28141. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  28142. #define __JUCE_MIDIFILE_JUCEHEADER__
  28143. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  28144. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28145. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28146. /**
  28147. A sequence of timestamped midi messages.
  28148. This allows the sequence to be manipulated, and also to be read from and
  28149. written to a standard midi file.
  28150. @see MidiMessage, MidiFile
  28151. */
  28152. class JUCE_API MidiMessageSequence
  28153. {
  28154. public:
  28155. /** Creates an empty midi sequence object. */
  28156. MidiMessageSequence();
  28157. /** Creates a copy of another sequence. */
  28158. MidiMessageSequence (const MidiMessageSequence& other);
  28159. /** Replaces this sequence with another one. */
  28160. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  28161. /** Destructor. */
  28162. ~MidiMessageSequence();
  28163. /** Structure used to hold midi events in the sequence.
  28164. These structures act as 'handles' on the events as they are moved about in
  28165. the list, and make it quick to find the matching note-offs for note-on events.
  28166. @see MidiMessageSequence::getEventPointer
  28167. */
  28168. class MidiEventHolder
  28169. {
  28170. public:
  28171. /** Destructor. */
  28172. ~MidiEventHolder();
  28173. /** The message itself, whose timestamp is used to specify the event's time.
  28174. */
  28175. MidiMessage message;
  28176. /** The matching note-off event (if this is a note-on event).
  28177. If this isn't a note-on, this pointer will be null.
  28178. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  28179. note-offs up-to-date after events have been moved around in the sequence
  28180. or deleted.
  28181. */
  28182. MidiEventHolder* noteOffObject;
  28183. juce_UseDebuggingNewOperator
  28184. private:
  28185. friend class MidiMessageSequence;
  28186. MidiEventHolder (const MidiMessage& message);
  28187. };
  28188. /** Clears the sequence. */
  28189. void clear();
  28190. /** Returns the number of events in the sequence. */
  28191. int getNumEvents() const;
  28192. /** Returns a pointer to one of the events. */
  28193. MidiEventHolder* getEventPointer (int index) const;
  28194. /** Returns the time of the note-up that matches the note-on at this index.
  28195. If the event at this index isn't a note-on, it'll just return 0.
  28196. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  28197. */
  28198. double getTimeOfMatchingKeyUp (int index) const;
  28199. /** Returns the index of the note-up that matches the note-on at this index.
  28200. If the event at this index isn't a note-on, it'll just return -1.
  28201. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  28202. */
  28203. int getIndexOfMatchingKeyUp (int index) const;
  28204. /** Returns the index of an event. */
  28205. int getIndexOf (MidiEventHolder* event) const;
  28206. /** Returns the index of the first event on or after the given timestamp.
  28207. If the time is beyond the end of the sequence, this will return the
  28208. number of events.
  28209. */
  28210. int getNextIndexAtTime (double timeStamp) const;
  28211. /** Returns the timestamp of the first event in the sequence.
  28212. @see getEndTime
  28213. */
  28214. double getStartTime() const;
  28215. /** Returns the timestamp of the last event in the sequence.
  28216. @see getStartTime
  28217. */
  28218. double getEndTime() const;
  28219. /** Returns the timestamp of the event at a given index.
  28220. If the index is out-of-range, this will return 0.0
  28221. */
  28222. double getEventTime (int index) const;
  28223. /** Inserts a midi message into the sequence.
  28224. The index at which the new message gets inserted will depend on its timestamp,
  28225. because the sequence is kept sorted.
  28226. Remember to call updateMatchedPairs() after adding note-on events.
  28227. @param newMessage the new message to add (an internal copy will be made)
  28228. @param timeAdjustment an optional value to add to the timestamp of the message
  28229. that will be inserted
  28230. @see updateMatchedPairs
  28231. */
  28232. void addEvent (const MidiMessage& newMessage,
  28233. double timeAdjustment = 0);
  28234. /** Deletes one of the events in the sequence.
  28235. Remember to call updateMatchedPairs() after removing events.
  28236. @param index the index of the event to delete
  28237. @param deleteMatchingNoteUp whether to also remove the matching note-off
  28238. if the event you're removing is a note-on
  28239. */
  28240. void deleteEvent (int index, bool deleteMatchingNoteUp);
  28241. /** Merges another sequence into this one.
  28242. Remember to call updateMatchedPairs() after using this method.
  28243. @param other the sequence to add from
  28244. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  28245. as they are read from the other sequence
  28246. @param firstAllowableDestTime events will not be added if their time is earlier
  28247. than this time. (This is after their time has been adjusted
  28248. by the timeAdjustmentDelta)
  28249. @param endOfAllowableDestTimes events will not be added if their time is equal to
  28250. or greater than this time. (This is after their time has
  28251. been adjusted by the timeAdjustmentDelta)
  28252. */
  28253. void addSequence (const MidiMessageSequence& other,
  28254. double timeAdjustmentDelta,
  28255. double firstAllowableDestTime,
  28256. double endOfAllowableDestTimes);
  28257. /** Makes sure all the note-on and note-off pairs are up-to-date.
  28258. Call this after moving messages about or deleting/adding messages, and it
  28259. will scan the list and make sure all the note-offs in the MidiEventHolder
  28260. structures are pointing at the correct ones.
  28261. */
  28262. void updateMatchedPairs();
  28263. /** Copies all the messages for a particular midi channel to another sequence.
  28264. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  28265. @param destSequence the sequence that the chosen events should be copied to
  28266. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  28267. channel) will also be copied across.
  28268. @see extractSysExMessages
  28269. */
  28270. void extractMidiChannelMessages (int channelNumberToExtract,
  28271. MidiMessageSequence& destSequence,
  28272. bool alsoIncludeMetaEvents) const;
  28273. /** Copies all midi sys-ex messages to another sequence.
  28274. @param destSequence this is the sequence to which any sys-exes in this sequence
  28275. will be added
  28276. @see extractMidiChannelMessages
  28277. */
  28278. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  28279. /** Removes any messages in this sequence that have a specific midi channel.
  28280. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  28281. */
  28282. void deleteMidiChannelMessages (int channelNumberToRemove);
  28283. /** Removes any sys-ex messages from this sequence.
  28284. */
  28285. void deleteSysExMessages();
  28286. /** Adds an offset to the timestamps of all events in the sequence.
  28287. @param deltaTime the amount to add to each timestamp.
  28288. */
  28289. void addTimeToMessages (double deltaTime);
  28290. /** Scans through the sequence to determine the state of any midi controllers at
  28291. a given time.
  28292. This will create a sequence of midi controller changes that can be
  28293. used to set all midi controllers to the state they would be in at the
  28294. specified time within this sequence.
  28295. As well as controllers, it will also recreate the midi program number
  28296. and pitch bend position.
  28297. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  28298. for other channels will be ignored.
  28299. @param time the time at which you want to find out the state - there are
  28300. no explicit units for this time measurement, it's the same units
  28301. as used for the timestamps of the messages
  28302. @param resultMessages an array to which midi controller-change messages will be added. This
  28303. will be the minimum number of controller changes to recreate the
  28304. state at the required time.
  28305. */
  28306. void createControllerUpdatesForTime (int channelNumber, double time,
  28307. OwnedArray<MidiMessage>& resultMessages);
  28308. /** Swaps this sequence with another one. */
  28309. void swapWith (MidiMessageSequence& other) throw();
  28310. juce_UseDebuggingNewOperator
  28311. /** @internal */
  28312. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  28313. const MidiMessageSequence::MidiEventHolder* second) throw();
  28314. private:
  28315. friend class MidiFile;
  28316. OwnedArray <MidiEventHolder> list;
  28317. void sort();
  28318. };
  28319. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28320. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  28321. /**
  28322. Reads/writes standard midi format files.
  28323. To read a midi file, create a MidiFile object and call its readFrom() method. You
  28324. can then get the individual midi tracks from it using the getTrack() method.
  28325. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  28326. to it using the addTrack() method, and then call its writeTo() method to stream
  28327. it out.
  28328. @see MidiMessageSequence
  28329. */
  28330. class JUCE_API MidiFile
  28331. {
  28332. public:
  28333. /** Creates an empty MidiFile object.
  28334. */
  28335. MidiFile();
  28336. /** Destructor. */
  28337. ~MidiFile();
  28338. /** Returns the number of tracks in the file.
  28339. @see getTrack, addTrack
  28340. */
  28341. int getNumTracks() const throw();
  28342. /** Returns a pointer to one of the tracks in the file.
  28343. @returns a pointer to the track, or 0 if the index is out-of-range
  28344. @see getNumTracks, addTrack
  28345. */
  28346. const MidiMessageSequence* getTrack (const int index) const throw();
  28347. /** Adds a midi track to the file.
  28348. This will make its own internal copy of the sequence that is passed-in.
  28349. @see getNumTracks, getTrack
  28350. */
  28351. void addTrack (const MidiMessageSequence& trackSequence);
  28352. /** Removes all midi tracks from the file.
  28353. @see getNumTracks
  28354. */
  28355. void clear();
  28356. /** Returns the raw time format code that will be written to a stream.
  28357. After reading a midi file, this method will return the time-format that
  28358. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  28359. or setSmpteTimeFormat() methods.
  28360. If the value returned is positive, it indicates the number of midi ticks
  28361. per quarter-note - see setTicksPerQuarterNote().
  28362. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  28363. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  28364. */
  28365. short getTimeFormat() const throw();
  28366. /** Sets the time format to use when this file is written to a stream.
  28367. If this is called, the file will be written as bars/beats using the
  28368. specified resolution, rather than SMPTE absolute times, as would be
  28369. used if setSmpteTimeFormat() had been called instead.
  28370. @param ticksPerQuarterNote e.g. 96, 960
  28371. @see setSmpteTimeFormat
  28372. */
  28373. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  28374. /** Sets the time format to use when this file is written to a stream.
  28375. If this is called, the file will be written using absolute times, rather
  28376. than bars/beats as would be the case if setTicksPerBeat() had been called
  28377. instead.
  28378. @param framesPerSecond must be 24, 25, 29 or 30
  28379. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  28380. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  28381. timing, setSmpteTimeFormat (25, 40)
  28382. @see setTicksPerBeat
  28383. */
  28384. void setSmpteTimeFormat (const int framesPerSecond,
  28385. const int subframeResolution) throw();
  28386. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  28387. Useful for finding the positions of all the tempo changes in a file.
  28388. @param tempoChangeEvents a list to which all the events will be added
  28389. */
  28390. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  28391. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  28392. Useful for finding the positions of all the tempo changes in a file.
  28393. @param timeSigEvents a list to which all the events will be added
  28394. */
  28395. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  28396. /** Returns the latest timestamp in any of the tracks.
  28397. (Useful for finding the length of the file).
  28398. */
  28399. double getLastTimestamp() const;
  28400. /** Reads a midi file format stream.
  28401. After calling this, you can get the tracks that were read from the file by using the
  28402. getNumTracks() and getTrack() methods.
  28403. The timestamps of the midi events in the tracks will represent their positions in
  28404. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  28405. method.
  28406. @returns true if the stream was read successfully
  28407. */
  28408. bool readFrom (InputStream& sourceStream);
  28409. /** Writes the midi tracks as a standard midi file.
  28410. @returns true if the operation succeeded.
  28411. */
  28412. bool writeTo (OutputStream& destStream);
  28413. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  28414. This will use the midi time format and tempo/time signature info in the
  28415. tracks to convert all the timestamps to absolute values in seconds.
  28416. */
  28417. void convertTimestampTicksToSeconds();
  28418. juce_UseDebuggingNewOperator
  28419. /** @internal */
  28420. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  28421. const MidiMessageSequence::MidiEventHolder* const second);
  28422. private:
  28423. OwnedArray <MidiMessageSequence> tracks;
  28424. short timeFormat;
  28425. MidiFile (const MidiFile&);
  28426. MidiFile& operator= (const MidiFile&);
  28427. void readNextTrack (const uint8* data, int size);
  28428. void writeTrack (OutputStream& mainOut, const int trackNum);
  28429. };
  28430. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  28431. /*** End of inlined file: juce_MidiFile.h ***/
  28432. #endif
  28433. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28434. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  28435. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28436. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28437. class MidiKeyboardState;
  28438. /**
  28439. Receives events from a MidiKeyboardState object.
  28440. @see MidiKeyboardState
  28441. */
  28442. class JUCE_API MidiKeyboardStateListener
  28443. {
  28444. public:
  28445. MidiKeyboardStateListener() throw() {}
  28446. virtual ~MidiKeyboardStateListener() {}
  28447. /** Called when one of the MidiKeyboardState's keys is pressed.
  28448. This will be called synchronously when the state is either processing a
  28449. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28450. when a note is being played with its MidiKeyboardState::noteOn() method.
  28451. Note that this callback could happen from an audio callback thread, so be
  28452. careful not to block, and avoid any UI activity in the callback.
  28453. */
  28454. virtual void handleNoteOn (MidiKeyboardState* source,
  28455. int midiChannel, int midiNoteNumber, float velocity) = 0;
  28456. /** Called when one of the MidiKeyboardState's keys is released.
  28457. This will be called synchronously when the state is either processing a
  28458. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28459. when a note is being played with its MidiKeyboardState::noteOff() method.
  28460. Note that this callback could happen from an audio callback thread, so be
  28461. careful not to block, and avoid any UI activity in the callback.
  28462. */
  28463. virtual void handleNoteOff (MidiKeyboardState* source,
  28464. int midiChannel, int midiNoteNumber) = 0;
  28465. };
  28466. /**
  28467. Represents a piano keyboard, keeping track of which keys are currently pressed.
  28468. This object can parse a stream of midi events, using them to update its idea
  28469. of which keys are pressed for each individiual midi channel.
  28470. When keys go up or down, it can broadcast these events to listener objects.
  28471. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  28472. methods, and midi messages for these events will be merged into the
  28473. midi stream that gets processed by processNextMidiBuffer().
  28474. */
  28475. class JUCE_API MidiKeyboardState
  28476. {
  28477. public:
  28478. MidiKeyboardState();
  28479. ~MidiKeyboardState();
  28480. /** Resets the state of the object.
  28481. All internal data for all the channels is reset, but no events are sent as a
  28482. result.
  28483. If you want to release any keys that are currently down, and to send out note-up
  28484. midi messages for this, use the allNotesOff() method instead.
  28485. */
  28486. void reset();
  28487. /** Returns true if the given midi key is currently held down for the given midi channel.
  28488. The channel number must be between 1 and 16. If you want to see if any notes are
  28489. on for a range of channels, use the isNoteOnForChannels() method.
  28490. */
  28491. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  28492. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  28493. The channel mask has a bit set for each midi channel you want to test for - bit
  28494. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  28495. If a note is on for at least one of the specified channels, this returns true.
  28496. */
  28497. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  28498. /** Turns a specified note on.
  28499. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  28500. next call to processNextMidiBuffer().
  28501. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28502. gone down.
  28503. */
  28504. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  28505. /** Turns a specified note off.
  28506. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  28507. next call to processNextMidiBuffer().
  28508. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28509. gone up.
  28510. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  28511. */
  28512. void noteOff (const int midiChannel, const int midiNoteNumber);
  28513. /** This will turn off any currently-down notes for the given midi channel.
  28514. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  28515. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  28516. and events being added to the midi stream.
  28517. */
  28518. void allNotesOff (const int midiChannel);
  28519. /** Looks at a key-up/down event and uses it to update the state of this object.
  28520. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  28521. instead.
  28522. */
  28523. void processNextMidiEvent (const MidiMessage& message);
  28524. /** Scans a midi stream for up/down events and adds its own events to it.
  28525. This will look for any up/down events and use them to update the internal state,
  28526. synchronously making suitable callbacks to the listeners.
  28527. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  28528. and noteOff() calls will be added into the buffer.
  28529. Only the section of the buffer whose timestamps are between startSample and
  28530. (startSample + numSamples) will be affected, and any events added will be placed
  28531. between these times.
  28532. If you're going to use this method, you'll need to keep calling it regularly for
  28533. it to work satisfactorily.
  28534. To process a single midi event at a time, use the processNextMidiEvent() method
  28535. instead.
  28536. */
  28537. void processNextMidiBuffer (MidiBuffer& buffer,
  28538. const int startSample,
  28539. const int numSamples,
  28540. const bool injectIndirectEvents);
  28541. /** Registers a listener for callbacks when keys go up or down.
  28542. @see removeListener
  28543. */
  28544. void addListener (MidiKeyboardStateListener* const listener) throw();
  28545. /** Deregisters a listener.
  28546. @see addListener
  28547. */
  28548. void removeListener (MidiKeyboardStateListener* const listener) throw();
  28549. juce_UseDebuggingNewOperator
  28550. private:
  28551. CriticalSection lock;
  28552. uint16 noteStates [128];
  28553. MidiBuffer eventsToAdd;
  28554. Array <MidiKeyboardStateListener*> listeners;
  28555. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  28556. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  28557. MidiKeyboardState (const MidiKeyboardState&);
  28558. MidiKeyboardState& operator= (const MidiKeyboardState&);
  28559. };
  28560. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28561. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  28562. #endif
  28563. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  28564. #endif
  28565. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28566. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  28567. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28568. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28569. /**
  28570. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  28571. processing by a block-based audio callback.
  28572. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  28573. so it can easily use a midi input or keyboard component as its source.
  28574. @see MidiMessage, MidiInput
  28575. */
  28576. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  28577. public MidiInputCallback
  28578. {
  28579. public:
  28580. /** Creates a MidiMessageCollector. */
  28581. MidiMessageCollector();
  28582. /** Destructor. */
  28583. ~MidiMessageCollector();
  28584. /** Clears any messages from the queue.
  28585. You need to call this method before starting to use the collector, so that
  28586. it knows the correct sample rate to use.
  28587. */
  28588. void reset (double sampleRate);
  28589. /** Takes an incoming real-time message and adds it to the queue.
  28590. The message's timestamp is taken, and it will be ready for retrieval as part
  28591. of the block returned by the next call to removeNextBlockOfMessages().
  28592. This method is fully thread-safe when overlapping calls are made with
  28593. removeNextBlockOfMessages().
  28594. */
  28595. void addMessageToQueue (const MidiMessage& message);
  28596. /** Removes all the pending messages from the queue as a buffer.
  28597. This will also correct the messages' timestamps to make sure they're in
  28598. the range 0 to numSamples - 1.
  28599. This call should be made regularly by something like an audio processing
  28600. callback, because the time that it happens is used in calculating the
  28601. midi event positions.
  28602. This method is fully thread-safe when overlapping calls are made with
  28603. addMessageToQueue().
  28604. */
  28605. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  28606. /** @internal */
  28607. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  28608. /** @internal */
  28609. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  28610. /** @internal */
  28611. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28612. juce_UseDebuggingNewOperator
  28613. private:
  28614. double lastCallbackTime;
  28615. CriticalSection midiCallbackLock;
  28616. MidiBuffer incomingMessages;
  28617. double sampleRate;
  28618. MidiMessageCollector (const MidiMessageCollector&);
  28619. MidiMessageCollector& operator= (const MidiMessageCollector&);
  28620. };
  28621. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28622. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  28623. #endif
  28624. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28625. #endif
  28626. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28627. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  28628. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28629. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28630. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  28631. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28632. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28633. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  28634. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28635. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28636. /*** Start of inlined file: juce_AudioProcessor.h ***/
  28637. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28638. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28639. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  28640. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28641. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28642. class AudioProcessor;
  28643. /**
  28644. Base class for the component that acts as the GUI for an AudioProcessor.
  28645. Derive your editor component from this class, and create an instance of it
  28646. by overriding the AudioProcessor::createEditor() method.
  28647. @see AudioProcessor, GenericAudioProcessorEditor
  28648. */
  28649. class JUCE_API AudioProcessorEditor : public Component
  28650. {
  28651. protected:
  28652. /** Creates an editor for the specified processor.
  28653. */
  28654. AudioProcessorEditor (AudioProcessor* const owner);
  28655. public:
  28656. /** Destructor. */
  28657. ~AudioProcessorEditor();
  28658. /** Returns a pointer to the processor that this editor represents. */
  28659. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  28660. private:
  28661. AudioProcessor* const owner;
  28662. AudioProcessorEditor (const AudioProcessorEditor&);
  28663. AudioProcessorEditor& operator= (const AudioProcessorEditor&);
  28664. };
  28665. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28666. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  28667. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  28668. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28669. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28670. class AudioProcessor;
  28671. /**
  28672. Base class for listeners that want to know about changes to an AudioProcessor.
  28673. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  28674. @see AudioProcessor
  28675. */
  28676. class JUCE_API AudioProcessorListener
  28677. {
  28678. public:
  28679. /** Destructor. */
  28680. virtual ~AudioProcessorListener() {}
  28681. /** Receives a callback when a parameter is changed.
  28682. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  28683. many audio processors will change their parameter during their audio callback.
  28684. This means that not only has your handler code got to be completely thread-safe,
  28685. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  28686. this event on your message thread, use this callback to trigger an AsyncUpdater
  28687. or ChangeBroadcaster which you can respond to on the message thread.
  28688. */
  28689. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  28690. int parameterIndex,
  28691. float newValue) = 0;
  28692. /** Called to indicate that something else in the plugin has changed, like its
  28693. program, number of parameters, etc.
  28694. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28695. call it during their audio callback. This means that not only has your handler code
  28696. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28697. blocking. If you need to handle this event on your message thread, use this callback
  28698. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28699. message thread.
  28700. */
  28701. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  28702. /** Indicates that a parameter change gesture has started.
  28703. E.g. if the user is dragging a slider, this would be called when they first
  28704. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  28705. called when they release it.
  28706. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28707. call it during their audio callback. This means that not only has your handler code
  28708. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28709. blocking. If you need to handle this event on your message thread, use this callback
  28710. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28711. message thread.
  28712. @see audioProcessorParameterChangeGestureEnd
  28713. */
  28714. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  28715. int parameterIndex);
  28716. /** Indicates that a parameter change gesture has finished.
  28717. E.g. if the user is dragging a slider, this would be called when they release
  28718. the mouse button.
  28719. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28720. call it during their audio callback. This means that not only has your handler code
  28721. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28722. blocking. If you need to handle this event on your message thread, use this callback
  28723. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28724. message thread.
  28725. @see audioPluginParameterChangeGestureStart
  28726. */
  28727. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  28728. int parameterIndex);
  28729. };
  28730. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28731. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  28732. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  28733. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28734. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28735. /**
  28736. A subclass of AudioPlayHead can supply information about the position and
  28737. status of a moving play head during audio playback.
  28738. One of these can be supplied to an AudioProcessor object so that it can find
  28739. out about the position of the audio that it is rendering.
  28740. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  28741. */
  28742. class JUCE_API AudioPlayHead
  28743. {
  28744. protected:
  28745. AudioPlayHead() {}
  28746. public:
  28747. virtual ~AudioPlayHead() {}
  28748. /** Frame rate types. */
  28749. enum FrameRateType
  28750. {
  28751. fps24 = 0,
  28752. fps25 = 1,
  28753. fps2997 = 2,
  28754. fps30 = 3,
  28755. fps2997drop = 4,
  28756. fps30drop = 5,
  28757. fpsUnknown = 99
  28758. };
  28759. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  28760. */
  28761. struct CurrentPositionInfo
  28762. {
  28763. /** The tempo in BPM */
  28764. double bpm;
  28765. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  28766. int timeSigNumerator;
  28767. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  28768. int timeSigDenominator;
  28769. /** The current play position, in seconds from the start of the edit. */
  28770. double timeInSeconds;
  28771. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  28772. double editOriginTime;
  28773. /** The current play position in pulses-per-quarter-note.
  28774. This is the number of quarter notes since the edit start.
  28775. */
  28776. double ppqPosition;
  28777. /** The position of the start of the last bar, in pulses-per-quarter-note.
  28778. This is the number of quarter notes from the start of the edit to the
  28779. start of the current bar.
  28780. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  28781. it's not available, the value will be 0.
  28782. */
  28783. double ppqPositionOfLastBarStart;
  28784. /** The video frame rate, if applicable. */
  28785. FrameRateType frameRate;
  28786. /** True if the transport is currently playing. */
  28787. bool isPlaying;
  28788. /** True if the transport is currently recording.
  28789. (When isRecording is true, then isPlaying will also be true).
  28790. */
  28791. bool isRecording;
  28792. bool operator== (const CurrentPositionInfo& other) const throw();
  28793. bool operator!= (const CurrentPositionInfo& other) const throw();
  28794. void resetToDefault();
  28795. };
  28796. /** Fills-in the given structure with details about the transport's
  28797. position at the start of the current processing block.
  28798. */
  28799. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  28800. };
  28801. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28802. /*** End of inlined file: juce_AudioPlayHead.h ***/
  28803. /**
  28804. Base class for audio processing filters or plugins.
  28805. This is intended to act as a base class of audio filter that is general enough to
  28806. be wrapped as a VST, AU, RTAS, etc, or used internally.
  28807. It is also used by the plugin hosting code as the wrapper around an instance
  28808. of a loaded plugin.
  28809. Derive your filter class from this base class, and if you're building a plugin,
  28810. you should implement a global function called createPluginFilter() which creates
  28811. and returns a new instance of your subclass.
  28812. */
  28813. class JUCE_API AudioProcessor
  28814. {
  28815. protected:
  28816. /** Constructor.
  28817. You can also do your initialisation tasks in the initialiseFilterInfo()
  28818. call, which will be made after this object has been created.
  28819. */
  28820. AudioProcessor();
  28821. public:
  28822. /** Destructor. */
  28823. virtual ~AudioProcessor();
  28824. /** Returns the name of this processor.
  28825. */
  28826. virtual const String getName() const = 0;
  28827. /** Called before playback starts, to let the filter prepare itself.
  28828. The sample rate is the target sample rate, and will remain constant until
  28829. playback stops.
  28830. The estimatedSamplesPerBlock value is a HINT about the typical number of
  28831. samples that will be processed for each callback, but isn't any kind
  28832. of guarantee. The actual block sizes that the host uses may be different
  28833. each time the callback happens, and may be more or less than this value.
  28834. */
  28835. virtual void prepareToPlay (double sampleRate,
  28836. int estimatedSamplesPerBlock) = 0;
  28837. /** Called after playback has stopped, to let the filter free up any resources it
  28838. no longer needs.
  28839. */
  28840. virtual void releaseResources() = 0;
  28841. /** Renders the next block.
  28842. When this method is called, the buffer contains a number of channels which is
  28843. at least as great as the maximum number of input and output channels that
  28844. this filter is using. It will be filled with the filter's input data and
  28845. should be replaced with the filter's output.
  28846. So for example if your filter has 2 input channels and 4 output channels, then
  28847. the buffer will contain 4 channels, the first two being filled with the
  28848. input data. Your filter should read these, do its processing, and replace
  28849. the contents of all 4 channels with its output.
  28850. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  28851. all filled with data, and your filter should overwrite the first 2 of these
  28852. with its output. But be VERY careful not to write anything to the last 3
  28853. channels, as these might be mapped to memory that the host assumes is read-only!
  28854. Note that if you have more outputs than inputs, then only those channels that
  28855. correspond to an input channel are guaranteed to contain sensible data - e.g.
  28856. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  28857. but the last two channels may contain garbage, so you should be careful not to
  28858. let this pass through without being overwritten or cleared.
  28859. Also note that the buffer may have more channels than are strictly necessary,
  28860. but your should only read/write from the ones that your filter is supposed to
  28861. be using.
  28862. The number of samples in these buffers is NOT guaranteed to be the same for every
  28863. callback, and may be more or less than the estimated value given to prepareToPlay().
  28864. Your code must be able to cope with variable-sized blocks, or you're going to get
  28865. clicks and crashes!
  28866. If the filter is receiving a midi input, then the midiMessages array will be filled
  28867. with the midi messages for this block. Each message's timestamp will indicate the
  28868. message's time, as a number of samples from the start of the block.
  28869. Any messages left in the midi buffer when this method has finished are assumed to
  28870. be the filter's midi output. This means that your filter should be careful to
  28871. clear any incoming messages from the array if it doesn't want them to be passed-on.
  28872. Be very careful about what you do in this callback - it's going to be called by
  28873. the audio thread, so any kind of interaction with the UI is absolutely
  28874. out of the question. If you change a parameter in here and need to tell your UI to
  28875. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  28876. the UI components register as listeners, and then call sendChangeMessage() inside the
  28877. processBlock() method to send out an asynchronous message. You could also use
  28878. the AsyncUpdater class in a similar way.
  28879. */
  28880. virtual void processBlock (AudioSampleBuffer& buffer,
  28881. MidiBuffer& midiMessages) = 0;
  28882. /** Returns the current AudioPlayHead object that should be used to find
  28883. out the state and position of the playhead.
  28884. You can call this from your processBlock() method, and use the AudioPlayHead
  28885. object to get the details about the time of the start of the block currently
  28886. being processed.
  28887. If the host hasn't supplied a playhead object, this will return 0.
  28888. */
  28889. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  28890. /** Returns the current sample rate.
  28891. This can be called from your processBlock() method - it's not guaranteed
  28892. to be valid at any other time, and may return 0 if it's unknown.
  28893. */
  28894. double getSampleRate() const throw() { return sampleRate; }
  28895. /** Returns the current typical block size that is being used.
  28896. This can be called from your processBlock() method - it's not guaranteed
  28897. to be valid at any other time.
  28898. Remember it's not the ONLY block size that may be used when calling
  28899. processBlock, it's just the normal one. The actual block sizes used may be
  28900. larger or smaller than this, and will vary between successive calls.
  28901. */
  28902. int getBlockSize() const throw() { return blockSize; }
  28903. /** Returns the number of input channels that the host will be sending the filter.
  28904. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28905. number of channels that your filter would prefer to have, and this method lets
  28906. you know how many the host is actually using.
  28907. Note that this method is only valid during or after the prepareToPlay()
  28908. method call. Until that point, the number of channels will be unknown.
  28909. */
  28910. int getNumInputChannels() const throw() { return numInputChannels; }
  28911. /** Returns the number of output channels that the host will be sending the filter.
  28912. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28913. number of channels that your filter would prefer to have, and this method lets
  28914. you know how many the host is actually using.
  28915. Note that this method is only valid during or after the prepareToPlay()
  28916. method call. Until that point, the number of channels will be unknown.
  28917. */
  28918. int getNumOutputChannels() const throw() { return numOutputChannels; }
  28919. /** Returns the name of one of the input channels, as returned by the host.
  28920. The host might not supply very useful names for channels, and this might be
  28921. something like "1", "2", "left", "right", etc.
  28922. */
  28923. virtual const String getInputChannelName (const int channelIndex) const = 0;
  28924. /** Returns the name of one of the output channels, as returned by the host.
  28925. The host might not supply very useful names for channels, and this might be
  28926. something like "1", "2", "left", "right", etc.
  28927. */
  28928. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  28929. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28930. virtual bool isInputChannelStereoPair (int index) const = 0;
  28931. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28932. virtual bool isOutputChannelStereoPair (int index) const = 0;
  28933. /** This returns the number of samples delay that the filter imposes on the audio
  28934. passing through it.
  28935. The host will call this to find the latency - the filter itself should set this value
  28936. by calling setLatencySamples() as soon as it can during its initialisation.
  28937. */
  28938. int getLatencySamples() const throw() { return latencySamples; }
  28939. /** The filter should call this to set the number of samples delay that it introduces.
  28940. The filter should call this as soon as it can during initialisation, and can call it
  28941. later if the value changes.
  28942. */
  28943. void setLatencySamples (const int newLatency);
  28944. /** Returns true if the processor wants midi messages. */
  28945. virtual bool acceptsMidi() const = 0;
  28946. /** Returns true if the processor produces midi messages. */
  28947. virtual bool producesMidi() const = 0;
  28948. /** This returns a critical section that will automatically be locked while the host
  28949. is calling the processBlock() method.
  28950. Use it from your UI or other threads to lock access to variables that are used
  28951. by the process callback, but obviously be careful not to keep it locked for
  28952. too long, because that could cause stuttering playback. If you need to do something
  28953. that'll take a long time and need the processing to stop while it happens, use the
  28954. suspendProcessing() method instead.
  28955. @see suspendProcessing
  28956. */
  28957. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  28958. /** Enables and disables the processing callback.
  28959. If you need to do something time-consuming on a thread and would like to make sure
  28960. the audio processing callback doesn't happen until you've finished, use this
  28961. to disable the callback and re-enable it again afterwards.
  28962. E.g.
  28963. @code
  28964. void loadNewPatch()
  28965. {
  28966. suspendProcessing (true);
  28967. ..do something that takes ages..
  28968. suspendProcessing (false);
  28969. }
  28970. @endcode
  28971. If the host tries to make an audio callback while processing is suspended, the
  28972. filter will return an empty buffer, but won't block the audio thread like it would
  28973. do if you use the getCallbackLock() critical section to synchronise access.
  28974. If you're going to use this, your processBlock() method must call isSuspended() and
  28975. check whether it's suspended or not. If it is, then it should skip doing any real
  28976. processing, either emitting silence or passing the input through unchanged.
  28977. @see getCallbackLock
  28978. */
  28979. void suspendProcessing (const bool shouldBeSuspended);
  28980. /** Returns true if processing is currently suspended.
  28981. @see suspendProcessing
  28982. */
  28983. bool isSuspended() const throw() { return suspended; }
  28984. /** A plugin can override this to be told when it should reset any playing voices.
  28985. The default implementation does nothing, but a host may call this to tell the
  28986. plugin that it should stop any tails or sounds that have been left running.
  28987. */
  28988. virtual void reset();
  28989. /** Returns true if the processor is being run in an offline mode for rendering.
  28990. If the processor is being run live on realtime signals, this returns false.
  28991. If the mode is unknown, this will assume it's realtime and return false.
  28992. This value may be unreliable until the prepareToPlay() method has been called,
  28993. and could change each time prepareToPlay() is called.
  28994. @see setNonRealtime()
  28995. */
  28996. bool isNonRealtime() const throw() { return nonRealtime; }
  28997. /** Called by the host to tell this processor whether it's being used in a non-realime
  28998. capacity for offline rendering or bouncing.
  28999. Whatever value is passed-in will be
  29000. */
  29001. void setNonRealtime (const bool isNonRealtime) throw();
  29002. /** Creates the filter's UI.
  29003. This can return 0 if you want a UI-less filter, in which case the host may create
  29004. a generic UI that lets the user twiddle the parameters directly.
  29005. If you do want to pass back a component, the component should be created and set to
  29006. the correct size before returning it.
  29007. Remember not to do anything silly like allowing your filter to keep a pointer to
  29008. the component that gets created - it could be deleted later without any warning, which
  29009. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  29010. The correct way to handle the connection between an editor component and its
  29011. filter is to use something like a ChangeBroadcaster so that the editor can
  29012. register itself as a listener, and be told when a change occurs. This lets them
  29013. safely unregister themselves when they are deleted.
  29014. Here are a few things to bear in mind when writing an editor:
  29015. - Initially there won't be an editor, until the user opens one, or they might
  29016. not open one at all. Your filter mustn't rely on it being there.
  29017. - An editor object may be deleted and a replacement one created again at any time.
  29018. - It's safe to assume that an editor will be deleted before its filter.
  29019. */
  29020. virtual AudioProcessorEditor* createEditor() = 0;
  29021. /** Returns the active editor, if there is one.
  29022. Bear in mind this can return 0, even if an editor has previously been
  29023. opened.
  29024. */
  29025. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  29026. /** Returns the active editor, or if there isn't one, it will create one.
  29027. This may call createEditor() internally to create the component.
  29028. */
  29029. AudioProcessorEditor* createEditorIfNeeded();
  29030. /** This must return the correct value immediately after the object has been
  29031. created, and mustn't change the number of parameters later.
  29032. */
  29033. virtual int getNumParameters() = 0;
  29034. /** Returns the name of a particular parameter. */
  29035. virtual const String getParameterName (int parameterIndex) = 0;
  29036. /** Called by the host to find out the value of one of the filter's parameters.
  29037. The host will expect the value returned to be between 0 and 1.0.
  29038. This could be called quite frequently, so try to make your code efficient.
  29039. It's also likely to be called by non-UI threads, so the code in here should
  29040. be thread-aware.
  29041. */
  29042. virtual float getParameter (int parameterIndex) = 0;
  29043. /** Returns the value of a parameter as a text string. */
  29044. virtual const String getParameterText (int parameterIndex) = 0;
  29045. /** The host will call this method to change the value of one of the filter's parameters.
  29046. The host may call this at any time, including during the audio processing
  29047. callback, so the filter has to process this very fast and avoid blocking.
  29048. If you want to set the value of a parameter internally, e.g. from your
  29049. editor component, then don't call this directly - instead, use the
  29050. setParameterNotifyingHost() method, which will also send a message to
  29051. the host telling it about the change. If the message isn't sent, the host
  29052. won't be able to automate your parameters properly.
  29053. The value passed will be between 0 and 1.0.
  29054. */
  29055. virtual void setParameter (int parameterIndex,
  29056. float newValue) = 0;
  29057. /** Your filter can call this when it needs to change one of its parameters.
  29058. This could happen when the editor or some other internal operation changes
  29059. a parameter. This method will call the setParameter() method to change the
  29060. value, and will then send a message to the host telling it about the change.
  29061. Note that to make sure the host correctly handles automation, you should call
  29062. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  29063. tell the host when the user has started and stopped changing the parameter.
  29064. */
  29065. void setParameterNotifyingHost (int parameterIndex,
  29066. float newValue);
  29067. /** Returns true if the host can automate this parameter.
  29068. By default, this returns true for all parameters.
  29069. */
  29070. virtual bool isParameterAutomatable (int parameterIndex) const;
  29071. /** Should return true if this parameter is a "meta" parameter.
  29072. A meta-parameter is a parameter that changes other params. It is used
  29073. by some hosts (e.g. AudioUnit hosts).
  29074. By default this returns false.
  29075. */
  29076. virtual bool isMetaParameter (int parameterIndex) const;
  29077. /** Sends a signal to the host to tell it that the user is about to start changing this
  29078. parameter.
  29079. This allows the host to know when a parameter is actively being held by the user, and
  29080. it may use this information to help it record automation.
  29081. If you call this, it must be matched by a later call to endParameterChangeGesture().
  29082. */
  29083. void beginParameterChangeGesture (int parameterIndex);
  29084. /** Tells the host that the user has finished changing this parameter.
  29085. This allows the host to know when a parameter is actively being held by the user, and
  29086. it may use this information to help it record automation.
  29087. A call to this method must follow a call to beginParameterChangeGesture().
  29088. */
  29089. void endParameterChangeGesture (int parameterIndex);
  29090. /** The filter can call this when something (apart from a parameter value) has changed.
  29091. It sends a hint to the host that something like the program, number of parameters,
  29092. etc, has changed, and that it should update itself.
  29093. */
  29094. void updateHostDisplay();
  29095. /** Returns the number of preset programs the filter supports.
  29096. The value returned must be valid as soon as this object is created, and
  29097. must not change over its lifetime.
  29098. This value shouldn't be less than 1.
  29099. */
  29100. virtual int getNumPrograms() = 0;
  29101. /** Returns the number of the currently active program.
  29102. */
  29103. virtual int getCurrentProgram() = 0;
  29104. /** Called by the host to change the current program.
  29105. */
  29106. virtual void setCurrentProgram (int index) = 0;
  29107. /** Must return the name of a given program. */
  29108. virtual const String getProgramName (int index) = 0;
  29109. /** Called by the host to rename a program.
  29110. */
  29111. virtual void changeProgramName (int index, const String& newName) = 0;
  29112. /** The host will call this method when it wants to save the filter's internal state.
  29113. This must copy any info about the filter's state into the block of memory provided,
  29114. so that the host can store this and later restore it using setStateInformation().
  29115. Note that there's also a getCurrentProgramStateInformation() method, which only
  29116. stores the current program, not the state of the entire filter.
  29117. See also the helper function copyXmlToBinary() for storing settings as XML.
  29118. @see getCurrentProgramStateInformation
  29119. */
  29120. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  29121. /** The host will call this method if it wants to save the state of just the filter's
  29122. current program.
  29123. Unlike getStateInformation, this should only return the current program's state.
  29124. Not all hosts support this, and if you don't implement it, the base class
  29125. method just calls getStateInformation() instead. If you do implement it, be
  29126. sure to also implement getCurrentProgramStateInformation.
  29127. @see getStateInformation, setCurrentProgramStateInformation
  29128. */
  29129. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  29130. /** This must restore the filter's state from a block of data previously created
  29131. using getStateInformation().
  29132. Note that there's also a setCurrentProgramStateInformation() method, which tries
  29133. to restore just the current program, not the state of the entire filter.
  29134. See also the helper function getXmlFromBinary() for loading settings as XML.
  29135. @see setCurrentProgramStateInformation
  29136. */
  29137. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  29138. /** The host will call this method if it wants to restore the state of just the filter's
  29139. current program.
  29140. Not all hosts support this, and if you don't implement it, the base class
  29141. method just calls setStateInformation() instead. If you do implement it, be
  29142. sure to also implement getCurrentProgramStateInformation.
  29143. @see setStateInformation, getCurrentProgramStateInformation
  29144. */
  29145. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  29146. /** Adds a listener that will be called when an aspect of this processor changes. */
  29147. void addListener (AudioProcessorListener* const newListener) throw();
  29148. /** Removes a previously added listener. */
  29149. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  29150. /** Not for public use - this is called before deleting an editor component. */
  29151. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  29152. /** Not for public use - this is called to initialise the processor. */
  29153. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  29154. /** Not for public use - this is called to initialise the processor before playing. */
  29155. void setPlayConfigDetails (const int numIns, const int numOuts,
  29156. const double sampleRate,
  29157. const int blockSize) throw();
  29158. juce_UseDebuggingNewOperator
  29159. protected:
  29160. /** Helper function that just converts an xml element into a binary blob.
  29161. Use this in your filter's getStateInformation() method if you want to
  29162. store its state as xml.
  29163. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  29164. from a binary blob.
  29165. */
  29166. static void copyXmlToBinary (const XmlElement& xml,
  29167. JUCE_NAMESPACE::MemoryBlock& destData);
  29168. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  29169. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  29170. an XmlElement object that the caller must delete when no longer needed.
  29171. */
  29172. static XmlElement* getXmlFromBinary (const void* data,
  29173. const int sizeInBytes);
  29174. /** @internal */
  29175. AudioPlayHead* playHead;
  29176. /** @internal */
  29177. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  29178. private:
  29179. Array <AudioProcessorListener*> listeners;
  29180. AudioProcessorEditor* activeEditor;
  29181. double sampleRate;
  29182. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  29183. bool suspended, nonRealtime;
  29184. CriticalSection callbackLock, listenerLock;
  29185. #if JUCE_DEBUG
  29186. BigInteger changingParams;
  29187. #endif
  29188. AudioProcessor (const AudioProcessor&);
  29189. AudioProcessor& operator= (const AudioProcessor&);
  29190. };
  29191. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  29192. /*** End of inlined file: juce_AudioProcessor.h ***/
  29193. /*** Start of inlined file: juce_PluginDescription.h ***/
  29194. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29195. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29196. /**
  29197. A small class to represent some facts about a particular type of plugin.
  29198. This class is for storing and managing the details about a plugin without
  29199. actually having to load an instance of it.
  29200. A KnownPluginList contains a list of PluginDescription objects.
  29201. @see KnownPluginList
  29202. */
  29203. class JUCE_API PluginDescription
  29204. {
  29205. public:
  29206. PluginDescription() throw();
  29207. PluginDescription (const PluginDescription& other) throw();
  29208. PluginDescription& operator= (const PluginDescription& other) throw();
  29209. ~PluginDescription() throw();
  29210. /** The name of the plugin. */
  29211. String name;
  29212. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  29213. */
  29214. String pluginFormatName;
  29215. /** A category, such as "Dynamics", "Reverbs", etc.
  29216. */
  29217. String category;
  29218. /** The manufacturer. */
  29219. String manufacturerName;
  29220. /** The version. This string doesn't have any particular format. */
  29221. String version;
  29222. /** Either the file containing the plugin module, or some other unique way
  29223. of identifying it.
  29224. E.g. for an AU, this would be an ID string that the component manager
  29225. could use to retrieve the plugin. For a VST, it's the file path.
  29226. */
  29227. String fileOrIdentifier;
  29228. /** The last time the plugin file was changed.
  29229. This is handy when scanning for new or changed plugins.
  29230. */
  29231. Time lastFileModTime;
  29232. /** A unique ID for the plugin.
  29233. Note that this might not be unique between formats, e.g. a VST and some
  29234. other format might actually have the same id.
  29235. @see createIdentifierString
  29236. */
  29237. int uid;
  29238. /** True if the plugin identifies itself as a synthesiser. */
  29239. bool isInstrument;
  29240. /** The number of inputs. */
  29241. int numInputChannels;
  29242. /** The number of outputs. */
  29243. int numOutputChannels;
  29244. /** Returns true if the two descriptions refer the the same plugin.
  29245. This isn't quite as simple as them just having the same file (because of
  29246. shell plugins).
  29247. */
  29248. bool isDuplicateOf (const PluginDescription& other) const;
  29249. /** Returns a string that can be saved and used to uniquely identify the
  29250. plugin again.
  29251. This contains less info than the XML encoding, and is independent of the
  29252. plugin's file location, so can be used to store a plugin ID for use
  29253. across different machines.
  29254. */
  29255. const String createIdentifierString() const throw();
  29256. /** Creates an XML object containing these details.
  29257. @see loadFromXml
  29258. */
  29259. XmlElement* createXml() const;
  29260. /** Reloads the info in this structure from an XML record that was previously
  29261. saved with createXML().
  29262. Returns true if the XML was a valid plugin description.
  29263. */
  29264. bool loadFromXml (const XmlElement& xml);
  29265. juce_UseDebuggingNewOperator
  29266. };
  29267. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29268. /*** End of inlined file: juce_PluginDescription.h ***/
  29269. /**
  29270. Base class for an active instance of a plugin.
  29271. This derives from the AudioProcessor class, and adds some extra functionality
  29272. that helps when wrapping dynamically loaded plugins.
  29273. @see AudioProcessor, AudioPluginFormat
  29274. */
  29275. class JUCE_API AudioPluginInstance : public AudioProcessor
  29276. {
  29277. public:
  29278. /** Destructor.
  29279. Make sure that you delete any UI components that belong to this plugin before
  29280. deleting the plugin.
  29281. */
  29282. virtual ~AudioPluginInstance();
  29283. /** Fills-in the appropriate parts of this plugin description object.
  29284. */
  29285. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  29286. juce_UseDebuggingNewOperator
  29287. protected:
  29288. AudioPluginInstance();
  29289. AudioPluginInstance (const AudioPluginInstance&);
  29290. AudioPluginInstance& operator= (const AudioPluginInstance&);
  29291. };
  29292. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29293. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  29294. class PluginDescription;
  29295. /**
  29296. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  29297. Use the static getNumFormats() and getFormat() calls to find the types
  29298. of format that are available.
  29299. */
  29300. class JUCE_API AudioPluginFormat
  29301. {
  29302. public:
  29303. /** Destructor. */
  29304. virtual ~AudioPluginFormat();
  29305. /** Returns the format name.
  29306. E.g. "VST", "AudioUnit", etc.
  29307. */
  29308. virtual const String getName() const = 0;
  29309. /** This tries to create descriptions for all the plugin types available in
  29310. a binary module file.
  29311. The file will be some kind of DLL or bundle.
  29312. Normally there will only be one type returned, but some plugins
  29313. (e.g. VST shells) can use a single DLL to create a set of different plugin
  29314. subtypes, so in that case, each subtype is returned as a separate object.
  29315. */
  29316. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  29317. const String& fileOrIdentifier) = 0;
  29318. /** Tries to recreate a type from a previously generated PluginDescription.
  29319. @see PluginDescription::createInstance
  29320. */
  29321. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  29322. /** Should do a quick check to see if this file or directory might be a plugin of
  29323. this format.
  29324. This is for searching for potential files, so it shouldn't actually try to
  29325. load the plugin or do anything time-consuming.
  29326. */
  29327. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  29328. /** Returns a readable version of the name of the plugin that this identifier refers to.
  29329. */
  29330. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  29331. /** Checks whether this plugin could possibly be loaded.
  29332. It doesn't actually need to load it, just to check whether the file or component
  29333. still exists.
  29334. */
  29335. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  29336. /** Searches a suggested set of directories for any plugins in this format.
  29337. The path might be ignored, e.g. by AUs, which are found by the OS rather
  29338. than manually.
  29339. */
  29340. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  29341. bool recursive) = 0;
  29342. /** Returns the typical places to look for this kind of plugin.
  29343. Note that if this returns no paths, it means that the format can't be scanned-for
  29344. (i.e. it's an internal format that doesn't live in files)
  29345. */
  29346. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  29347. juce_UseDebuggingNewOperator
  29348. protected:
  29349. AudioPluginFormat() throw();
  29350. AudioPluginFormat (const AudioPluginFormat&);
  29351. AudioPluginFormat& operator= (const AudioPluginFormat&);
  29352. };
  29353. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29354. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  29355. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  29356. /**
  29357. Implements a plugin format manager for AudioUnits.
  29358. */
  29359. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  29360. {
  29361. public:
  29362. AudioUnitPluginFormat();
  29363. ~AudioUnitPluginFormat();
  29364. const String getName() const { return "AudioUnit"; }
  29365. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29366. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29367. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29368. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29369. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29370. bool doesPluginStillExist (const PluginDescription& desc);
  29371. const FileSearchPath getDefaultLocationsToSearch();
  29372. juce_UseDebuggingNewOperator
  29373. private:
  29374. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  29375. AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  29376. };
  29377. #endif
  29378. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  29379. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  29380. #endif
  29381. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29382. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  29383. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29384. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29385. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  29386. // Sorry, this file is just a placeholder at the moment!...
  29387. /**
  29388. Implements a plugin format manager for DirectX plugins.
  29389. */
  29390. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  29391. {
  29392. public:
  29393. DirectXPluginFormat();
  29394. ~DirectXPluginFormat();
  29395. const String getName() const { return "DirectX"; }
  29396. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29397. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29398. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29399. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29400. const FileSearchPath getDefaultLocationsToSearch();
  29401. juce_UseDebuggingNewOperator
  29402. private:
  29403. DirectXPluginFormat (const DirectXPluginFormat&);
  29404. DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  29405. };
  29406. #endif
  29407. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29408. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  29409. #endif
  29410. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29411. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  29412. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29413. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29414. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  29415. // Sorry, this file is just a placeholder at the moment!...
  29416. /**
  29417. Implements a plugin format manager for DirectX plugins.
  29418. */
  29419. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  29420. {
  29421. public:
  29422. LADSPAPluginFormat();
  29423. ~LADSPAPluginFormat();
  29424. const String getName() const { return "LADSPA"; }
  29425. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29426. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29427. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29428. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29429. const FileSearchPath getDefaultLocationsToSearch();
  29430. juce_UseDebuggingNewOperator
  29431. private:
  29432. LADSPAPluginFormat (const LADSPAPluginFormat&);
  29433. LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  29434. };
  29435. #endif
  29436. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29437. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  29438. #endif
  29439. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29440. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  29441. #ifdef __aeffect__
  29442. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29443. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29444. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  29445. events to the list.
  29446. This is used by both the VST hosting code and the plugin wrapper.
  29447. */
  29448. class VSTMidiEventList
  29449. {
  29450. public:
  29451. VSTMidiEventList()
  29452. : numEventsUsed (0), numEventsAllocated (0)
  29453. {
  29454. }
  29455. ~VSTMidiEventList()
  29456. {
  29457. freeEvents();
  29458. }
  29459. void clear()
  29460. {
  29461. numEventsUsed = 0;
  29462. if (events != 0)
  29463. events->numEvents = 0;
  29464. }
  29465. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  29466. {
  29467. ensureSize (numEventsUsed + 1);
  29468. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  29469. events->numEvents = ++numEventsUsed;
  29470. if (numBytes <= 4)
  29471. {
  29472. if (e->type == kVstSysExType)
  29473. {
  29474. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29475. e->type = kVstMidiType;
  29476. e->byteSize = sizeof (VstMidiEvent);
  29477. e->noteLength = 0;
  29478. e->noteOffset = 0;
  29479. e->detune = 0;
  29480. e->noteOffVelocity = 0;
  29481. }
  29482. e->deltaFrames = frameOffset;
  29483. memcpy (e->midiData, midiData, numBytes);
  29484. }
  29485. else
  29486. {
  29487. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  29488. if (se->type == kVstSysExType)
  29489. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  29490. else
  29491. se->sysexDump = (char*) juce_malloc (numBytes);
  29492. memcpy (se->sysexDump, midiData, numBytes);
  29493. se->type = kVstSysExType;
  29494. se->byteSize = sizeof (VstMidiSysexEvent);
  29495. se->deltaFrames = frameOffset;
  29496. se->flags = 0;
  29497. se->dumpBytes = numBytes;
  29498. se->resvd1 = 0;
  29499. se->resvd2 = 0;
  29500. }
  29501. }
  29502. // Handy method to pull the events out of an event buffer supplied by the host
  29503. // or plugin.
  29504. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  29505. {
  29506. for (int i = 0; i < events->numEvents; ++i)
  29507. {
  29508. const VstEvent* const e = events->events[i];
  29509. if (e != 0)
  29510. {
  29511. if (e->type == kVstMidiType)
  29512. {
  29513. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  29514. 4, e->deltaFrames);
  29515. }
  29516. else if (e->type == kVstSysExType)
  29517. {
  29518. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  29519. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  29520. e->deltaFrames);
  29521. }
  29522. }
  29523. }
  29524. }
  29525. void ensureSize (int numEventsNeeded)
  29526. {
  29527. if (numEventsNeeded > numEventsAllocated)
  29528. {
  29529. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  29530. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  29531. if (events == 0)
  29532. events.calloc (size, 1);
  29533. else
  29534. events.realloc (size, 1);
  29535. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  29536. {
  29537. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  29538. (int) sizeof (VstMidiSysexEvent)));
  29539. e->type = kVstMidiType;
  29540. e->byteSize = sizeof (VstMidiEvent);
  29541. events->events[i] = (VstEvent*) e;
  29542. }
  29543. numEventsAllocated = numEventsNeeded;
  29544. }
  29545. }
  29546. void freeEvents()
  29547. {
  29548. if (events != 0)
  29549. {
  29550. for (int i = numEventsAllocated; --i >= 0;)
  29551. {
  29552. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  29553. if (e->type == kVstSysExType)
  29554. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29555. juce_free (e);
  29556. }
  29557. events.free();
  29558. numEventsUsed = 0;
  29559. numEventsAllocated = 0;
  29560. }
  29561. }
  29562. HeapBlock <VstEvents> events;
  29563. private:
  29564. int numEventsUsed, numEventsAllocated;
  29565. };
  29566. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29567. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29568. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  29569. #endif
  29570. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29571. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  29572. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29573. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29574. #if JUCE_PLUGINHOST_VST
  29575. /**
  29576. Implements a plugin format manager for VSTs.
  29577. */
  29578. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  29579. {
  29580. public:
  29581. VSTPluginFormat();
  29582. ~VSTPluginFormat();
  29583. const String getName() const { return "VST"; }
  29584. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29585. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29586. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29587. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29588. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29589. bool doesPluginStillExist (const PluginDescription& desc);
  29590. const FileSearchPath getDefaultLocationsToSearch();
  29591. juce_UseDebuggingNewOperator
  29592. private:
  29593. VSTPluginFormat (const VSTPluginFormat&);
  29594. VSTPluginFormat& operator= (const VSTPluginFormat&);
  29595. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  29596. };
  29597. #endif
  29598. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29599. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  29600. #endif
  29601. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29602. #endif
  29603. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29604. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  29605. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29606. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29607. /**
  29608. This maintains a list of known AudioPluginFormats.
  29609. @see AudioPluginFormat
  29610. */
  29611. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  29612. {
  29613. public:
  29614. AudioPluginFormatManager() throw();
  29615. /** Destructor. */
  29616. ~AudioPluginFormatManager() throw();
  29617. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  29618. /** Adds any formats that it knows about, e.g. VST.
  29619. */
  29620. void addDefaultFormats();
  29621. /** Returns the number of types of format that are available.
  29622. Use getFormat() to get one of them.
  29623. */
  29624. int getNumFormats() throw();
  29625. /** Returns one of the available formats.
  29626. @see getNumFormats
  29627. */
  29628. AudioPluginFormat* getFormat (const int index) throw();
  29629. /** Adds a format to the list.
  29630. The object passed in will be owned and deleted by the manager.
  29631. */
  29632. void addFormat (AudioPluginFormat* const format) throw();
  29633. /** Tries to load the type for this description, by trying all the formats
  29634. that this manager knows about.
  29635. The caller is responsible for deleting the object that is returned.
  29636. If it can't load the plugin, it returns 0 and leaves a message in the
  29637. errorMessage string.
  29638. */
  29639. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  29640. String& errorMessage) const;
  29641. /** Checks that the file or component for this plugin actually still exists.
  29642. (This won't try to load the plugin)
  29643. */
  29644. bool doesPluginStillExist (const PluginDescription& description) const;
  29645. juce_UseDebuggingNewOperator
  29646. private:
  29647. OwnedArray <AudioPluginFormat> formats;
  29648. AudioPluginFormatManager (const AudioPluginFormatManager&);
  29649. AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  29650. };
  29651. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29652. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  29653. #endif
  29654. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29655. #endif
  29656. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29657. /*** Start of inlined file: juce_KnownPluginList.h ***/
  29658. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29659. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29660. /**
  29661. Manages a list of plugin types.
  29662. This can be easily edited, saved and loaded, and used to create instances of
  29663. the plugin types in it.
  29664. @see PluginListComponent
  29665. */
  29666. class JUCE_API KnownPluginList : public ChangeBroadcaster
  29667. {
  29668. public:
  29669. /** Creates an empty list.
  29670. */
  29671. KnownPluginList();
  29672. /** Destructor. */
  29673. ~KnownPluginList();
  29674. /** Clears the list. */
  29675. void clear();
  29676. /** Returns the number of types currently in the list.
  29677. @see getType
  29678. */
  29679. int getNumTypes() const throw() { return types.size(); }
  29680. /** Returns one of the types.
  29681. @see getNumTypes
  29682. */
  29683. PluginDescription* getType (int index) const throw() { return types [index]; }
  29684. /** Looks for a type in the list which comes from this file.
  29685. */
  29686. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  29687. /** Looks for a type in the list which matches a plugin type ID.
  29688. The identifierString parameter must have been created by
  29689. PluginDescription::createIdentifierString().
  29690. */
  29691. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  29692. /** Adds a type manually from its description. */
  29693. bool addType (const PluginDescription& type);
  29694. /** Removes a type. */
  29695. void removeType (int index) throw();
  29696. /** Looks for all types that can be loaded from a given file, and adds them
  29697. to the list.
  29698. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29699. re-tested if it's not already in the list, or if the file's modification
  29700. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29701. false, the file will always be reloaded and tested.
  29702. Returns true if any new types were added, and all the types found in this
  29703. file (even if it was already known and hasn't been re-scanned) get returned
  29704. in the array.
  29705. */
  29706. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  29707. bool dontRescanIfAlreadyInList,
  29708. OwnedArray <PluginDescription>& typesFound,
  29709. AudioPluginFormat& formatToUse);
  29710. /** Returns true if the specified file is already known about and if it
  29711. hasn't been modified since our entry was created.
  29712. */
  29713. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  29714. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  29715. If any types are found in the files, their descriptions are returned in the array.
  29716. */
  29717. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  29718. OwnedArray <PluginDescription>& typesFound);
  29719. /** Sort methods used to change the order of the plugins in the list.
  29720. */
  29721. enum SortMethod
  29722. {
  29723. defaultOrder = 0,
  29724. sortAlphabetically,
  29725. sortByCategory,
  29726. sortByManufacturer,
  29727. sortByFileSystemLocation
  29728. };
  29729. /** Adds all the plugin types to a popup menu so that the user can select one.
  29730. Depending on the sort method, it may add sub-menus for categories,
  29731. manufacturers, etc.
  29732. Use getIndexChosenByMenu() to find out the type that was chosen.
  29733. */
  29734. void addToMenu (PopupMenu& menu,
  29735. const SortMethod sortMethod) const;
  29736. /** Converts a menu item index that has been chosen into its index in this list.
  29737. Returns -1 if it's not an ID that was used.
  29738. @see addToMenu
  29739. */
  29740. int getIndexChosenByMenu (int menuResultCode) const;
  29741. /** Sorts the list. */
  29742. void sort (const SortMethod method);
  29743. /** Creates some XML that can be used to store the state of this list.
  29744. */
  29745. XmlElement* createXml() const;
  29746. /** Recreates the state of this list from its stored XML format.
  29747. */
  29748. void recreateFromXml (const XmlElement& xml);
  29749. juce_UseDebuggingNewOperator
  29750. private:
  29751. OwnedArray <PluginDescription> types;
  29752. KnownPluginList (const KnownPluginList&);
  29753. KnownPluginList& operator= (const KnownPluginList&);
  29754. };
  29755. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29756. /*** End of inlined file: juce_KnownPluginList.h ***/
  29757. #endif
  29758. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29759. #endif
  29760. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29761. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  29762. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29763. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29764. /**
  29765. Scans a directory for plugins, and adds them to a KnownPluginList.
  29766. To use one of these, create it and call scanNextFile() repeatedly, until
  29767. it returns false.
  29768. */
  29769. class JUCE_API PluginDirectoryScanner
  29770. {
  29771. public:
  29772. /**
  29773. Creates a scanner.
  29774. @param listToAddResultsTo this will get the new types added to it.
  29775. @param formatToLookFor this is the type of format that you want to look for
  29776. @param directoriesToSearch the path to search
  29777. @param searchRecursively true to search recursively
  29778. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  29779. be used as a file to store the names of any plugins
  29780. that crash during initialisation. If there are
  29781. any plugins listed in it, then these will always
  29782. be scanned after all other possible files have
  29783. been tried - in this way, even if there's a few
  29784. dodgy plugins in your path, then a couple of rescans
  29785. will still manage to find all the proper plugins.
  29786. It's probably best to choose a file in the user's
  29787. application data directory (alongside your app's
  29788. settings file) for this. The file format it uses
  29789. is just a list of filenames of the modules that
  29790. failed.
  29791. */
  29792. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  29793. AudioPluginFormat& formatToLookFor,
  29794. FileSearchPath directoriesToSearch,
  29795. bool searchRecursively,
  29796. const File& deadMansPedalFile);
  29797. /** Destructor. */
  29798. ~PluginDirectoryScanner();
  29799. /** Tries the next likely-looking file.
  29800. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29801. re-tested if it's not already in the list, or if the file's modification
  29802. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29803. false, the file will always be reloaded and tested.
  29804. Returns false when there are no more files to try.
  29805. */
  29806. bool scanNextFile (bool dontRescanIfAlreadyInList);
  29807. /** Returns the description of the plugin that will be scanned during the next
  29808. call to scanNextFile().
  29809. This is handy if you want to show the user which file is currently getting
  29810. scanned.
  29811. */
  29812. const String getNextPluginFileThatWillBeScanned() const throw();
  29813. /** Returns the estimated progress, between 0 and 1.
  29814. */
  29815. float getProgress() const { return progress; }
  29816. /** This returns a list of all the filenames of things that looked like being
  29817. a plugin file, but which failed to open for some reason.
  29818. */
  29819. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  29820. juce_UseDebuggingNewOperator
  29821. private:
  29822. KnownPluginList& list;
  29823. AudioPluginFormat& format;
  29824. StringArray filesOrIdentifiersToScan;
  29825. File deadMansPedalFile;
  29826. StringArray failedFiles;
  29827. int nextIndex;
  29828. float progress;
  29829. const StringArray getDeadMansPedalFile() throw();
  29830. void setDeadMansPedalFile (const StringArray& newContents) throw();
  29831. PluginDirectoryScanner (const PluginDirectoryScanner&);
  29832. PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  29833. };
  29834. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29835. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  29836. #endif
  29837. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29838. /*** Start of inlined file: juce_PluginListComponent.h ***/
  29839. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29840. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29841. /*** Start of inlined file: juce_ListBox.h ***/
  29842. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  29843. #define __JUCE_LISTBOX_JUCEHEADER__
  29844. class ListViewport;
  29845. /**
  29846. A subclass of this is used to drive a ListBox.
  29847. @see ListBox
  29848. */
  29849. class JUCE_API ListBoxModel
  29850. {
  29851. public:
  29852. /** Destructor. */
  29853. virtual ~ListBoxModel() {}
  29854. /** This has to return the number of items in the list.
  29855. @see ListBox::getNumRows()
  29856. */
  29857. virtual int getNumRows() = 0;
  29858. /** This method must be implemented to draw a row of the list.
  29859. */
  29860. virtual void paintListBoxItem (int rowNumber,
  29861. Graphics& g,
  29862. int width, int height,
  29863. bool rowIsSelected) = 0;
  29864. /** This is used to create or update a custom component to go in a row of the list.
  29865. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  29866. and handle mouse clicks with listBoxItemClicked().
  29867. This method will be called whenever a custom component might need to be updated - e.g.
  29868. when the table is changed, or TableListBox::updateContent() is called.
  29869. If you don't need a custom component for the specified row, then return 0.
  29870. If you do want a custom component, and the existingComponentToUpdate is null, then
  29871. this method must create a suitable new component and return it.
  29872. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  29873. by this method. In this case, the method must either update it to make sure it's correctly representing
  29874. the given row (which may be different from the one that the component was created for), or it can
  29875. delete this component and return a new one.
  29876. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  29877. */
  29878. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  29879. Component* existingComponentToUpdate);
  29880. /** This can be overridden to react to the user clicking on a row.
  29881. @see listBoxItemDoubleClicked
  29882. */
  29883. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  29884. /** This can be overridden to react to the user double-clicking on a row.
  29885. @see listBoxItemClicked
  29886. */
  29887. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  29888. /** This can be overridden to react to the user double-clicking on a part of the list where
  29889. there are no rows.
  29890. @see listBoxItemClicked
  29891. */
  29892. virtual void backgroundClicked();
  29893. /** Override this to be informed when rows are selected or deselected.
  29894. This will be called whenever a row is selected or deselected. If a range of
  29895. rows is selected all at once, this will just be called once for that event.
  29896. @param lastRowSelected the last row that the user selected. If no
  29897. rows are currently selected, this may be -1.
  29898. */
  29899. virtual void selectedRowsChanged (int lastRowSelected);
  29900. /** Override this to be informed when the delete key is pressed.
  29901. If no rows are selected when they press the key, this won't be called.
  29902. @param lastRowSelected the last row that had been selected when they pressed the
  29903. key - if there are multiple selections, this might not be
  29904. very useful
  29905. */
  29906. virtual void deleteKeyPressed (int lastRowSelected);
  29907. /** Override this to be informed when the return key is pressed.
  29908. If no rows are selected when they press the key, this won't be called.
  29909. @param lastRowSelected the last row that had been selected when they pressed the
  29910. key - if there are multiple selections, this might not be
  29911. very useful
  29912. */
  29913. virtual void returnKeyPressed (int lastRowSelected);
  29914. /** Override this to be informed when the list is scrolled.
  29915. This might be caused by the user moving the scrollbar, or by programmatic changes
  29916. to the list position.
  29917. */
  29918. virtual void listWasScrolled();
  29919. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  29920. If this returns a non-empty name then when the user drags a row, the listbox will
  29921. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  29922. a drag-and-drop operation, using this string as the source description, with the listbox
  29923. itself as the source component.
  29924. @see DragAndDropContainer::startDragging
  29925. */
  29926. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  29927. /** You can override this to provide tool tips for specific rows.
  29928. @see TooltipClient
  29929. */
  29930. virtual const String getTooltipForRow (int row);
  29931. };
  29932. /**
  29933. A list of items that can be scrolled vertically.
  29934. To create a list, you'll need to create a subclass of ListBoxModel. This can
  29935. either paint each row of the list and respond to events via callbacks, or for
  29936. more specialised tasks, it can supply a custom component to fill each row.
  29937. @see ComboBox, TableListBox
  29938. */
  29939. class JUCE_API ListBox : public Component,
  29940. public SettableTooltipClient
  29941. {
  29942. public:
  29943. /** Creates a ListBox.
  29944. The model pointer passed-in can be null, in which case you can set it later
  29945. with setModel().
  29946. */
  29947. ListBox (const String& componentName,
  29948. ListBoxModel* model);
  29949. /** Destructor. */
  29950. ~ListBox();
  29951. /** Changes the current data model to display. */
  29952. void setModel (ListBoxModel* newModel);
  29953. /** Returns the current list model. */
  29954. ListBoxModel* getModel() const throw() { return model; }
  29955. /** Causes the list to refresh its content.
  29956. Call this when the number of rows in the list changes, or if you want it
  29957. to call refreshComponentForRow() on all the row components.
  29958. Be careful not to call it from a different thread, though, as it's not
  29959. thread-safe.
  29960. */
  29961. void updateContent();
  29962. /** Turns on multiple-selection of rows.
  29963. By default this is disabled.
  29964. When your row component gets clicked you'll need to call the
  29965. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  29966. clicked and to get it to do the appropriate selection based on whether
  29967. the ctrl/shift keys are held down.
  29968. */
  29969. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  29970. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  29971. This function is here primarily for the ComboBox class to use, but might be
  29972. useful for some other purpose too.
  29973. */
  29974. void setMouseMoveSelectsRows (bool shouldSelect);
  29975. /** Selects a row.
  29976. If the row is already selected, this won't do anything.
  29977. @param rowNumber the row to select
  29978. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  29979. the selected row is off-screen, it'll scroll to make
  29980. sure that row is on-screen
  29981. @param deselectOthersFirst if true and there are multiple selections, these will
  29982. first be deselected before this item is selected
  29983. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  29984. deselectAllRows, selectRangeOfRows
  29985. */
  29986. void selectRow (int rowNumber,
  29987. bool dontScrollToShowThisRow = false,
  29988. bool deselectOthersFirst = true);
  29989. /** Selects a set of rows.
  29990. This will add these rows to the current selection, so you might need to
  29991. clear the current selection first with deselectAllRows()
  29992. @param firstRow the first row to select (inclusive)
  29993. @param lastRow the last row to select (inclusive)
  29994. */
  29995. void selectRangeOfRows (int firstRow,
  29996. int lastRow);
  29997. /** Deselects a row.
  29998. If it's not currently selected, this will do nothing.
  29999. @see selectRow, deselectAllRows
  30000. */
  30001. void deselectRow (int rowNumber);
  30002. /** Deselects any currently selected rows.
  30003. @see deselectRow
  30004. */
  30005. void deselectAllRows();
  30006. /** Selects or deselects a row.
  30007. If the row's currently selected, this deselects it, and vice-versa.
  30008. */
  30009. void flipRowSelection (int rowNumber);
  30010. /** Returns a sparse set indicating the rows that are currently selected.
  30011. @see setSelectedRows
  30012. */
  30013. const SparseSet<int> getSelectedRows() const;
  30014. /** Sets the rows that should be selected, based on an explicit set of ranges.
  30015. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  30016. method will be called. If it's false, no notification will be sent to the model.
  30017. @see getSelectedRows
  30018. */
  30019. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  30020. bool sendNotificationEventToModel = true);
  30021. /** Checks whether a row is selected.
  30022. */
  30023. bool isRowSelected (int rowNumber) const;
  30024. /** Returns the number of rows that are currently selected.
  30025. @see getSelectedRow, isRowSelected, getLastRowSelected
  30026. */
  30027. int getNumSelectedRows() const;
  30028. /** Returns the row number of a selected row.
  30029. This will return the row number of the Nth selected row. The row numbers returned will
  30030. be sorted in order from low to high.
  30031. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  30032. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  30033. selected
  30034. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  30035. */
  30036. int getSelectedRow (int index = 0) const;
  30037. /** Returns the last row that the user selected.
  30038. This isn't the same as the highest row number that is currently selected - if the user
  30039. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  30040. If nothing is selected, it will return -1.
  30041. */
  30042. int getLastRowSelected() const;
  30043. /** Multiply-selects rows based on the modifier keys.
  30044. If no modifier keys are down, this will select the given row and
  30045. deselect any others.
  30046. If the ctrl (or command on the Mac) key is down, it'll flip the
  30047. state of the selected row.
  30048. If the shift key is down, it'll select up to the given row from the
  30049. last row selected.
  30050. @see selectRow
  30051. */
  30052. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  30053. const ModifierKeys& modifiers);
  30054. /** Scrolls the list to a particular position.
  30055. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  30056. 1.0 scrolls to the bottom.
  30057. If the total number of rows all fit onto the screen at once, then this
  30058. method won't do anything.
  30059. @see getVerticalPosition
  30060. */
  30061. void setVerticalPosition (double newProportion);
  30062. /** Returns the current vertical position as a proportion of the total.
  30063. This can be used in conjunction with setVerticalPosition() to save and restore
  30064. the list's position. It returns a value in the range 0 to 1.
  30065. @see setVerticalPosition
  30066. */
  30067. double getVerticalPosition() const;
  30068. /** Scrolls if necessary to make sure that a particular row is visible.
  30069. */
  30070. void scrollToEnsureRowIsOnscreen (int row);
  30071. /** Returns a pointer to the scrollbar.
  30072. (Unlikely to be useful for most people).
  30073. */
  30074. ScrollBar* getVerticalScrollBar() const throw();
  30075. /** Returns a pointer to the scrollbar.
  30076. (Unlikely to be useful for most people).
  30077. */
  30078. ScrollBar* getHorizontalScrollBar() const throw();
  30079. /** Finds the row index that contains a given x,y position.
  30080. The position is relative to the ListBox's top-left.
  30081. If no row exists at this position, the method will return -1.
  30082. @see getComponentForRowNumber
  30083. */
  30084. int getRowContainingPosition (int x, int y) const throw();
  30085. /** Finds a row index that would be the most suitable place to insert a new
  30086. item for a given position.
  30087. This is useful when the user is e.g. dragging and dropping onto the listbox,
  30088. because it lets you easily choose the best position to insert the item that
  30089. they drop, based on where they drop it.
  30090. If the position is out of range, this will return -1. If the position is
  30091. beyond the end of the list, it will return getNumRows() to indicate the end
  30092. of the list.
  30093. @see getComponentForRowNumber
  30094. */
  30095. int getInsertionIndexForPosition (int x, int y) const throw();
  30096. /** Returns the position of one of the rows, relative to the top-left of
  30097. the listbox.
  30098. This may be off-screen, and the range of the row number that is passed-in is
  30099. not checked to see if it's a valid row.
  30100. */
  30101. const Rectangle<int> getRowPosition (int rowNumber,
  30102. bool relativeToComponentTopLeft) const throw();
  30103. /** Finds the row component for a given row in the list.
  30104. The component returned will have been created using createRowComponent().
  30105. If the component for this row is off-screen or if the row is out-of-range,
  30106. this will return 0.
  30107. @see getRowContainingPosition
  30108. */
  30109. Component* getComponentForRowNumber (int rowNumber) const throw();
  30110. /** Returns the row number that the given component represents.
  30111. If the component isn't one of the list's rows, this will return -1.
  30112. */
  30113. int getRowNumberOfComponent (Component* rowComponent) const throw();
  30114. /** Returns the width of a row (which may be less than the width of this component
  30115. if there's a scrollbar).
  30116. */
  30117. int getVisibleRowWidth() const throw();
  30118. /** Sets the height of each row in the list.
  30119. The default height is 22 pixels.
  30120. @see getRowHeight
  30121. */
  30122. void setRowHeight (int newHeight);
  30123. /** Returns the height of a row in the list.
  30124. @see setRowHeight
  30125. */
  30126. int getRowHeight() const throw() { return rowHeight; }
  30127. /** Returns the number of rows actually visible.
  30128. This is the number of whole rows which will fit on-screen, so the value might
  30129. be more than the actual number of rows in the list.
  30130. */
  30131. int getNumRowsOnScreen() const throw();
  30132. /** A set of colour IDs to use to change the colour of various aspects of the label.
  30133. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30134. methods.
  30135. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30136. */
  30137. enum ColourIds
  30138. {
  30139. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  30140. Make this transparent if you don't want the background to be filled. */
  30141. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  30142. Make this transparent to not have an outline. */
  30143. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  30144. };
  30145. /** Sets the thickness of a border that will be drawn around the box.
  30146. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  30147. @see outlineColourId
  30148. */
  30149. void setOutlineThickness (int outlineThickness);
  30150. /** Returns the thickness of outline that will be drawn around the listbox.
  30151. @see setOutlineColour
  30152. */
  30153. int getOutlineThickness() const throw() { return outlineThickness; }
  30154. /** Sets a component that the list should use as a header.
  30155. This will position the given component at the top of the list, maintaining the
  30156. height of the component passed-in, but rescaling it horizontally to match the
  30157. width of the items in the listbox.
  30158. The component will be deleted when setHeaderComponent() is called with a
  30159. different component, or when the listbox is deleted.
  30160. */
  30161. void setHeaderComponent (Component* newHeaderComponent);
  30162. /** Changes the width of the rows in the list.
  30163. This can be used to make the list's row components wider than the list itself - the
  30164. width of the rows will be either the width of the list or this value, whichever is
  30165. greater, and if the rows become wider than the list, a horizontal scrollbar will
  30166. appear.
  30167. The default value for this is 0, which means that the rows will always
  30168. be the same width as the list.
  30169. */
  30170. void setMinimumContentWidth (int newMinimumWidth);
  30171. /** Returns the space currently available for the row items, taking into account
  30172. borders, scrollbars, etc.
  30173. */
  30174. int getVisibleContentWidth() const throw();
  30175. /** Repaints one of the rows.
  30176. This is a lightweight alternative to calling updateContent, and just causes a
  30177. repaint of the row's area.
  30178. */
  30179. void repaintRow (int rowNumber) throw();
  30180. /** This fairly obscure method creates an image that just shows the currently
  30181. selected row components.
  30182. It's a handy method for doing drag-and-drop, as it can be passed to the
  30183. DragAndDropContainer for use as the drag image.
  30184. Note that it will make the row components temporarily invisible, so if you're
  30185. using custom components this could affect them if they're sensitive to that
  30186. sort of thing.
  30187. @see Component::createComponentSnapshot
  30188. */
  30189. const Image createSnapshotOfSelectedRows (int& x, int& y);
  30190. /** Returns the viewport that this ListBox uses.
  30191. You may need to use this to change parameters such as whether scrollbars
  30192. are shown, etc.
  30193. */
  30194. Viewport* getViewport() const throw();
  30195. /** @internal */
  30196. bool keyPressed (const KeyPress& key);
  30197. /** @internal */
  30198. bool keyStateChanged (bool isKeyDown);
  30199. /** @internal */
  30200. void paint (Graphics& g);
  30201. /** @internal */
  30202. void paintOverChildren (Graphics& g);
  30203. /** @internal */
  30204. void resized();
  30205. /** @internal */
  30206. void visibilityChanged();
  30207. /** @internal */
  30208. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  30209. /** @internal */
  30210. void mouseMove (const MouseEvent&);
  30211. /** @internal */
  30212. void mouseExit (const MouseEvent&);
  30213. /** @internal */
  30214. void mouseUp (const MouseEvent&);
  30215. /** @internal */
  30216. void colourChanged();
  30217. /** @internal */
  30218. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  30219. juce_UseDebuggingNewOperator
  30220. private:
  30221. friend class ListViewport;
  30222. friend class TableListBox;
  30223. ListBoxModel* model;
  30224. ScopedPointer<ListViewport> viewport;
  30225. ScopedPointer<Component> headerComponent;
  30226. int totalItems, rowHeight, minimumRowWidth;
  30227. int outlineThickness;
  30228. int lastRowSelected;
  30229. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  30230. SparseSet <int> selected;
  30231. void selectRowInternal (int rowNumber,
  30232. bool dontScrollToShowThisRow,
  30233. bool deselectOthersFirst,
  30234. bool isMouseClick);
  30235. ListBox (const ListBox&);
  30236. ListBox& operator= (const ListBox&);
  30237. };
  30238. #endif // __JUCE_LISTBOX_JUCEHEADER__
  30239. /*** End of inlined file: juce_ListBox.h ***/
  30240. /*** Start of inlined file: juce_TextButton.h ***/
  30241. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30242. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  30243. /**
  30244. A button that uses the standard lozenge-shaped background with a line of
  30245. text on it.
  30246. @see Button, DrawableButton
  30247. */
  30248. class JUCE_API TextButton : public Button
  30249. {
  30250. public:
  30251. /** Creates a TextButton.
  30252. @param buttonName the text to put in the button (the component's name is also
  30253. initially set to this string, but these can be changed later
  30254. using the setName() and setButtonText() methods)
  30255. @param toolTip an optional string to use as a toolip
  30256. @see Button
  30257. */
  30258. TextButton (const String& buttonName = String::empty,
  30259. const String& toolTip = String::empty);
  30260. /** Destructor. */
  30261. ~TextButton();
  30262. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30263. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30264. methods.
  30265. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30266. */
  30267. enum ColourIds
  30268. {
  30269. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  30270. 'off'). The look-and-feel class might re-interpret this to add
  30271. effects, etc. */
  30272. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  30273. 'on'). The look-and-feel class might re-interpret this to add
  30274. effects, etc. */
  30275. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  30276. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  30277. };
  30278. /** Resizes the button to fit neatly around its current text.
  30279. If newHeight is >= 0, the button's height will be changed to this
  30280. value. If it's less than zero, its height will be unaffected.
  30281. */
  30282. void changeWidthToFitText (int newHeight = -1);
  30283. /** This can be overridden to use different fonts than the default one.
  30284. Note that you'll need to set the font's size appropriately, too.
  30285. */
  30286. virtual const Font getFont();
  30287. juce_UseDebuggingNewOperator
  30288. protected:
  30289. /** @internal */
  30290. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  30291. /** @internal */
  30292. void colourChanged();
  30293. private:
  30294. TextButton (const TextButton&);
  30295. TextButton& operator= (const TextButton&);
  30296. };
  30297. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  30298. /*** End of inlined file: juce_TextButton.h ***/
  30299. /**
  30300. A component displaying a list of plugins, with options to scan for them,
  30301. add, remove and sort them.
  30302. */
  30303. class JUCE_API PluginListComponent : public Component,
  30304. public ListBoxModel,
  30305. public ChangeListener,
  30306. public ButtonListener,
  30307. public Timer
  30308. {
  30309. public:
  30310. /**
  30311. Creates the list component.
  30312. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  30313. The properties file, if supplied, is used to store the user's last search paths.
  30314. */
  30315. PluginListComponent (KnownPluginList& listToRepresent,
  30316. const File& deadMansPedalFile,
  30317. PropertiesFile* propertiesToUse);
  30318. /** Destructor. */
  30319. ~PluginListComponent();
  30320. /** @internal */
  30321. void resized();
  30322. /** @internal */
  30323. bool isInterestedInFileDrag (const StringArray& files);
  30324. /** @internal */
  30325. void filesDropped (const StringArray& files, int, int);
  30326. /** @internal */
  30327. int getNumRows();
  30328. /** @internal */
  30329. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  30330. /** @internal */
  30331. void deleteKeyPressed (int lastRowSelected);
  30332. /** @internal */
  30333. void buttonClicked (Button* b);
  30334. /** @internal */
  30335. void changeListenerCallback (void*);
  30336. /** @internal */
  30337. void timerCallback();
  30338. juce_UseDebuggingNewOperator
  30339. private:
  30340. KnownPluginList& list;
  30341. File deadMansPedalFile;
  30342. ListBox* listBox;
  30343. TextButton* optionsButton;
  30344. PropertiesFile* propertiesToUse;
  30345. int typeToScan;
  30346. void scanFor (AudioPluginFormat* format);
  30347. PluginListComponent (const PluginListComponent&);
  30348. PluginListComponent& operator= (const PluginListComponent&);
  30349. };
  30350. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  30351. /*** End of inlined file: juce_PluginListComponent.h ***/
  30352. #endif
  30353. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  30354. #endif
  30355. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  30356. #endif
  30357. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  30358. #endif
  30359. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30360. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  30361. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30362. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30363. /**
  30364. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  30365. Use one of these objects if you want to wire-up a set of AudioProcessors
  30366. and play back the result.
  30367. Processors can be added to the graph as "nodes" using addNode(), and once
  30368. added, you can connect any of their input or output channels to other
  30369. nodes using addConnection().
  30370. To play back a graph through an audio device, you might want to use an
  30371. AudioProcessorPlayer object.
  30372. */
  30373. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  30374. public AsyncUpdater
  30375. {
  30376. public:
  30377. /** Creates an empty graph.
  30378. */
  30379. AudioProcessorGraph();
  30380. /** Destructor.
  30381. Any processor objects that have been added to the graph will also be deleted.
  30382. */
  30383. ~AudioProcessorGraph();
  30384. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  30385. To create a node, call AudioProcessorGraph::addNode().
  30386. */
  30387. class JUCE_API Node : public ReferenceCountedObject
  30388. {
  30389. public:
  30390. /** Destructor.
  30391. */
  30392. ~Node();
  30393. /** The ID number assigned to this node.
  30394. This is assigned by the graph that owns it, and can't be changed.
  30395. */
  30396. const uint32 id;
  30397. /** The actual processor object that this node represents.
  30398. */
  30399. AudioProcessor* const processor;
  30400. /** A set of user-definable properties that are associated with this node.
  30401. This can be used to attach values to the node for whatever purpose seems
  30402. useful. For example, you might store an x and y position if your application
  30403. is displaying the nodes on-screen.
  30404. */
  30405. NamedValueSet properties;
  30406. /** A convenient typedef for referring to a pointer to a node object.
  30407. */
  30408. typedef ReferenceCountedObjectPtr <Node> Ptr;
  30409. juce_UseDebuggingNewOperator
  30410. private:
  30411. friend class AudioProcessorGraph;
  30412. bool isPrepared;
  30413. Node (uint32 id, AudioProcessor* processor);
  30414. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  30415. void unprepare();
  30416. Node (const Node&);
  30417. Node& operator= (const Node&);
  30418. };
  30419. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  30420. To create a connection, use AudioProcessorGraph::addConnection().
  30421. */
  30422. struct JUCE_API Connection
  30423. {
  30424. public:
  30425. /** The ID number of the node which is the input source for this connection.
  30426. @see AudioProcessorGraph::getNodeForId
  30427. */
  30428. uint32 sourceNodeId;
  30429. /** The index of the output channel of the source node from which this
  30430. connection takes its data.
  30431. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30432. it is referring to the source node's midi output. Otherwise, it is the zero-based
  30433. index of an audio output channel in the source node.
  30434. */
  30435. int sourceChannelIndex;
  30436. /** The ID number of the node which is the destination for this connection.
  30437. @see AudioProcessorGraph::getNodeForId
  30438. */
  30439. uint32 destNodeId;
  30440. /** The index of the input channel of the destination node to which this
  30441. connection delivers its data.
  30442. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30443. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  30444. index of an audio input channel in the destination node.
  30445. */
  30446. int destChannelIndex;
  30447. juce_UseDebuggingNewOperator
  30448. private:
  30449. };
  30450. /** Deletes all nodes and connections from this graph.
  30451. Any processor objects in the graph will be deleted.
  30452. */
  30453. void clear();
  30454. /** Returns the number of nodes in the graph. */
  30455. int getNumNodes() const { return nodes.size(); }
  30456. /** Returns a pointer to one of the nodes in the graph.
  30457. This will return 0 if the index is out of range.
  30458. @see getNodeForId
  30459. */
  30460. Node* getNode (const int index) const { return nodes [index]; }
  30461. /** Searches the graph for a node with the given ID number and returns it.
  30462. If no such node was found, this returns 0.
  30463. @see getNode
  30464. */
  30465. Node* getNodeForId (const uint32 nodeId) const;
  30466. /** Adds a node to the graph.
  30467. This creates a new node in the graph, for the specified processor. Once you have
  30468. added a processor to the graph, the graph owns it and will delete it later when
  30469. it is no longer needed.
  30470. The optional nodeId parameter lets you specify an ID to use for the node, but
  30471. if the value is already in use, this new node will overwrite the old one.
  30472. If this succeeds, it returns a pointer to the newly-created node.
  30473. */
  30474. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  30475. /** Deletes a node within the graph which has the specified ID.
  30476. This will also delete any connections that are attached to this node.
  30477. */
  30478. bool removeNode (uint32 nodeId);
  30479. /** Returns the number of connections in the graph. */
  30480. int getNumConnections() const { return connections.size(); }
  30481. /** Returns a pointer to one of the connections in the graph. */
  30482. const Connection* getConnection (int index) const { return connections [index]; }
  30483. /** Searches for a connection between some specified channels.
  30484. If no such connection is found, this returns 0.
  30485. */
  30486. const Connection* getConnectionBetween (uint32 sourceNodeId,
  30487. int sourceChannelIndex,
  30488. uint32 destNodeId,
  30489. int destChannelIndex) const;
  30490. /** Returns true if there is a connection between any of the channels of
  30491. two specified nodes.
  30492. */
  30493. bool isConnected (uint32 possibleSourceNodeId,
  30494. uint32 possibleDestNodeId) const;
  30495. /** Returns true if it would be legal to connect the specified points.
  30496. */
  30497. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  30498. uint32 destNodeId, int destChannelIndex) const;
  30499. /** Attempts to connect two specified channels of two nodes.
  30500. If this isn't allowed (e.g. because you're trying to connect a midi channel
  30501. to an audio one or other such nonsense), then it'll return false.
  30502. */
  30503. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30504. uint32 destNodeId, int destChannelIndex);
  30505. /** Deletes the connection with the specified index.
  30506. Returns true if a connection was actually deleted.
  30507. */
  30508. void removeConnection (int index);
  30509. /** Deletes any connection between two specified points.
  30510. Returns true if a connection was actually deleted.
  30511. */
  30512. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30513. uint32 destNodeId, int destChannelIndex);
  30514. /** Removes all connections from the specified node.
  30515. */
  30516. bool disconnectNode (uint32 nodeId);
  30517. /** Performs a sanity checks of all the connections.
  30518. This might be useful if some of the processors are doing things like changing
  30519. their channel counts, which could render some connections obsolete.
  30520. */
  30521. bool removeIllegalConnections();
  30522. /** A special number that represents the midi channel of a node.
  30523. This is used as a channel index value if you want to refer to the midi input
  30524. or output instead of an audio channel.
  30525. */
  30526. static const int midiChannelIndex;
  30527. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  30528. in order to use the audio that comes into and out of the graph itself.
  30529. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  30530. node in the graph which delivers the audio that is coming into the parent
  30531. graph. This allows you to stream the data to other nodes and process the
  30532. incoming audio.
  30533. Likewise, one of these in "output" mode can be sent data which it will add to
  30534. the sum of data being sent to the graph's output.
  30535. @see AudioProcessorGraph
  30536. */
  30537. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  30538. {
  30539. public:
  30540. /** Specifies the mode in which this processor will operate.
  30541. */
  30542. enum IODeviceType
  30543. {
  30544. audioInputNode, /**< In this mode, the processor has output channels
  30545. representing all the audio input channels that are
  30546. coming into its parent audio graph. */
  30547. audioOutputNode, /**< In this mode, the processor has input channels
  30548. representing all the audio output channels that are
  30549. going out of its parent audio graph. */
  30550. midiInputNode, /**< In this mode, the processor has a midi output which
  30551. delivers the same midi data that is arriving at its
  30552. parent graph. */
  30553. midiOutputNode /**< In this mode, the processor has a midi input and
  30554. any data sent to it will be passed out of the parent
  30555. graph. */
  30556. };
  30557. /** Returns the mode of this processor. */
  30558. IODeviceType getType() const { return type; }
  30559. /** Returns the parent graph to which this processor belongs, or 0 if it
  30560. hasn't yet been added to one. */
  30561. AudioProcessorGraph* getParentGraph() const { return graph; }
  30562. /** True if this is an audio or midi input. */
  30563. bool isInput() const;
  30564. /** True if this is an audio or midi output. */
  30565. bool isOutput() const;
  30566. AudioGraphIOProcessor (const IODeviceType type);
  30567. ~AudioGraphIOProcessor();
  30568. const String getName() const;
  30569. void fillInPluginDescription (PluginDescription& d) const;
  30570. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30571. void releaseResources();
  30572. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30573. const String getInputChannelName (const int channelIndex) const;
  30574. const String getOutputChannelName (const int channelIndex) const;
  30575. bool isInputChannelStereoPair (int index) const;
  30576. bool isOutputChannelStereoPair (int index) const;
  30577. bool acceptsMidi() const;
  30578. bool producesMidi() const;
  30579. AudioProcessorEditor* createEditor();
  30580. int getNumParameters();
  30581. const String getParameterName (int);
  30582. float getParameter (int);
  30583. const String getParameterText (int);
  30584. void setParameter (int, float);
  30585. int getNumPrograms();
  30586. int getCurrentProgram();
  30587. void setCurrentProgram (int);
  30588. const String getProgramName (int);
  30589. void changeProgramName (int, const String&);
  30590. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30591. void setStateInformation (const void* data, int sizeInBytes);
  30592. /** @internal */
  30593. void setParentGraph (AudioProcessorGraph* graph);
  30594. juce_UseDebuggingNewOperator
  30595. private:
  30596. const IODeviceType type;
  30597. AudioProcessorGraph* graph;
  30598. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  30599. AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  30600. };
  30601. // AudioProcessor methods:
  30602. const String getName() const;
  30603. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30604. void releaseResources();
  30605. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30606. const String getInputChannelName (const int channelIndex) const;
  30607. const String getOutputChannelName (const int channelIndex) const;
  30608. bool isInputChannelStereoPair (int index) const;
  30609. bool isOutputChannelStereoPair (int index) const;
  30610. bool acceptsMidi() const;
  30611. bool producesMidi() const;
  30612. AudioProcessorEditor* createEditor() { return 0; }
  30613. int getNumParameters() { return 0; }
  30614. const String getParameterName (int) { return String::empty; }
  30615. float getParameter (int) { return 0; }
  30616. const String getParameterText (int) { return String::empty; }
  30617. void setParameter (int, float) { }
  30618. int getNumPrograms() { return 0; }
  30619. int getCurrentProgram() { return 0; }
  30620. void setCurrentProgram (int) { }
  30621. const String getProgramName (int) { return String::empty; }
  30622. void changeProgramName (int, const String&) { }
  30623. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30624. void setStateInformation (const void* data, int sizeInBytes);
  30625. /** @internal */
  30626. void handleAsyncUpdate();
  30627. juce_UseDebuggingNewOperator
  30628. private:
  30629. ReferenceCountedArray <Node> nodes;
  30630. OwnedArray <Connection> connections;
  30631. int lastNodeId;
  30632. AudioSampleBuffer renderingBuffers;
  30633. OwnedArray <MidiBuffer> midiBuffers;
  30634. CriticalSection renderLock;
  30635. Array<void*> renderingOps;
  30636. friend class AudioGraphIOProcessor;
  30637. AudioSampleBuffer* currentAudioInputBuffer;
  30638. AudioSampleBuffer currentAudioOutputBuffer;
  30639. MidiBuffer* currentMidiInputBuffer;
  30640. MidiBuffer currentMidiOutputBuffer;
  30641. void clearRenderingSequence();
  30642. void buildRenderingSequence();
  30643. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  30644. AudioProcessorGraph (const AudioProcessorGraph&);
  30645. AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  30646. };
  30647. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30648. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  30649. #endif
  30650. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  30651. #endif
  30652. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30653. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  30654. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30655. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30656. /**
  30657. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  30658. To use one of these, just make it the callback used by your AudioIODevice, and
  30659. give it a processor to use by calling setProcessor().
  30660. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  30661. input to send both streams through the processor.
  30662. @see AudioProcessor, AudioProcessorGraph
  30663. */
  30664. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  30665. public MidiInputCallback
  30666. {
  30667. public:
  30668. /**
  30669. */
  30670. AudioProcessorPlayer();
  30671. /** Destructor. */
  30672. virtual ~AudioProcessorPlayer();
  30673. /** Sets the processor that should be played.
  30674. The processor that is passed in will not be deleted or owned by this object.
  30675. To stop anything playing, pass in 0 to this method.
  30676. */
  30677. void setProcessor (AudioProcessor* const processorToPlay);
  30678. /** Returns the current audio processor that is being played.
  30679. */
  30680. AudioProcessor* getCurrentProcessor() const { return processor; }
  30681. /** Returns a midi message collector that you can pass midi messages to if you
  30682. want them to be injected into the midi stream that is being sent to the
  30683. processor.
  30684. */
  30685. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  30686. /** @internal */
  30687. void audioDeviceIOCallback (const float** inputChannelData,
  30688. int totalNumInputChannels,
  30689. float** outputChannelData,
  30690. int totalNumOutputChannels,
  30691. int numSamples);
  30692. /** @internal */
  30693. void audioDeviceAboutToStart (AudioIODevice* device);
  30694. /** @internal */
  30695. void audioDeviceStopped();
  30696. /** @internal */
  30697. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  30698. juce_UseDebuggingNewOperator
  30699. private:
  30700. AudioProcessor* processor;
  30701. CriticalSection lock;
  30702. double sampleRate;
  30703. int blockSize;
  30704. bool isPrepared;
  30705. int numInputChans, numOutputChans;
  30706. float* channels [128];
  30707. AudioSampleBuffer tempBuffer;
  30708. MidiBuffer incomingMidi;
  30709. MidiMessageCollector messageCollector;
  30710. AudioProcessorPlayer (const AudioProcessorPlayer&);
  30711. AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  30712. };
  30713. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30714. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  30715. #endif
  30716. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30717. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30718. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30719. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30720. /*** Start of inlined file: juce_PropertyPanel.h ***/
  30721. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  30722. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  30723. /*** Start of inlined file: juce_PropertyComponent.h ***/
  30724. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30725. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30726. class EditableProperty;
  30727. /**
  30728. A base class for a component that goes in a PropertyPanel and displays one of
  30729. an item's properties.
  30730. Subclasses of this are used to display a property in various forms, e.g. a
  30731. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  30732. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  30733. A subclass must implement the refresh() method which will be called to tell the
  30734. component to update itself, and is also responsible for calling this it when the
  30735. item that it refers to is changed.
  30736. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  30737. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  30738. */
  30739. class JUCE_API PropertyComponent : public Component,
  30740. public SettableTooltipClient
  30741. {
  30742. public:
  30743. /** Creates a PropertyComponent.
  30744. @param propertyName the name is stored as this component's name, and is
  30745. used as the name displayed next to this component in
  30746. a property panel
  30747. @param preferredHeight the height that the component should be given - some
  30748. items may need to be larger than a normal row height.
  30749. This value can also be set if a subclass changes the
  30750. preferredHeight member variable.
  30751. */
  30752. PropertyComponent (const String& propertyName,
  30753. int preferredHeight = 25);
  30754. /** Destructor. */
  30755. ~PropertyComponent();
  30756. /** Returns this item's preferred height.
  30757. This value is specified either in the constructor or by a subclass changing the
  30758. preferredHeight member variable.
  30759. */
  30760. int getPreferredHeight() const throw() { return preferredHeight; }
  30761. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  30762. /** Updates the property component if the item it refers to has changed.
  30763. A subclass must implement this method, and other objects may call it to
  30764. force it to refresh itself.
  30765. The subclass should be economical in the amount of work is done, so for
  30766. example it should check whether it really needs to do a repaint rather than
  30767. just doing one every time this method is called, as it may be called when
  30768. the value being displayed hasn't actually changed.
  30769. */
  30770. virtual void refresh() = 0;
  30771. /** The default paint method fills the background and draws a label for the
  30772. item's name.
  30773. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  30774. */
  30775. void paint (Graphics& g);
  30776. /** The default resize method positions any child component to the right of this
  30777. one, based on the look and feel's default label size.
  30778. */
  30779. void resized();
  30780. /** By default, this just repaints the component. */
  30781. void enablementChanged();
  30782. juce_UseDebuggingNewOperator
  30783. protected:
  30784. /** Used by the PropertyPanel to determine how high this component needs to be.
  30785. A subclass can update this value in its constructor but shouldn't alter it later
  30786. as changes won't necessarily be picked up.
  30787. */
  30788. int preferredHeight;
  30789. };
  30790. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30791. /*** End of inlined file: juce_PropertyComponent.h ***/
  30792. /**
  30793. A panel that holds a list of PropertyComponent objects.
  30794. This panel displays a list of PropertyComponents, and allows them to be organised
  30795. into collapsible sections.
  30796. To use, simply create one of these and add your properties to it with addProperties()
  30797. or addSection().
  30798. @see PropertyComponent
  30799. */
  30800. class JUCE_API PropertyPanel : public Component
  30801. {
  30802. public:
  30803. /** Creates an empty property panel. */
  30804. PropertyPanel();
  30805. /** Destructor. */
  30806. ~PropertyPanel();
  30807. /** Deletes all property components from the panel.
  30808. */
  30809. void clear();
  30810. /** Adds a set of properties to the panel.
  30811. The components in the list will be owned by this object and will be automatically
  30812. deleted later on when no longer needed.
  30813. These properties are added without them being inside a named section. If you
  30814. want them to be kept together in a collapsible section, use addSection() instead.
  30815. */
  30816. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  30817. /** Adds a set of properties to the panel.
  30818. These properties are added at the bottom of the list, under a section heading with
  30819. a plus/minus button that allows it to be opened and closed.
  30820. The components in the list will be owned by this object and will be automatically
  30821. deleted later on when no longer needed.
  30822. To add properies without them being in a section, use addProperties().
  30823. */
  30824. void addSection (const String& sectionTitle,
  30825. const Array <PropertyComponent*>& newPropertyComponents,
  30826. bool shouldSectionInitiallyBeOpen = true);
  30827. /** Calls the refresh() method of all PropertyComponents in the panel */
  30828. void refreshAll() const;
  30829. /** Returns a list of all the names of sections in the panel.
  30830. These are the sections that have been added with addSection().
  30831. */
  30832. const StringArray getSectionNames() const;
  30833. /** Returns true if the section at this index is currently open.
  30834. The index is from 0 up to the number of items returned by getSectionNames().
  30835. */
  30836. bool isSectionOpen (int sectionIndex) const;
  30837. /** Opens or closes one of the sections.
  30838. The index is from 0 up to the number of items returned by getSectionNames().
  30839. */
  30840. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  30841. /** Enables or disables one of the sections.
  30842. The index is from 0 up to the number of items returned by getSectionNames().
  30843. */
  30844. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  30845. /** Saves the current state of open/closed sections so it can be restored later.
  30846. The caller is responsible for deleting the object that is returned.
  30847. To restore this state, use restoreOpennessState().
  30848. @see restoreOpennessState
  30849. */
  30850. XmlElement* getOpennessState() const;
  30851. /** Restores a previously saved arrangement of open/closed sections.
  30852. This will try to restore a snapshot of the panel's state that was created by
  30853. the getOpennessState() method. If any of the sections named in the original
  30854. XML aren't present, they will be ignored.
  30855. @see getOpennessState
  30856. */
  30857. void restoreOpennessState (const XmlElement& newState);
  30858. /** Sets a message to be displayed when there are no properties in the panel.
  30859. The default message is "nothing selected".
  30860. */
  30861. void setMessageWhenEmpty (const String& newMessage);
  30862. /** Returns the message that is displayed when there are no properties.
  30863. @see setMessageWhenEmpty
  30864. */
  30865. const String& getMessageWhenEmpty() const;
  30866. /** @internal */
  30867. void paint (Graphics& g);
  30868. /** @internal */
  30869. void resized();
  30870. juce_UseDebuggingNewOperator
  30871. private:
  30872. Viewport viewport;
  30873. class PropertyHolderComponent;
  30874. PropertyHolderComponent* propertyHolderComponent;
  30875. String messageWhenEmpty;
  30876. void updatePropHolderLayout() const;
  30877. void updatePropHolderLayout (int width) const;
  30878. };
  30879. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  30880. /*** End of inlined file: juce_PropertyPanel.h ***/
  30881. /**
  30882. A type of UI component that displays the parameters of an AudioProcessor as
  30883. a simple list of sliders.
  30884. This can be used for showing an editor for a processor that doesn't supply
  30885. its own custom editor.
  30886. @see AudioProcessor
  30887. */
  30888. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  30889. {
  30890. public:
  30891. GenericAudioProcessorEditor (AudioProcessor* const owner);
  30892. ~GenericAudioProcessorEditor();
  30893. void paint (Graphics& g);
  30894. void resized();
  30895. juce_UseDebuggingNewOperator
  30896. private:
  30897. PropertyPanel* panel;
  30898. GenericAudioProcessorEditor (const GenericAudioProcessorEditor&);
  30899. GenericAudioProcessorEditor& operator= (const GenericAudioProcessorEditor&);
  30900. };
  30901. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30902. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30903. #endif
  30904. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30905. /*** Start of inlined file: juce_Sampler.h ***/
  30906. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30907. #define __JUCE_SAMPLER_JUCEHEADER__
  30908. /*** Start of inlined file: juce_Synthesiser.h ***/
  30909. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  30910. #define __JUCE_SYNTHESISER_JUCEHEADER__
  30911. /**
  30912. Describes one of the sounds that a Synthesiser can play.
  30913. A synthesiser can contain one or more sounds, and a sound can choose which
  30914. midi notes and channels can trigger it.
  30915. The SynthesiserSound is a passive class that just describes what the sound is -
  30916. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  30917. more than one SynthesiserVoice to play the same sound at the same time.
  30918. @see Synthesiser, SynthesiserVoice
  30919. */
  30920. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  30921. {
  30922. protected:
  30923. SynthesiserSound();
  30924. public:
  30925. /** Destructor. */
  30926. virtual ~SynthesiserSound();
  30927. /** Returns true if this sound should be played when a given midi note is pressed.
  30928. The Synthesiser will use this information when deciding which sounds to trigger
  30929. for a given note.
  30930. */
  30931. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  30932. /** Returns true if the sound should be triggered by midi events on a given channel.
  30933. The Synthesiser will use this information when deciding which sounds to trigger
  30934. for a given note.
  30935. */
  30936. virtual bool appliesToChannel (const int midiChannel) = 0;
  30937. /**
  30938. */
  30939. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  30940. juce_UseDebuggingNewOperator
  30941. };
  30942. /**
  30943. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  30944. A voice plays a single sound at a time, and a synthesiser holds an array of
  30945. voices so that it can play polyphonically.
  30946. @see Synthesiser, SynthesiserSound
  30947. */
  30948. class JUCE_API SynthesiserVoice
  30949. {
  30950. public:
  30951. /** Creates a voice. */
  30952. SynthesiserVoice();
  30953. /** Destructor. */
  30954. virtual ~SynthesiserVoice();
  30955. /** Returns the midi note that this voice is currently playing.
  30956. Returns a value less than 0 if no note is playing.
  30957. */
  30958. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  30959. /** Returns the sound that this voice is currently playing.
  30960. Returns 0 if it's not playing.
  30961. */
  30962. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  30963. /** Must return true if this voice object is capable of playing the given sound.
  30964. If there are different classes of sound, and different classes of voice, a voice can
  30965. choose which ones it wants to take on.
  30966. A typical implementation of this method may just return true if there's only one type
  30967. of voice and sound, or it might check the type of the sound object passed-in and
  30968. see if it's one that it understands.
  30969. */
  30970. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  30971. /** Called to start a new note.
  30972. This will be called during the rendering callback, so must be fast and thread-safe.
  30973. */
  30974. virtual void startNote (const int midiNoteNumber,
  30975. const float velocity,
  30976. SynthesiserSound* sound,
  30977. const int currentPitchWheelPosition) = 0;
  30978. /** Called to stop a note.
  30979. This will be called during the rendering callback, so must be fast and thread-safe.
  30980. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  30981. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  30982. and allow the synth to reassign it another sound.
  30983. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  30984. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  30985. finishes playing (during the rendering callback), it must make sure that it calls
  30986. clearCurrentNote().
  30987. */
  30988. virtual void stopNote (const bool allowTailOff) = 0;
  30989. /** Called to let the voice know that the pitch wheel has been moved.
  30990. This will be called during the rendering callback, so must be fast and thread-safe.
  30991. */
  30992. virtual void pitchWheelMoved (const int newValue) = 0;
  30993. /** Called to let the voice know that a midi controller has been moved.
  30994. This will be called during the rendering callback, so must be fast and thread-safe.
  30995. */
  30996. virtual void controllerMoved (const int controllerNumber,
  30997. const int newValue) = 0;
  30998. /** Renders the next block of data for this voice.
  30999. The output audio data must be added to the current contents of the buffer provided.
  31000. Only the region of the buffer between startSample and (startSample + numSamples)
  31001. should be altered by this method.
  31002. If the voice is currently silent, it should just return without doing anything.
  31003. If the sound that the voice is playing finishes during the course of this rendered
  31004. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  31005. The size of the blocks that are rendered can change each time it is called, and may
  31006. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  31007. the voice's methods will be called to tell it about note and controller events.
  31008. */
  31009. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  31010. int startSample,
  31011. int numSamples) = 0;
  31012. /** Returns true if the voice is currently playing a sound which is mapped to the given
  31013. midi channel.
  31014. If it's not currently playing, this will return false.
  31015. */
  31016. bool isPlayingChannel (int midiChannel) const;
  31017. /** Changes the voice's reference sample rate.
  31018. The rate is set so that subclasses know the output rate and can set their pitch
  31019. accordingly.
  31020. This method is called by the synth, and subclasses can access the current rate with
  31021. the currentSampleRate member.
  31022. */
  31023. void setCurrentPlaybackSampleRate (double newRate);
  31024. juce_UseDebuggingNewOperator
  31025. protected:
  31026. /** Returns the current target sample rate at which rendering is being done.
  31027. This is available for subclasses so they can pitch things correctly.
  31028. */
  31029. double getSampleRate() const { return currentSampleRate; }
  31030. /** Resets the state of this voice after a sound has finished playing.
  31031. The subclass must call this when it finishes playing a note and becomes available
  31032. to play new ones.
  31033. It must either call it in the stopNote() method, or if the voice is tailing off,
  31034. then it should call it later during the renderNextBlock method, as soon as it
  31035. finishes its tail-off.
  31036. It can also be called at any time during the render callback if the sound happens
  31037. to have finished, e.g. if it's playing a sample and the sample finishes.
  31038. */
  31039. void clearCurrentNote();
  31040. private:
  31041. friend class Synthesiser;
  31042. double currentSampleRate;
  31043. int currentlyPlayingNote;
  31044. uint32 noteOnTime;
  31045. SynthesiserSound::Ptr currentlyPlayingSound;
  31046. };
  31047. /**
  31048. Base class for a musical device that can play sounds.
  31049. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  31050. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  31051. which can play back one of these sounds.
  31052. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  31053. set of sounds, and a set of voices it can use to play them. If you only give it
  31054. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  31055. have available.
  31056. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  31057. events that go in will be scanned for note on/off messages, and these are used to
  31058. start and stop the voices playing the appropriate sounds.
  31059. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  31060. noteOff() and other controller methods.
  31061. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  31062. what the target playback rate is. This value is passed on to the voices so that
  31063. they can pitch their output correctly.
  31064. */
  31065. class JUCE_API Synthesiser
  31066. {
  31067. public:
  31068. /** Creates a new synthesiser.
  31069. You'll need to add some sounds and voices before it'll make any sound..
  31070. */
  31071. Synthesiser();
  31072. /** Destructor. */
  31073. virtual ~Synthesiser();
  31074. /** Deletes all voices. */
  31075. void clearVoices();
  31076. /** Returns the number of voices that have been added. */
  31077. int getNumVoices() const { return voices.size(); }
  31078. /** Returns one of the voices that have been added. */
  31079. SynthesiserVoice* getVoice (int index) const;
  31080. /** Adds a new voice to the synth.
  31081. All the voices should be the same class of object and are treated equally.
  31082. The object passed in will be managed by the synthesiser, which will delete
  31083. it later on when no longer needed. The caller should not retain a pointer to the
  31084. voice.
  31085. */
  31086. void addVoice (SynthesiserVoice* newVoice);
  31087. /** Deletes one of the voices. */
  31088. void removeVoice (int index);
  31089. /** Deletes all sounds. */
  31090. void clearSounds();
  31091. /** Returns the number of sounds that have been added to the synth. */
  31092. int getNumSounds() const { return sounds.size(); }
  31093. /** Returns one of the sounds. */
  31094. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  31095. /** Adds a new sound to the synthesiser.
  31096. The object passed in is reference counted, so will be deleted when it is removed
  31097. from the synthesiser, and when no voices are still using it.
  31098. */
  31099. void addSound (const SynthesiserSound::Ptr& newSound);
  31100. /** Removes and deletes one of the sounds. */
  31101. void removeSound (int index);
  31102. /** If set to true, then the synth will try to take over an existing voice if
  31103. it runs out and needs to play another note.
  31104. The value of this boolean is passed into findFreeVoice(), so the result will
  31105. depend on the implementation of this method.
  31106. */
  31107. void setNoteStealingEnabled (bool shouldStealNotes);
  31108. /** Returns true if note-stealing is enabled.
  31109. @see setNoteStealingEnabled
  31110. */
  31111. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  31112. /** Triggers a note-on event.
  31113. The default method here will find all the sounds that want to be triggered by
  31114. this note/channel. For each sound, it'll try to find a free voice, and use the
  31115. voice to start playing the sound.
  31116. Subclasses might want to override this if they need a more complex algorithm.
  31117. This method will be called automatically according to the midi data passed into
  31118. renderNextBlock(), but may be called explicitly too.
  31119. */
  31120. virtual void noteOn (const int midiChannel,
  31121. const int midiNoteNumber,
  31122. const float velocity);
  31123. /** Triggers a note-off event.
  31124. This will turn off any voices that are playing a sound for the given note/channel.
  31125. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  31126. (if they can do). If this is false, the notes will all be cut off immediately.
  31127. This method will be called automatically according to the midi data passed into
  31128. renderNextBlock(), but may be called explicitly too.
  31129. */
  31130. virtual void noteOff (const int midiChannel,
  31131. const int midiNoteNumber,
  31132. const bool allowTailOff);
  31133. /** Turns off all notes.
  31134. This will turn off any voices that are playing a sound on the given midi channel.
  31135. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  31136. which channel they're playing.
  31137. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  31138. (if they can do). If this is false, the notes will all be cut off immediately.
  31139. This method will be called automatically according to the midi data passed into
  31140. renderNextBlock(), but may be called explicitly too.
  31141. */
  31142. virtual void allNotesOff (const int midiChannel,
  31143. const bool allowTailOff);
  31144. /** Sends a pitch-wheel message.
  31145. This will send a pitch-wheel message to any voices that are playing sounds on
  31146. the given midi channel.
  31147. This method will be called automatically according to the midi data passed into
  31148. renderNextBlock(), but may be called explicitly too.
  31149. @param midiChannel the midi channel for the event
  31150. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  31151. */
  31152. virtual void handlePitchWheel (const int midiChannel,
  31153. const int wheelValue);
  31154. /** Sends a midi controller message.
  31155. This will send a midi controller message to any voices that are playing sounds on
  31156. the given midi channel.
  31157. This method will be called automatically according to the midi data passed into
  31158. renderNextBlock(), but may be called explicitly too.
  31159. @param midiChannel the midi channel for the event
  31160. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  31161. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  31162. */
  31163. virtual void handleController (const int midiChannel,
  31164. const int controllerNumber,
  31165. const int controllerValue);
  31166. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  31167. render.
  31168. This value is propagated to the voices so that they can use it to render the correct
  31169. pitches.
  31170. */
  31171. void setCurrentPlaybackSampleRate (const double sampleRate);
  31172. /** Creates the next block of audio output.
  31173. This will process the next numSamples of data from all the voices, and add that output
  31174. to the audio block supplied, starting from the offset specified. Note that the
  31175. data will be added to the current contents of the buffer, so you should clear it
  31176. before calling this method if necessary.
  31177. The midi events in the inputMidi buffer are parsed for note and controller events,
  31178. and these are used to trigger the voices. Note that the startSample offset applies
  31179. both to the audio output buffer and the midi input buffer, so any midi events
  31180. with timestamps outside the specified region will be ignored.
  31181. */
  31182. void renderNextBlock (AudioSampleBuffer& outputAudio,
  31183. const MidiBuffer& inputMidi,
  31184. int startSample,
  31185. int numSamples);
  31186. juce_UseDebuggingNewOperator
  31187. protected:
  31188. /** This is used to control access to the rendering callback and the note trigger methods. */
  31189. CriticalSection lock;
  31190. OwnedArray <SynthesiserVoice> voices;
  31191. ReferenceCountedArray <SynthesiserSound> sounds;
  31192. /** The last pitch-wheel values for each midi channel. */
  31193. int lastPitchWheelValues [16];
  31194. /** Searches through the voices to find one that's not currently playing, and which
  31195. can play the given sound.
  31196. Returns 0 if all voices are busy and stealing isn't enabled.
  31197. This can be overridden to implement custom voice-stealing algorithms.
  31198. */
  31199. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  31200. const bool stealIfNoneAvailable) const;
  31201. /** Starts a specified voice playing a particular sound.
  31202. You'll probably never need to call this, it's used internally by noteOn(), but
  31203. may be needed by subclasses for custom behaviours.
  31204. */
  31205. void startVoice (SynthesiserVoice* voice,
  31206. SynthesiserSound* sound,
  31207. int midiChannel,
  31208. int midiNoteNumber,
  31209. float velocity);
  31210. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  31211. int findFreeVoice (const bool) const { return 0; }
  31212. private:
  31213. double sampleRate;
  31214. uint32 lastNoteOnCounter;
  31215. bool shouldStealNotes;
  31216. Synthesiser (const Synthesiser&);
  31217. Synthesiser& operator= (const Synthesiser&);
  31218. };
  31219. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  31220. /*** End of inlined file: juce_Synthesiser.h ***/
  31221. /**
  31222. A subclass of SynthesiserSound that represents a sampled audio clip.
  31223. This is a pretty basic sampler, and just attempts to load the whole audio stream
  31224. into memory.
  31225. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  31226. give it some SampledSound objects to play.
  31227. @see SamplerVoice, Synthesiser, SynthesiserSound
  31228. */
  31229. class JUCE_API SamplerSound : public SynthesiserSound
  31230. {
  31231. public:
  31232. /** Creates a sampled sound from an audio reader.
  31233. This will attempt to load the audio from the source into memory and store
  31234. it in this object.
  31235. @param name a name for the sample
  31236. @param source the audio to load. This object can be safely deleted by the
  31237. caller after this constructor returns
  31238. @param midiNotes the set of midi keys that this sound should be played on. This
  31239. is used by the SynthesiserSound::appliesToNote() method
  31240. @param midiNoteForNormalPitch the midi note at which the sample should be played
  31241. with its natural rate. All other notes will be pitched
  31242. up or down relative to this one
  31243. @param attackTimeSecs the attack (fade-in) time, in seconds
  31244. @param releaseTimeSecs the decay (fade-out) time, in seconds
  31245. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  31246. source, in seconds
  31247. */
  31248. SamplerSound (const String& name,
  31249. AudioFormatReader& source,
  31250. const BigInteger& midiNotes,
  31251. int midiNoteForNormalPitch,
  31252. double attackTimeSecs,
  31253. double releaseTimeSecs,
  31254. double maxSampleLengthSeconds);
  31255. /** Destructor. */
  31256. ~SamplerSound();
  31257. /** Returns the sample's name */
  31258. const String& getName() const { return name; }
  31259. /** Returns the audio sample data.
  31260. This could be 0 if there was a problem loading it.
  31261. */
  31262. AudioSampleBuffer* getAudioData() const { return data; }
  31263. bool appliesToNote (const int midiNoteNumber);
  31264. bool appliesToChannel (const int midiChannel);
  31265. juce_UseDebuggingNewOperator
  31266. private:
  31267. friend class SamplerVoice;
  31268. String name;
  31269. ScopedPointer <AudioSampleBuffer> data;
  31270. double sourceSampleRate;
  31271. BigInteger midiNotes;
  31272. int length, attackSamples, releaseSamples;
  31273. int midiRootNote;
  31274. };
  31275. /**
  31276. A subclass of SynthesiserVoice that can play a SamplerSound.
  31277. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  31278. give it some SampledSound objects to play.
  31279. @see SamplerSound, Synthesiser, SynthesiserVoice
  31280. */
  31281. class JUCE_API SamplerVoice : public SynthesiserVoice
  31282. {
  31283. public:
  31284. /** Creates a SamplerVoice.
  31285. */
  31286. SamplerVoice();
  31287. /** Destructor. */
  31288. ~SamplerVoice();
  31289. bool canPlaySound (SynthesiserSound* sound);
  31290. void startNote (const int midiNoteNumber,
  31291. const float velocity,
  31292. SynthesiserSound* sound,
  31293. const int currentPitchWheelPosition);
  31294. void stopNote (const bool allowTailOff);
  31295. void pitchWheelMoved (const int newValue);
  31296. void controllerMoved (const int controllerNumber,
  31297. const int newValue);
  31298. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  31299. juce_UseDebuggingNewOperator
  31300. private:
  31301. double pitchRatio;
  31302. double sourceSamplePosition;
  31303. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  31304. bool isInAttack, isInRelease;
  31305. };
  31306. #endif // __JUCE_SAMPLER_JUCEHEADER__
  31307. /*** End of inlined file: juce_Sampler.h ***/
  31308. #endif
  31309. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  31310. #endif
  31311. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31312. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  31313. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31314. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31315. /*** Start of inlined file: juce_ActionListenerList.h ***/
  31316. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31317. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31318. /**
  31319. A set of ActionListeners.
  31320. Listeners can be added and removed from the list, and messages can be
  31321. broadcast to all the listeners.
  31322. @see ActionListener, ActionBroadcaster
  31323. */
  31324. class JUCE_API ActionListenerList : public MessageListener
  31325. {
  31326. public:
  31327. /** Creates an empty list. */
  31328. ActionListenerList() throw();
  31329. /** Destructor. */
  31330. ~ActionListenerList() throw();
  31331. /** Adds a listener to the list.
  31332. (Trying to add a listener that's already on the list will have no effect).
  31333. */
  31334. void addActionListener (ActionListener* listener) throw();
  31335. /** Removes a listener from the list.
  31336. If the listener isn't on the list, this won't have any effect.
  31337. */
  31338. void removeActionListener (ActionListener* listener) throw();
  31339. /** Removes all listeners from the list. */
  31340. void removeAllActionListeners() throw();
  31341. /** Broadcasts a message to all the registered listeners.
  31342. This sends the message asynchronously.
  31343. If a listener is on the list when this method is called but is removed from
  31344. the list before the message arrives, it won't receive the message. Similarly
  31345. listeners that are added to the list after the message is sent but before it
  31346. arrives won't get the message either.
  31347. */
  31348. void sendActionMessage (const String& message) const;
  31349. /** @internal */
  31350. void handleMessage (const Message&);
  31351. juce_UseDebuggingNewOperator
  31352. private:
  31353. SortedSet <void*> actionListeners_;
  31354. CriticalSection actionListenerLock_;
  31355. ActionListenerList (const ActionListenerList&);
  31356. ActionListenerList& operator= (const ActionListenerList&);
  31357. };
  31358. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31359. /*** End of inlined file: juce_ActionListenerList.h ***/
  31360. /** Manages a list of ActionListeners, and can send them messages.
  31361. To quickly add methods to your class that can add/remove action
  31362. listeners and broadcast to them, you can derive from this.
  31363. @see ActionListenerList, ActionListener
  31364. */
  31365. class JUCE_API ActionBroadcaster
  31366. {
  31367. public:
  31368. /** Creates an ActionBroadcaster. */
  31369. ActionBroadcaster() throw();
  31370. /** Destructor. */
  31371. virtual ~ActionBroadcaster();
  31372. /** Adds a listener to the list.
  31373. (Trying to add a listener that's already on the list will have no effect).
  31374. */
  31375. void addActionListener (ActionListener* listener);
  31376. /** Removes a listener from the list.
  31377. If the listener isn't on the list, this won't have any effect.
  31378. */
  31379. void removeActionListener (ActionListener* listener);
  31380. /** Removes all listeners from the list. */
  31381. void removeAllActionListeners();
  31382. /** Broadcasts a message to all the registered listeners.
  31383. @see ActionListenerList::sendActionMessage
  31384. */
  31385. void sendActionMessage (const String& message) const;
  31386. private:
  31387. ActionListenerList actionListenerList;
  31388. ActionBroadcaster (const ActionBroadcaster&);
  31389. ActionBroadcaster& operator= (const ActionBroadcaster&);
  31390. };
  31391. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31392. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  31393. #endif
  31394. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  31395. #endif
  31396. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31397. #endif
  31398. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  31399. #endif
  31400. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31401. /*** Start of inlined file: juce_CallbackMessage.h ***/
  31402. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31403. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31404. /**
  31405. A message that calls a custom function when it gets delivered.
  31406. You can use this class to fire off actions that you want to be performed later
  31407. on the message thread.
  31408. Unlike other Message objects, these don't get sent to a MessageListener, you
  31409. just call the post() method to send them, and when they arrive, your
  31410. messageCallback() method will automatically be invoked.
  31411. @see MessageListener, MessageManager, ActionListener, ChangeListener
  31412. */
  31413. class JUCE_API CallbackMessage : public Message
  31414. {
  31415. public:
  31416. CallbackMessage() throw();
  31417. /** Destructor. */
  31418. ~CallbackMessage() throw();
  31419. /** Called when the message is delivered.
  31420. You should implement this method and make it do whatever action you want
  31421. to perform.
  31422. Note that like all other messages, this object will be deleted immediately
  31423. after this method has been invoked.
  31424. */
  31425. virtual void messageCallback() = 0;
  31426. /** Instead of sending this message to a MessageListener, just call this method
  31427. to post it to the event queue.
  31428. After you've called this, this object will belong to the MessageManager,
  31429. which will delete it later. So make sure you don't delete the object yourself,
  31430. call post() more than once, or call post() on a stack-based obect!
  31431. */
  31432. void post();
  31433. juce_UseDebuggingNewOperator
  31434. private:
  31435. CallbackMessage (const CallbackMessage&);
  31436. CallbackMessage& operator= (const CallbackMessage&);
  31437. };
  31438. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31439. /*** End of inlined file: juce_CallbackMessage.h ***/
  31440. #endif
  31441. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  31442. #endif
  31443. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  31444. #endif
  31445. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  31446. #endif
  31447. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31448. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  31449. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31450. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31451. class InterprocessConnectionServer;
  31452. /**
  31453. Manages a simple two-way messaging connection to another process, using either
  31454. a socket or a named pipe as the transport medium.
  31455. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  31456. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  31457. and incoming messages will result in a callback via the messageReceived()
  31458. method.
  31459. To open a pipe and wait for another client to connect to it, use the createPipe()
  31460. method.
  31461. To act as a socket server and create connections for one or more client, see the
  31462. InterprocessConnectionServer class.
  31463. @see InterprocessConnectionServer, Socket, NamedPipe
  31464. */
  31465. class JUCE_API InterprocessConnection : public Thread,
  31466. private MessageListener
  31467. {
  31468. public:
  31469. /** Creates a connection.
  31470. Connections are created manually, connecting them with the connectToSocket()
  31471. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  31472. when a client wants to connect.
  31473. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  31474. connectionLost() and messageReceived() methods will
  31475. always be made using the message thread; if false,
  31476. these will be called immediately on the connection's
  31477. own thread.
  31478. @param magicMessageHeaderNumber a magic number to use in the header to check the
  31479. validity of the data blocks being sent and received. This
  31480. can be any number, but the sender and receiver must obviously
  31481. use matching values or they won't recognise each other.
  31482. */
  31483. InterprocessConnection (bool callbacksOnMessageThread = true,
  31484. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  31485. /** Destructor. */
  31486. ~InterprocessConnection();
  31487. /** Tries to connect this object to a socket.
  31488. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  31489. object waiting to receive client connections on this port number.
  31490. @param hostName the host computer, either a network address or name
  31491. @param portNumber the socket port number to try to connect to
  31492. @param timeOutMillisecs how long to keep trying before giving up
  31493. @returns true if the connection is established successfully
  31494. @see Socket
  31495. */
  31496. bool connectToSocket (const String& hostName,
  31497. int portNumber,
  31498. int timeOutMillisecs);
  31499. /** Tries to connect the object to an existing named pipe.
  31500. For this to work, another process on the same computer must already have opened
  31501. an InterprocessConnection object and used createPipe() to create a pipe for this
  31502. to connect to.
  31503. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31504. @returns true if it connects successfully.
  31505. @see createPipe, NamedPipe
  31506. */
  31507. bool connectToPipe (const String& pipeName,
  31508. int pipeReceiveMessageTimeoutMs = -1);
  31509. /** Tries to create a new pipe for other processes to connect to.
  31510. This creates a pipe with the given name, so that other processes can use
  31511. connectToPipe() to connect to the other end.
  31512. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31513. If another process is already using this pipe, this will fail and return false.
  31514. */
  31515. bool createPipe (const String& pipeName,
  31516. int pipeReceiveMessageTimeoutMs = -1);
  31517. /** Disconnects and closes any currently-open sockets or pipes. */
  31518. void disconnect();
  31519. /** True if a socket or pipe is currently active. */
  31520. bool isConnected() const;
  31521. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  31522. StreamingSocket* getSocket() const throw() { return socket; }
  31523. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  31524. NamedPipe* getPipe() const throw() { return pipe; }
  31525. /** Returns the name of the machine at the other end of this connection.
  31526. This will return an empty string if the other machine isn't known for
  31527. some reason.
  31528. */
  31529. const String getConnectedHostName() const;
  31530. /** Tries to send a message to the other end of this connection.
  31531. This will fail if it's not connected, or if there's some kind of write error. If
  31532. it succeeds, the connection object at the other end will receive the message by
  31533. a callback to its messageReceived() method.
  31534. @see messageReceived
  31535. */
  31536. bool sendMessage (const MemoryBlock& message);
  31537. /** Called when the connection is first connected.
  31538. If the connection was created with the callbacksOnMessageThread flag set, then
  31539. this will be called on the message thread; otherwise it will be called on a server
  31540. thread.
  31541. */
  31542. virtual void connectionMade() = 0;
  31543. /** Called when the connection is broken.
  31544. If the connection was created with the callbacksOnMessageThread flag set, then
  31545. this will be called on the message thread; otherwise it will be called on a server
  31546. thread.
  31547. */
  31548. virtual void connectionLost() = 0;
  31549. /** Called when a message arrives.
  31550. When the object at the other end of this connection sends us a message with sendMessage(),
  31551. this callback is used to deliver it to us.
  31552. If the connection was created with the callbacksOnMessageThread flag set, then
  31553. this will be called on the message thread; otherwise it will be called on a server
  31554. thread.
  31555. @see sendMessage
  31556. */
  31557. virtual void messageReceived (const MemoryBlock& message) = 0;
  31558. juce_UseDebuggingNewOperator
  31559. private:
  31560. CriticalSection pipeAndSocketLock;
  31561. ScopedPointer <StreamingSocket> socket;
  31562. ScopedPointer <NamedPipe> pipe;
  31563. bool callbackConnectionState;
  31564. const bool useMessageThread;
  31565. const uint32 magicMessageHeader;
  31566. int pipeReceiveMessageTimeout;
  31567. friend class InterprocessConnectionServer;
  31568. void initialiseWithSocket (StreamingSocket* socket_);
  31569. void initialiseWithPipe (NamedPipe* pipe_);
  31570. void handleMessage (const Message& message);
  31571. void connectionMadeInt();
  31572. void connectionLostInt();
  31573. void deliverDataInt (const MemoryBlock& data);
  31574. bool readNextMessageInt();
  31575. void run();
  31576. InterprocessConnection (const InterprocessConnection&);
  31577. InterprocessConnection& operator= (const InterprocessConnection&);
  31578. };
  31579. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31580. /*** End of inlined file: juce_InterprocessConnection.h ***/
  31581. #endif
  31582. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31583. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  31584. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31585. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31586. /**
  31587. An object that waits for client sockets to connect to a port on this host, and
  31588. creates InterprocessConnection objects for each one.
  31589. To use this, create a class derived from it which implements the createConnectionObject()
  31590. method, so that it creates suitable connection objects for each client that tries
  31591. to connect.
  31592. @see InterprocessConnection
  31593. */
  31594. class JUCE_API InterprocessConnectionServer : private Thread
  31595. {
  31596. public:
  31597. /** Creates an uninitialised server object.
  31598. */
  31599. InterprocessConnectionServer();
  31600. /** Destructor. */
  31601. ~InterprocessConnectionServer();
  31602. /** Starts an internal thread which listens on the given port number.
  31603. While this is running, in another process tries to connect with the
  31604. InterprocessConnection::connectToSocket() method, this object will call
  31605. createConnectionObject() to create a connection to that client.
  31606. Use stop() to stop the thread running.
  31607. @see createConnectionObject, stop
  31608. */
  31609. bool beginWaitingForSocket (int portNumber);
  31610. /** Terminates the listener thread, if it's active.
  31611. @see beginWaitingForSocket
  31612. */
  31613. void stop();
  31614. protected:
  31615. /** Creates a suitable connection object for a client process that wants to
  31616. connect to this one.
  31617. This will be called by the listener thread when a client process tries
  31618. to connect, and must return a new InterprocessConnection object that will
  31619. then run as this end of the connection.
  31620. @see InterprocessConnection
  31621. */
  31622. virtual InterprocessConnection* createConnectionObject() = 0;
  31623. public:
  31624. juce_UseDebuggingNewOperator
  31625. private:
  31626. ScopedPointer <StreamingSocket> socket;
  31627. void run();
  31628. InterprocessConnectionServer (const InterprocessConnectionServer&);
  31629. InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  31630. };
  31631. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31632. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  31633. #endif
  31634. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  31635. #endif
  31636. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  31637. #endif
  31638. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  31639. #endif
  31640. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31641. /*** Start of inlined file: juce_MessageManager.h ***/
  31642. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31643. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31644. class Component;
  31645. class MessageManagerLock;
  31646. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  31647. */
  31648. typedef void* (MessageCallbackFunction) (void* userData);
  31649. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  31650. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  31651. */
  31652. class JUCE_API MessageManager
  31653. {
  31654. public:
  31655. /** Returns the global instance of the MessageManager. */
  31656. static MessageManager* getInstance() throw();
  31657. /** Runs the event dispatch loop until a stop message is posted.
  31658. This method is only intended to be run by the application's startup routine,
  31659. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  31660. @see stopDispatchLoop
  31661. */
  31662. void runDispatchLoop();
  31663. /** Sends a signal that the dispatch loop should terminate.
  31664. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  31665. will be interrupted and will return.
  31666. @see runDispatchLoop
  31667. */
  31668. void stopDispatchLoop();
  31669. /** Returns true if the stopDispatchLoop() method has been called.
  31670. */
  31671. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  31672. /** Synchronously dispatches messages until a given time has elapsed.
  31673. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  31674. otherwise returns true.
  31675. */
  31676. bool runDispatchLoopUntil (int millisecondsToRunFor);
  31677. /** Calls a function using the message-thread.
  31678. This can be used by any thread to cause this function to be called-back
  31679. by the message thread. If it's the message-thread that's calling this method,
  31680. then the function will just be called; if another thread is calling, a message
  31681. will be posted to the queue, and this method will block until that message
  31682. is delivered, the function is called, and the result is returned.
  31683. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  31684. thread has a critical section locked, which an unrelated message callback then tries to lock
  31685. before the message thread gets round to processing this callback.
  31686. @param callback the function to call - its signature must be @code
  31687. void* myCallbackFunction (void*) @endcode
  31688. @param userData a user-defined pointer that will be passed to the function that gets called
  31689. @returns the value that the callback function returns.
  31690. @see MessageManagerLock
  31691. */
  31692. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  31693. void* userData);
  31694. /** Returns true if the caller-thread is the message thread. */
  31695. bool isThisTheMessageThread() const throw();
  31696. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  31697. (Best to ignore this method unless you really know what you're doing..)
  31698. @see getCurrentMessageThread
  31699. */
  31700. void setCurrentThreadAsMessageThread();
  31701. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  31702. (Best to ignore this method unless you really know what you're doing..)
  31703. @see setCurrentMessageThread
  31704. */
  31705. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  31706. /** Returns true if the caller thread has currenltly got the message manager locked.
  31707. see the MessageManagerLock class for more info about this.
  31708. This will be true if the caller is the message thread, because that automatically
  31709. gains a lock while a message is being dispatched.
  31710. */
  31711. bool currentThreadHasLockedMessageManager() const throw();
  31712. /** Sends a message to all other JUCE applications that are running.
  31713. @param messageText the string that will be passed to the actionListenerCallback()
  31714. method of the broadcast listeners in the other app.
  31715. @see registerBroadcastListener, ActionListener
  31716. */
  31717. static void broadcastMessage (const String& messageText) throw();
  31718. /** Registers a listener to get told about broadcast messages.
  31719. The actionListenerCallback() callback's string parameter
  31720. is the message passed into broadcastMessage().
  31721. @see broadcastMessage
  31722. */
  31723. void registerBroadcastListener (ActionListener* listener) throw();
  31724. /** Deregisters a broadcast listener. */
  31725. void deregisterBroadcastListener (ActionListener* listener) throw();
  31726. /** @internal */
  31727. void deliverMessage (Message*);
  31728. /** @internal */
  31729. void deliverBroadcastMessage (const String&);
  31730. /** @internal */
  31731. ~MessageManager() throw();
  31732. juce_UseDebuggingNewOperator
  31733. private:
  31734. MessageManager() throw();
  31735. friend class MessageListener;
  31736. friend class ChangeBroadcaster;
  31737. friend class ActionBroadcaster;
  31738. friend class CallbackMessage;
  31739. static MessageManager* instance;
  31740. SortedSet <const MessageListener*> messageListeners;
  31741. ScopedPointer <ActionListenerList> broadcastListeners;
  31742. friend class JUCEApplication;
  31743. bool quitMessagePosted, quitMessageReceived;
  31744. Thread::ThreadID messageThreadId;
  31745. static void* exitModalLoopCallback (void*);
  31746. void postMessageToQueue (Message* message);
  31747. void postCallbackMessage (Message* message);
  31748. static void doPlatformSpecificInitialisation();
  31749. static void doPlatformSpecificShutdown();
  31750. friend class MessageManagerLock;
  31751. Thread::ThreadID volatile threadWithLock;
  31752. CriticalSection lockingLock;
  31753. MessageManager (const MessageManager&);
  31754. MessageManager& operator= (const MessageManager&);
  31755. };
  31756. /** Used to make sure that the calling thread has exclusive access to the message loop.
  31757. Because it's not thread-safe to call any of the Component or other UI classes
  31758. from threads other than the message thread, one of these objects can be used to
  31759. lock the message loop and allow this to be done. The message thread will be
  31760. suspended for the lifetime of the MessageManagerLock object, so create one on
  31761. the stack like this: @code
  31762. void MyThread::run()
  31763. {
  31764. someData = 1234;
  31765. const MessageManagerLock mmLock;
  31766. // the event loop will now be locked so it's safe to make a few calls..
  31767. myComponent->setBounds (newBounds);
  31768. myComponent->repaint();
  31769. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  31770. }
  31771. @endcode
  31772. Obviously be careful not to create one of these and leave it lying around, or
  31773. your app will grind to a halt!
  31774. Another caveat is that using this in conjunction with other CriticalSections
  31775. can create lots of interesting ways of producing a deadlock! In particular, if
  31776. your message thread calls stopThread() for a thread that uses these locks,
  31777. you'll get an (occasional) deadlock..
  31778. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  31779. */
  31780. class JUCE_API MessageManagerLock
  31781. {
  31782. public:
  31783. /** Tries to acquire a lock on the message manager.
  31784. The constructor attempts to gain a lock on the message loop, and the lock will be
  31785. kept for the lifetime of this object.
  31786. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  31787. this method will keep checking whether the thread has been given the
  31788. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  31789. without gaining the lock. If you pass a thread, you must check whether the lock was
  31790. successful by calling lockWasGained(). If this is false, your thread is being told to
  31791. die, so you should take evasive action.
  31792. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  31793. careful when doing this, because it's very easy to deadlock if your message thread
  31794. attempts to call stopThread() on a thread just as that thread attempts to get the
  31795. message lock.
  31796. If the calling thread already has the lock, nothing will be done, so it's safe and
  31797. quick to use these locks recursively.
  31798. E.g.
  31799. @code
  31800. void run()
  31801. {
  31802. ...
  31803. while (! threadShouldExit())
  31804. {
  31805. MessageManagerLock mml (Thread::getCurrentThread());
  31806. if (! mml.lockWasGained())
  31807. return; // another thread is trying to kill us!
  31808. ..do some locked stuff here..
  31809. }
  31810. ..and now the MM is now unlocked..
  31811. }
  31812. @endcode
  31813. */
  31814. MessageManagerLock (Thread* threadToCheckForExitSignal = 0) throw();
  31815. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  31816. instead of a thread.
  31817. See the MessageManagerLock (Thread*) constructor for details on how this works.
  31818. */
  31819. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal) throw();
  31820. /** Releases the current thread's lock on the message manager.
  31821. Make sure this object is created and deleted by the same thread,
  31822. otherwise there are no guarantees what will happen!
  31823. */
  31824. ~MessageManagerLock() throw();
  31825. /** Returns true if the lock was successfully acquired.
  31826. (See the constructor that takes a Thread for more info).
  31827. */
  31828. bool lockWasGained() const throw() { return locked; }
  31829. private:
  31830. class SharedEvents;
  31831. class BlockingMessage;
  31832. friend class SharedEvents;
  31833. friend class BlockingMessage;
  31834. SharedEvents* sharedEvents;
  31835. bool locked;
  31836. void init (Thread* thread, ThreadPoolJob* job) throw();
  31837. MessageManagerLock (const MessageManagerLock&);
  31838. MessageManagerLock& operator= (const MessageManagerLock&);
  31839. };
  31840. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31841. /*** End of inlined file: juce_MessageManager.h ***/
  31842. #endif
  31843. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31844. /*** Start of inlined file: juce_MultiTimer.h ***/
  31845. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31846. #define __JUCE_MULTITIMER_JUCEHEADER__
  31847. /**
  31848. A type of timer class that can run multiple timers with different frequencies,
  31849. all of which share a single callback.
  31850. This class is very similar to the Timer class, but allows you run multiple
  31851. separate timers, where each one has a unique ID number. The methods in this
  31852. class are exactly equivalent to those in Timer, but with the addition of
  31853. this ID number.
  31854. To use it, you need to create a subclass of MultiTimer, implementing the
  31855. timerCallback() method. Then you can start timers with startTimer(), and
  31856. each time the callback is triggered, it passes in the ID of the timer that
  31857. caused it.
  31858. @see Timer
  31859. */
  31860. class JUCE_API MultiTimer
  31861. {
  31862. protected:
  31863. /** Creates a MultiTimer.
  31864. When created, no timers are running, so use startTimer() to start things off.
  31865. */
  31866. MultiTimer() throw();
  31867. /** Creates a copy of another timer.
  31868. Note that this timer will not contain any running timers, even if the one you're
  31869. copying from was running.
  31870. */
  31871. MultiTimer (const MultiTimer& other) throw();
  31872. public:
  31873. /** Destructor. */
  31874. virtual ~MultiTimer();
  31875. /** The user-defined callback routine that actually gets called by each of the
  31876. timers that are running.
  31877. It's perfectly ok to call startTimer() or stopTimer() from within this
  31878. callback to change the subsequent intervals.
  31879. */
  31880. virtual void timerCallback (int timerId) = 0;
  31881. /** Starts a timer and sets the length of interval required.
  31882. If the timer is already started, this will reset it, so the
  31883. time between calling this method and the next timer callback
  31884. will not be less than the interval length passed in.
  31885. @param timerId a unique Id number that identifies the timer to
  31886. start. This is the id that will be passed back
  31887. to the timerCallback() method when this timer is
  31888. triggered
  31889. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  31890. rounded up to 1)
  31891. */
  31892. void startTimer (int timerId, int intervalInMilliseconds) throw();
  31893. /** Stops a timer.
  31894. If a timer has been started with the given ID number, it will be cancelled.
  31895. No more callbacks will be made for the specified timer after this method returns.
  31896. If this is called from a different thread, any callbacks that may
  31897. be currently executing may be allowed to finish before the method
  31898. returns.
  31899. */
  31900. void stopTimer (int timerId) throw();
  31901. /** Checks whether a timer has been started for a specified ID.
  31902. @returns true if a timer with the given ID is running.
  31903. */
  31904. bool isTimerRunning (int timerId) const throw();
  31905. /** Returns the interval for a specified timer ID.
  31906. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  31907. is running for the ID number specified.
  31908. */
  31909. int getTimerInterval (int timerId) const throw();
  31910. private:
  31911. class MultiTimerCallback;
  31912. CriticalSection timerListLock;
  31913. OwnedArray <MultiTimerCallback> timers;
  31914. MultiTimer& operator= (const MultiTimer&);
  31915. };
  31916. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  31917. /*** End of inlined file: juce_MultiTimer.h ***/
  31918. #endif
  31919. #ifndef __JUCE_TIMER_JUCEHEADER__
  31920. #endif
  31921. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31922. /*** Start of inlined file: juce_ArrowButton.h ***/
  31923. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31924. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31925. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  31926. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31927. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31928. /**
  31929. An effect filter that adds a drop-shadow behind the image's content.
  31930. (This will only work on images/components that aren't opaque, of course).
  31931. When added to a component, this effect will draw a soft-edged
  31932. shadow based on what gets drawn inside it. The shadow will also
  31933. be applied to the component's children.
  31934. For speed, this doesn't use a proper gaussian blur, but cheats by
  31935. using a simple bilinear filter. If you need a really high-quality
  31936. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31937. @see Component::setComponentEffect
  31938. */
  31939. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31940. {
  31941. public:
  31942. /** Creates a default drop-shadow effect.
  31943. To customise the shadow's appearance, use the setShadowProperties()
  31944. method.
  31945. */
  31946. DropShadowEffect();
  31947. /** Destructor. */
  31948. ~DropShadowEffect();
  31949. /** Sets up parameters affecting the shadow's appearance.
  31950. @param newRadius the (approximate) radius of the blur used
  31951. @param newOpacity the opacity with which the shadow is rendered
  31952. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  31953. component's contents
  31954. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  31955. component's contents
  31956. */
  31957. void setShadowProperties (float newRadius,
  31958. float newOpacity,
  31959. int newShadowOffsetX,
  31960. int newShadowOffsetY);
  31961. /** @internal */
  31962. void applyEffect (Image& sourceImage, Graphics& destContext);
  31963. juce_UseDebuggingNewOperator
  31964. private:
  31965. int offsetX, offsetY;
  31966. float radius, opacity;
  31967. };
  31968. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31969. /*** End of inlined file: juce_DropShadowEffect.h ***/
  31970. /**
  31971. A button with an arrow in it.
  31972. @see Button
  31973. */
  31974. class JUCE_API ArrowButton : public Button
  31975. {
  31976. public:
  31977. /** Creates an ArrowButton.
  31978. @param buttonName the name to give the button
  31979. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31980. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31981. @param arrowColour the colour to use for the arrow
  31982. */
  31983. ArrowButton (const String& buttonName,
  31984. float arrowDirection,
  31985. const Colour& arrowColour);
  31986. /** Destructor. */
  31987. ~ArrowButton();
  31988. juce_UseDebuggingNewOperator
  31989. protected:
  31990. /** @internal */
  31991. void paintButton (Graphics& g,
  31992. bool isMouseOverButton,
  31993. bool isButtonDown);
  31994. /** @internal */
  31995. void buttonStateChanged();
  31996. private:
  31997. Colour colour;
  31998. DropShadowEffect shadow;
  31999. Path path;
  32000. int offset;
  32001. ArrowButton (const ArrowButton&);
  32002. ArrowButton& operator= (const ArrowButton&);
  32003. };
  32004. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  32005. /*** End of inlined file: juce_ArrowButton.h ***/
  32006. #endif
  32007. #ifndef __JUCE_BUTTON_JUCEHEADER__
  32008. #endif
  32009. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32010. /*** Start of inlined file: juce_DrawableButton.h ***/
  32011. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32012. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32013. /*** Start of inlined file: juce_Drawable.h ***/
  32014. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  32015. #define __JUCE_DRAWABLE_JUCEHEADER__
  32016. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  32017. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32018. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32019. /**
  32020. Expresses a coordinate as an absolute or proportional distance from other
  32021. named coordinates.
  32022. A RelativeCoordinate represents a position as either:
  32023. - an absolute distance from the origin
  32024. - an absolute distance from another named RelativeCoordinate
  32025. - a proportion of the distance between two other named RelativeCoordinates
  32026. Of course, the coordinates that this one is relative to may themselves be relative
  32027. to other coordinates, so complex arrangements can be built up (as long as you're careful
  32028. not to create recursive loops!)
  32029. Rather than keeping pointers to the coordinates that this one is dependent on, it
  32030. stores their names, and when resolving this coordinate to an absolute value, a
  32031. NamedCoordinateFinder class is required to retrieve these coordinates by name.
  32032. @see RelativePoint, RelativeRectangle
  32033. */
  32034. class JUCE_API RelativeCoordinate
  32035. {
  32036. public:
  32037. /** Creates a zero coordinate. */
  32038. RelativeCoordinate();
  32039. /** Creates an absolute position from the parent origin on either the X or Y axis.
  32040. @param absoluteDistanceFromOrigin the distance from the origin
  32041. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  32042. */
  32043. RelativeCoordinate (double absoluteDistanceFromOrigin);
  32044. /** Creates an absolute position relative to a named coordinate.
  32045. @param absoluteDistanceFromAnchor the distance to add to the named anchor point
  32046. @param anchorPoint the name of the coordinate from which this one will be relative. See the constructor
  32047. notes for a description of the syntax for coordinate names.
  32048. */
  32049. RelativeCoordinate (double absoluteDistanceFromAnchor, const String& anchorPoint);
  32050. /** Creates a relative position between two named points.
  32051. @param relativeProportionBetweenAnchors a value between 0 and 1 indicating this coordinate's relative position
  32052. between anchorPoint1 and anchorPoint2.
  32053. @param anchorPoint1 the name of the first coordinate from which this one will be relative. See the constructor
  32054. notes for a description of the syntax for coordinate names.
  32055. @param anchorPoint2 the name of the first coordinate from which this one will be relative. See the constructor
  32056. notes for a description of the syntax for coordinate names.
  32057. */
  32058. RelativeCoordinate (double relativeProportionBetweenAnchors, const String& anchorPoint1, const String& anchorPoint2);
  32059. /** Recreates a coordinate from a string description.
  32060. The string can be in one of the following formats:
  32061. - "123" = 123 pixels from parent origin (this is equivalent to "parent.left + 123"
  32062. or "parent.top + 123", depending on which axis the coordinate is using)
  32063. - "anchor" = the same position as the coordinate named "anchor"
  32064. - "anchor + 123" = the coordinate named "anchor" + 123 pixels
  32065. - "anchor - 123" = the coordinate named "anchor" - 123 pixels
  32066. - "50%" = 50% of the distance between the coordinate space's top-left origin and its extent
  32067. (this is equivalent to "50% * parent.left -> parent.right" or "50% * parent.top -> parent.bottom")
  32068. - "50% * anchor" = 50% of the distance between the coordinate space's origin and the coordinate named "anchor"
  32069. (this is equivalent to "50% * parent.left -> anchor" or "50% * parent.top -> anchor")
  32070. - "50% * anchor1 -> anchor2" = 50% of the distance between the coordinate "anchor1" and the coordinate "anchor2"
  32071. An anchor name can either be just a single identifier (letters, digits and underscores only - no spaces),
  32072. e.g. "marker1", or it can be a two-part name in the form "objectName.edge". For example "parent.left" is
  32073. the origin, or "myComponent.top" is the top edge of a component called "myComponent". The exact names that
  32074. will be recognised are dependent on the NamedCoordinateFinder that you provide for looking them up, but
  32075. "parent.left" and "parent.top" are always available, meaning the origin. "parent.right" and "parent.bottom"
  32076. may also be available if the coordinate space has a fixed size.
  32077. @param stringVersion the string to parse
  32078. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  32079. @see toString
  32080. */
  32081. RelativeCoordinate (const String& stringVersion, bool isHorizontal);
  32082. /** Destructor. */
  32083. ~RelativeCoordinate();
  32084. bool operator== (const RelativeCoordinate& other) const throw();
  32085. bool operator!= (const RelativeCoordinate& other) const throw();
  32086. /**
  32087. Provides an interface for looking up the position of a named anchor when resolving a RelativeCoordinate.
  32088. When using RelativeCoordinates, to resolve their names you need to provide a subclass of this which
  32089. can retrieve a coordinate by name.
  32090. */
  32091. class JUCE_API NamedCoordinateFinder
  32092. {
  32093. public:
  32094. /** Destructor. */
  32095. virtual ~NamedCoordinateFinder() {}
  32096. /** Returns the coordinate for a given name.
  32097. The objectName parameter will be the first section of the name, and the edge the name of the second part.
  32098. E.g. for "parent.right", objectName would be "parent" and edge would be "right". If the name
  32099. has no dot, the edge parameter will be an empty string.
  32100. This method must be able to resolve "parent.left", "parent.top", "parent.right" and "parent.bottom", as
  32101. well as any other objects that your application uses.
  32102. */
  32103. virtual const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const = 0;
  32104. };
  32105. /** Calculates the absolute position of this coordinate.
  32106. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32107. be needed to calculate the result.
  32108. */
  32109. double resolve (const NamedCoordinateFinder* nameFinder) const;
  32110. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  32111. This will recursively check any coordinates upon which this one depends.
  32112. */
  32113. bool references (const String& coordName, const NamedCoordinateFinder* nameFinder) const;
  32114. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  32115. bool isRecursive (const NamedCoordinateFinder* nameFinder) const;
  32116. /** Returns true if this coordinate depends on any other coordinates for its position. */
  32117. bool isDynamic() const;
  32118. /** Changes the value of this coord to make it resolve to the specified position.
  32119. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  32120. or relative position to whatever value is necessary to make its resultant position
  32121. match the position that is provided.
  32122. */
  32123. void moveToAbsolute (double absoluteTargetPosition, const NamedCoordinateFinder* nameFinder);
  32124. /** Returns true if the coordinate is calculated as a proportion of the distance between two other points.
  32125. @see toggleProportionality
  32126. */
  32127. bool isProportional() const throw() { return anchor2.isNotEmpty(); }
  32128. /** Toggles the coordinate between using a proportional or absolute position.
  32129. Note that calling this will reset the names of any anchor points, and just make the
  32130. coordinate relative to the parent origin and parent size.
  32131. */
  32132. void toggleProportionality (const NamedCoordinateFinder* nameFinder,
  32133. const String& proportionalAnchor1, const String& proportionalAnchor2);
  32134. /** Returns a value that can be edited to set this coordinate's position.
  32135. The meaning of this number depends on the coordinate's mode. If the coordinate is
  32136. proportional, the number will be a percentage between 0 and 100. If the
  32137. coordinate is absolute, then it will be the number of pixels from its anchor point.
  32138. @see setEditableNumber
  32139. */
  32140. const double getEditableNumber() const;
  32141. /** Sets the value that controls this coordinate's position.
  32142. The meaning of this number depends on the coordinate's mode. If the coordinate is
  32143. proportional, the number must be a percentage between 0 and 100. If the
  32144. coordinate is absolute, then it indicates the number of pixels from its anchor point.
  32145. @see setEditableNumber
  32146. */
  32147. void setEditableNumber (const double newValue);
  32148. /** Returns the name of the first anchor point from which this coordinate is relative.
  32149. */
  32150. const String getAnchorName1 (const String& returnValueIfOrigin) const;
  32151. /** Returns the name of the second anchor point from which this coordinate is relative.
  32152. The second anchor is only valid if the coordinate is in proportional mode.
  32153. */
  32154. const String getAnchorName2 (const String& returnValueIfOrigin) const;
  32155. /** Returns the first anchor point as a coordinate. */
  32156. const RelativeCoordinate getAnchorCoordinate1() const;
  32157. /** Returns the first anchor point as a coordinate.
  32158. The second anchor is only valid if the coordinate is in proportional mode.
  32159. */
  32160. const RelativeCoordinate getAnchorCoordinate2() const;
  32161. /** Changes the first anchor point, keeping the resultant position of this coordinate in
  32162. the same place it was previously.
  32163. */
  32164. void changeAnchor1 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  32165. /** Changes the second anchor point, keeping the resultant position of this coordinate in
  32166. the same place it was previously.
  32167. */
  32168. void changeAnchor2 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  32169. /** Tells the coordinate that an object is changing its name or being deleted.
  32170. If either of this coordinates anchor points match this name, they will be replaced.
  32171. If the newName string is empty, it indicates that the object is being removed, so if
  32172. this coordinate was using it, the coordinate is changed to be relative to the origin
  32173. instead.
  32174. */
  32175. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32176. const NamedCoordinateFinder* nameFinder);
  32177. /** Returns a string which represents this coordinate.
  32178. For details of the string syntax, see the constructor notes.
  32179. */
  32180. const String toString() const;
  32181. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  32182. As well as avoiding using string literals in your code, using these preset values
  32183. has the advantage that all instances of the same string will share the same, reference-counted
  32184. String object, so if you have thousands of points which all refer to the same
  32185. anchor points, this can save a significant amount of memory allocation.
  32186. */
  32187. struct Strings
  32188. {
  32189. static const String parent; /**< "parent" */
  32190. static const String left; /**< "left" */
  32191. static const String right; /**< "right" */
  32192. static const String top; /**< "top" */
  32193. static const String bottom; /**< "bottom" */
  32194. static const String parentLeft; /**< "parent.left" */
  32195. static const String parentTop; /**< "parent.top" */
  32196. static const String parentRight; /**< "parent.right" */
  32197. static const String parentBottom; /**< "parent.bottom" */
  32198. };
  32199. private:
  32200. String anchor1, anchor2;
  32201. double value;
  32202. double resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const;
  32203. static double resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter);
  32204. };
  32205. /**
  32206. An X-Y position stored as a pair of RelativeCoordinate values.
  32207. @see RelativeCoordinate, RelativeRectangle
  32208. */
  32209. class JUCE_API RelativePoint
  32210. {
  32211. public:
  32212. /** Creates a point at the origin. */
  32213. RelativePoint();
  32214. /** Creates an absolute point, relative to the origin. */
  32215. RelativePoint (const Point<float>& absolutePoint);
  32216. /** Creates an absolute point, relative to the origin. */
  32217. RelativePoint (float absoluteX, float absoluteY);
  32218. /** Creates an absolute point from two coordinates. */
  32219. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  32220. /** Creates a point from a stringified representation.
  32221. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  32222. strings is explained in the RelativeCoordinate class.
  32223. @see toString
  32224. */
  32225. RelativePoint (const String& stringVersion);
  32226. bool operator== (const RelativePoint& other) const throw();
  32227. bool operator!= (const RelativePoint& other) const throw();
  32228. /** Calculates the absolute position of this point.
  32229. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32230. be needed to calculate the result.
  32231. */
  32232. const Point<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  32233. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  32234. Calling this will leave any anchor points unchanged, but will set any absolute
  32235. or relative positions to whatever values are necessary to make the resultant position
  32236. match the position that is provided.
  32237. */
  32238. void moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32239. /** Returns a string which represents this point.
  32240. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  32241. coordinates, see the RelativeCoordinate constructor notes.
  32242. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  32243. */
  32244. const String toString() const;
  32245. /** Tells the point that an object is changing its name or being deleted.
  32246. This calls RelativeCoordinate::renameAnchorIfUsed() on its X and Y coordinates.
  32247. */
  32248. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32249. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32250. /** Returns true if this point depends on any other coordinates for its position. */
  32251. bool isDynamic() const;
  32252. // The actual X and Y coords...
  32253. RelativeCoordinate x, y;
  32254. };
  32255. /**
  32256. An rectangle stored as a set of RelativeCoordinate values.
  32257. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  32258. @see RelativeCoordinate, RelativePoint
  32259. */
  32260. class JUCE_API RelativeRectangle
  32261. {
  32262. public:
  32263. /** Creates a zero-size rectangle at the origin. */
  32264. RelativeRectangle();
  32265. /** Creates an absolute rectangle, relative to the origin. */
  32266. explicit RelativeRectangle (const Rectangle<float>& rect, const String& componentName);
  32267. /** Creates a rectangle from four coordinates. */
  32268. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  32269. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  32270. /** Creates a rectangle from a stringified representation.
  32271. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  32272. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  32273. RelativeCoordinate class.
  32274. @see toString
  32275. */
  32276. explicit RelativeRectangle (const String& stringVersion);
  32277. bool operator== (const RelativeRectangle& other) const throw();
  32278. bool operator!= (const RelativeRectangle& other) const throw();
  32279. /** Calculates the absolute position of this rectangle.
  32280. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32281. be needed to calculate the result.
  32282. */
  32283. const Rectangle<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  32284. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  32285. Calling this will leave any anchor points unchanged, but will set any absolute
  32286. or relative positions to whatever values are necessary to make the resultant position
  32287. match the position that is provided.
  32288. */
  32289. void moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32290. /** Returns a string which represents this point.
  32291. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  32292. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  32293. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  32294. */
  32295. const String toString() const;
  32296. /** Tells the rectangle that an object is changing its name or being deleted.
  32297. This calls RelativeCoordinate::renameAnchorIfUsed() on the rectangle's coordinates.
  32298. */
  32299. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32300. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32301. // The actual rectangle coords...
  32302. RelativeCoordinate left, right, top, bottom;
  32303. };
  32304. /**
  32305. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  32306. One of these paths can be converted into a Path object for drawing and manipulation, but
  32307. unlike a Path, its points can be dynamic instead of just fixed.
  32308. @see RelativePoint, RelativeCoordinate
  32309. */
  32310. class JUCE_API RelativePointPath
  32311. {
  32312. public:
  32313. RelativePointPath();
  32314. RelativePointPath (const RelativePointPath& other);
  32315. RelativePointPath (const ValueTree& drawable);
  32316. RelativePointPath (const Path& path);
  32317. ~RelativePointPath();
  32318. /** Resolves this points in this path and adds them to a normal Path object. */
  32319. void createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32320. /** Returns true if the path contains any non-fixed points. */
  32321. bool containsAnyDynamicPoints() const;
  32322. /** Writes the path to this drawable encoding. */
  32323. void writeTo (ValueTree state, UndoManager* undoManager) const;
  32324. /** Quickly swaps the contents of this path with another. */
  32325. void swapWith (RelativePointPath& other) throw();
  32326. /** The types of element that may be contained in this path.
  32327. @see RelativePointPath::ElementBase
  32328. */
  32329. enum ElementType
  32330. {
  32331. nullElement,
  32332. startSubPathElement,
  32333. closeSubPathElement,
  32334. lineToElement,
  32335. quadraticToElement,
  32336. cubicToElement
  32337. };
  32338. /** Base class for the elements that make up a RelativePointPath.
  32339. */
  32340. class JUCE_API ElementBase
  32341. {
  32342. public:
  32343. ElementBase (ElementType type);
  32344. virtual ~ElementBase() {}
  32345. virtual const ValueTree createTree() const = 0;
  32346. virtual void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const = 0;
  32347. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  32348. const ElementType type;
  32349. private:
  32350. ElementBase (const ElementBase&);
  32351. ElementBase& operator= (const ElementBase&);
  32352. };
  32353. class JUCE_API StartSubPath : public ElementBase
  32354. {
  32355. public:
  32356. StartSubPath (const RelativePoint& pos);
  32357. ~StartSubPath() {}
  32358. const ValueTree createTree() const;
  32359. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32360. RelativePoint* getControlPoints (int& numPoints);
  32361. RelativePoint startPos;
  32362. private:
  32363. StartSubPath (const StartSubPath&);
  32364. StartSubPath& operator= (const StartSubPath&);
  32365. };
  32366. class JUCE_API CloseSubPath : public ElementBase
  32367. {
  32368. public:
  32369. CloseSubPath();
  32370. ~CloseSubPath() {}
  32371. const ValueTree createTree() const;
  32372. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32373. RelativePoint* getControlPoints (int& numPoints);
  32374. private:
  32375. CloseSubPath (const CloseSubPath&);
  32376. CloseSubPath& operator= (const CloseSubPath&);
  32377. };
  32378. class JUCE_API LineTo : public ElementBase
  32379. {
  32380. public:
  32381. LineTo (const RelativePoint& endPoint);
  32382. ~LineTo() {}
  32383. const ValueTree createTree() const;
  32384. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32385. RelativePoint* getControlPoints (int& numPoints);
  32386. RelativePoint endPoint;
  32387. private:
  32388. LineTo (const LineTo&);
  32389. LineTo& operator= (const LineTo&);
  32390. };
  32391. class JUCE_API QuadraticTo : public ElementBase
  32392. {
  32393. public:
  32394. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  32395. ~QuadraticTo() {}
  32396. const ValueTree createTree() const;
  32397. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32398. RelativePoint* getControlPoints (int& numPoints);
  32399. RelativePoint controlPoints[2];
  32400. private:
  32401. QuadraticTo (const QuadraticTo&);
  32402. QuadraticTo& operator= (const QuadraticTo&);
  32403. };
  32404. class JUCE_API CubicTo : public ElementBase
  32405. {
  32406. public:
  32407. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  32408. ~CubicTo() {}
  32409. const ValueTree createTree() const;
  32410. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32411. RelativePoint* getControlPoints (int& numPoints);
  32412. RelativePoint controlPoints[3];
  32413. private:
  32414. CubicTo (const CubicTo&);
  32415. CubicTo& operator= (const CubicTo&);
  32416. };
  32417. OwnedArray <ElementBase> elements;
  32418. bool usesNonZeroWinding;
  32419. private:
  32420. bool containsDynamicPoints;
  32421. void parse (const ValueTree& state);
  32422. RelativePointPath& operator= (const RelativePointPath&);
  32423. };
  32424. /**
  32425. A parallelogram defined by three RelativePoint positions.
  32426. @see RelativePoint, RelativeCoordinate
  32427. */
  32428. class JUCE_API RelativeParallelogram
  32429. {
  32430. public:
  32431. RelativeParallelogram();
  32432. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  32433. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  32434. ~RelativeParallelogram();
  32435. void resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32436. void resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32437. const Rectangle<float> getBounds (RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32438. void getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32439. const AffineTransform resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32440. bool operator== (const RelativeParallelogram& other) const throw();
  32441. bool operator!= (const RelativeParallelogram& other) const throw();
  32442. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  32443. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  32444. RelativePoint topLeft, topRight, bottomLeft;
  32445. };
  32446. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32447. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  32448. class DrawableComposite;
  32449. /**
  32450. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  32451. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32452. */
  32453. class JUCE_API Drawable
  32454. {
  32455. protected:
  32456. /** The base class can't be instantiated directly.
  32457. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32458. */
  32459. Drawable();
  32460. public:
  32461. /** Destructor. */
  32462. virtual ~Drawable();
  32463. /** Creates a deep copy of this Drawable object.
  32464. Use this to create a new copy of this and any sub-objects in the tree.
  32465. */
  32466. virtual Drawable* createCopy() const = 0;
  32467. /** Renders this Drawable object.
  32468. @see drawWithin
  32469. */
  32470. void draw (Graphics& g, float opacity,
  32471. const AffineTransform& transform = AffineTransform::identity) const;
  32472. /** Renders the Drawable at a given offset within the Graphics context.
  32473. The co-ordinates passed-in are used to translate the object relative to its own
  32474. origin before drawing it - this is basically a quick way of saying:
  32475. @code
  32476. draw (g, AffineTransform::translation (x, y)).
  32477. @endcode
  32478. */
  32479. void drawAt (Graphics& g,
  32480. float x, float y,
  32481. float opacity) const;
  32482. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  32483. changing its aspect-ratio.
  32484. The object can placed arbitrarily within the rectangle based on a Justification type,
  32485. and can either be made as big as possible, or just reduced to fit.
  32486. @param g the graphics context to render onto
  32487. @param destX top-left of the target rectangle to fit it into
  32488. @param destY top-left of the target rectangle to fit it into
  32489. @param destWidth size of the target rectangle to fit the image into
  32490. @param destHeight size of the target rectangle to fit the image into
  32491. @param placement defines the alignment and rescaling to use to fit
  32492. this object within the target rectangle.
  32493. @param opacity the opacity to use, in the range 0 to 1.0
  32494. */
  32495. void drawWithin (Graphics& g,
  32496. int destX,
  32497. int destY,
  32498. int destWidth,
  32499. int destHeight,
  32500. const RectanglePlacement& placement,
  32501. float opacity) const;
  32502. /** Holds the information needed when telling a drawable to render itself.
  32503. @see Drawable::draw
  32504. */
  32505. class RenderingContext
  32506. {
  32507. public:
  32508. RenderingContext (Graphics& g, const AffineTransform& transform, float opacity) throw();
  32509. Graphics& g;
  32510. AffineTransform transform;
  32511. float opacity;
  32512. private:
  32513. RenderingContext& operator= (const RenderingContext&);
  32514. };
  32515. /** Renders this Drawable object.
  32516. @see draw
  32517. */
  32518. virtual void render (const RenderingContext& context) const = 0;
  32519. /** Returns the smallest rectangle that can contain this Drawable object.
  32520. Co-ordinates are relative to the object's own origin.
  32521. */
  32522. virtual const Rectangle<float> getBounds() const = 0;
  32523. /** Returns true if the given point is somewhere inside this Drawable.
  32524. Co-ordinates are relative to the object's own origin.
  32525. */
  32526. virtual bool hitTest (float x, float y) const = 0;
  32527. /** Returns the name given to this drawable.
  32528. @see setName
  32529. */
  32530. const String& getName() const throw() { return name; }
  32531. /** Assigns a name to this drawable. */
  32532. void setName (const String& newName) throw() { name = newName; }
  32533. /** Returns the DrawableComposite that contains this object, if there is one. */
  32534. DrawableComposite* getParent() const throw() { return parent; }
  32535. /** Tries to turn some kind of image file into a drawable.
  32536. The data could be an image that the ImageFileFormat class understands, or it
  32537. could be SVG.
  32538. */
  32539. static Drawable* createFromImageData (const void* data, size_t numBytes);
  32540. /** Tries to turn a stream containing some kind of image data into a drawable.
  32541. The data could be an image that the ImageFileFormat class understands, or it
  32542. could be SVG.
  32543. */
  32544. static Drawable* createFromImageDataStream (InputStream& dataSource);
  32545. /** Tries to turn a file containing some kind of image data into a drawable.
  32546. The data could be an image that the ImageFileFormat class understands, or it
  32547. could be SVG.
  32548. */
  32549. static Drawable* createFromImageFile (const File& file);
  32550. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  32551. into a Drawable tree.
  32552. The object returned must be deleted by the caller. If something goes wrong
  32553. while parsing, it may return 0.
  32554. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  32555. implementation, but it can return the basic vector objects.
  32556. */
  32557. static Drawable* createFromSVG (const XmlElement& svgDocument);
  32558. /** This class is used when loading Drawables that contain images, and retrieves
  32559. the image for a stored identifier.
  32560. @see Drawable::createFromValueTree
  32561. */
  32562. class JUCE_API ImageProvider
  32563. {
  32564. public:
  32565. ImageProvider() {}
  32566. virtual ~ImageProvider() {}
  32567. /** Retrieves the image associated with this identifier, which could be any
  32568. kind of string, number, filename, etc.
  32569. The image that is returned will be owned by the caller, but it may come
  32570. from the ImageCache.
  32571. */
  32572. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  32573. /** Returns an identifier to be used to refer to a given image.
  32574. This is used when converting a drawable into a ValueTree, so if you're
  32575. only loading drawables, you can just return a var::null here.
  32576. */
  32577. virtual const var getIdentifierForImage (const Image& image) = 0;
  32578. };
  32579. /** Tries to create a Drawable from a previously-saved ValueTree.
  32580. The ValueTree must have been created by the createValueTree() method.
  32581. If there are any images used within the drawable, you'll need to provide a valid
  32582. ImageProvider object that can be used to retrieve these images from whatever type
  32583. of identifier is used to represent them.
  32584. */
  32585. static Drawable* createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  32586. /** Tries to refresh a Drawable from the same ValueTree that was used to create it.
  32587. @returns the damage rectangle that will need repainting due to any changes that were made.
  32588. */
  32589. virtual const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider) = 0;
  32590. /** Creates a ValueTree to represent this Drawable.
  32591. The VarTree that is returned can be turned back into a Drawable with
  32592. createFromValueTree().
  32593. If there are any images used in this drawable, you'll need to provide a valid
  32594. ImageProvider object that can be used to create storable representations of them.
  32595. */
  32596. virtual const ValueTree createValueTree (ImageProvider* imageProvider) const = 0;
  32597. /** Returns the tag ID that is used for a ValueTree that stores this type of drawable. */
  32598. virtual const Identifier getValueTreeType() const = 0;
  32599. /** Internal class used to manage ValueTrees that represent Drawables. */
  32600. class ValueTreeWrapperBase
  32601. {
  32602. public:
  32603. ValueTreeWrapperBase (const ValueTree& state);
  32604. ~ValueTreeWrapperBase();
  32605. ValueTree& getState() throw() { return state; }
  32606. const String getID() const;
  32607. void setID (const String& newID, UndoManager* undoManager);
  32608. static const Identifier idProperty;
  32609. static const FillType readFillType (const ValueTree& v, RelativePoint* gradientPoint1,
  32610. RelativePoint* gradientPoint2, RelativePoint* gradientPoint3,
  32611. RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  32612. ImageProvider* imageProvider);
  32613. static void writeFillType (ValueTree& v, const FillType& fillType,
  32614. const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  32615. const RelativePoint* gradientPoint3, ImageProvider* imageProvider,
  32616. UndoManager* undoManager);
  32617. ValueTree state;
  32618. static const Identifier type, gradientPoint1, gradientPoint2, gradientPoint3,
  32619. colour, radial, colours, imageId, imageOpacity;
  32620. };
  32621. juce_UseDebuggingNewOperator
  32622. protected:
  32623. friend class DrawableComposite;
  32624. DrawableComposite* parent;
  32625. virtual void invalidatePoints() = 0;
  32626. static Drawable* createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider);
  32627. private:
  32628. String name;
  32629. Drawable (const Drawable&);
  32630. Drawable& operator= (const Drawable&);
  32631. };
  32632. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  32633. /*** End of inlined file: juce_Drawable.h ***/
  32634. /**
  32635. A button that displays a Drawable.
  32636. Up to three Drawable objects can be given to this button, to represent the
  32637. 'normal', 'over' and 'down' states.
  32638. @see Button
  32639. */
  32640. class JUCE_API DrawableButton : public Button
  32641. {
  32642. public:
  32643. enum ButtonStyle
  32644. {
  32645. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  32646. ImageRaw, /**< The button will just display the images in their normal size and position.
  32647. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  32648. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  32649. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  32650. };
  32651. /** Creates a DrawableButton.
  32652. After creating one of these, use setImages() to specify the drawables to use.
  32653. @param buttonName the name to give the component
  32654. @param buttonStyle the layout to use
  32655. @see ButtonStyle, setButtonStyle, setImages
  32656. */
  32657. DrawableButton (const String& buttonName,
  32658. ButtonStyle buttonStyle);
  32659. /** Destructor. */
  32660. ~DrawableButton();
  32661. /** Sets up the images to draw for the various button states.
  32662. The button will keep its own internal copies of these drawables.
  32663. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  32664. will be made of the object passed-in if it is non-zero.
  32665. @param overImage the thing to draw for the button's 'over' state - if this is
  32666. zero, the button's normal image will be used when the mouse is
  32667. over it. An internal copy will be made of the object passed-in
  32668. if it is non-zero.
  32669. @param downImage the thing to draw for the button's 'down' state - if this is
  32670. zero, the 'over' image will be used instead (or the normal image
  32671. as a last resort). An internal copy will be made of the object
  32672. passed-in if it is non-zero.
  32673. @param disabledImage an image to draw when the button is disabled. If this is zero,
  32674. the normal image will be drawn with a reduced opacity instead.
  32675. An internal copy will be made of the object passed-in if it is
  32676. non-zero.
  32677. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  32678. state is 'on'. If this is 0, the normal image is used instead
  32679. @param overImageOn same as the overImage, but this is used when the button's toggle
  32680. state is 'on'. If this is 0, the normalImageOn is drawn instead
  32681. @param downImageOn same as the downImage, but this is used when the button's toggle
  32682. state is 'on'. If this is 0, the overImageOn is drawn instead
  32683. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  32684. state is 'on'. If this is 0, the normal image will be drawn instead
  32685. with a reduced opacity
  32686. */
  32687. void setImages (const Drawable* normalImage,
  32688. const Drawable* overImage = 0,
  32689. const Drawable* downImage = 0,
  32690. const Drawable* disabledImage = 0,
  32691. const Drawable* normalImageOn = 0,
  32692. const Drawable* overImageOn = 0,
  32693. const Drawable* downImageOn = 0,
  32694. const Drawable* disabledImageOn = 0);
  32695. /** Changes the button's style.
  32696. @see ButtonStyle
  32697. */
  32698. void setButtonStyle (ButtonStyle newStyle);
  32699. /** Changes the button's background colours.
  32700. The toggledOffColour is the colour to use when the button's toggle state
  32701. is off, and toggledOnColour when it's on.
  32702. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  32703. used to fill the background of the component.
  32704. For an ImageOnButtonBackground style, the colour is used to draw the
  32705. button's lozenge shape and exactly how the colour's used will depend
  32706. on the LookAndFeel.
  32707. */
  32708. void setBackgroundColours (const Colour& toggledOffColour,
  32709. const Colour& toggledOnColour);
  32710. /** Returns the current background colour being used.
  32711. @see setBackgroundColour
  32712. */
  32713. const Colour& getBackgroundColour() const throw();
  32714. /** Gives the button an optional amount of space around the edge of the drawable.
  32715. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  32716. ones on a button background. If the button is too small for the given gap, a
  32717. smaller gap will be used.
  32718. By default there's a gap of about 3 pixels.
  32719. */
  32720. void setEdgeIndent (int numPixelsIndent);
  32721. /** Returns the image that the button is currently displaying. */
  32722. const Drawable* getCurrentImage() const throw();
  32723. const Drawable* getNormalImage() const throw();
  32724. const Drawable* getOverImage() const throw();
  32725. const Drawable* getDownImage() const throw();
  32726. juce_UseDebuggingNewOperator
  32727. protected:
  32728. /** @internal */
  32729. void paintButton (Graphics& g,
  32730. bool isMouseOverButton,
  32731. bool isButtonDown);
  32732. private:
  32733. ButtonStyle style;
  32734. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  32735. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  32736. Colour backgroundOff, backgroundOn;
  32737. int edgeIndent;
  32738. void deleteImages();
  32739. DrawableButton (const DrawableButton&);
  32740. DrawableButton& operator= (const DrawableButton&);
  32741. };
  32742. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32743. /*** End of inlined file: juce_DrawableButton.h ***/
  32744. #endif
  32745. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32746. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  32747. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32748. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32749. /**
  32750. A button showing an underlined weblink, that will launch the link
  32751. when it's clicked.
  32752. @see Button
  32753. */
  32754. class JUCE_API HyperlinkButton : public Button
  32755. {
  32756. public:
  32757. /** Creates a HyperlinkButton.
  32758. @param linkText the text that will be displayed in the button - this is
  32759. also set as the Component's name, but the text can be
  32760. changed later with the Button::getButtonText() method
  32761. @param linkURL the URL to launch when the user clicks the button
  32762. */
  32763. HyperlinkButton (const String& linkText,
  32764. const URL& linkURL);
  32765. /** Destructor. */
  32766. ~HyperlinkButton();
  32767. /** Changes the font to use for the text.
  32768. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  32769. to match the size of the component.
  32770. */
  32771. void setFont (const Font& newFont,
  32772. bool resizeToMatchComponentHeight,
  32773. const Justification& justificationType = Justification::horizontallyCentred);
  32774. /** A set of colour IDs to use to change the colour of various aspects of the link.
  32775. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32776. methods.
  32777. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32778. */
  32779. enum ColourIds
  32780. {
  32781. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  32782. };
  32783. /** Changes the URL that the button will trigger. */
  32784. void setURL (const URL& newURL) throw();
  32785. /** Returns the URL that the button will trigger. */
  32786. const URL& getURL() const throw() { return url; }
  32787. /** Resizes the button horizontally to fit snugly around the text.
  32788. This won't affect the button's height.
  32789. */
  32790. void changeWidthToFitText();
  32791. juce_UseDebuggingNewOperator
  32792. protected:
  32793. /** @internal */
  32794. void clicked();
  32795. /** @internal */
  32796. void colourChanged();
  32797. /** @internal */
  32798. void paintButton (Graphics& g,
  32799. bool isMouseOverButton,
  32800. bool isButtonDown);
  32801. private:
  32802. URL url;
  32803. Font font;
  32804. bool resizeFont;
  32805. Justification justification;
  32806. const Font getFontToUse() const;
  32807. HyperlinkButton (const HyperlinkButton&);
  32808. HyperlinkButton& operator= (const HyperlinkButton&);
  32809. };
  32810. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32811. /*** End of inlined file: juce_HyperlinkButton.h ***/
  32812. #endif
  32813. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32814. /*** Start of inlined file: juce_ImageButton.h ***/
  32815. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32816. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  32817. /**
  32818. As the title suggests, this is a button containing an image.
  32819. The colour and transparency of the image can be set to vary when the
  32820. button state changes.
  32821. @see Button, ShapeButton, TextButton
  32822. */
  32823. class JUCE_API ImageButton : public Button
  32824. {
  32825. public:
  32826. /** Creates an ImageButton.
  32827. Use setImage() to specify the image to use. The colours and opacities that
  32828. are specified here can be changed later using setDrawingOptions().
  32829. @param name the name to give the component
  32830. */
  32831. explicit ImageButton (const String& name);
  32832. /** Destructor. */
  32833. ~ImageButton();
  32834. /** Sets up the images to draw in various states.
  32835. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  32836. resized to the same dimensions as the normal image
  32837. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  32838. button when the button's size changes
  32839. @param preserveImageProportions if true then any rescaling of the image to fit
  32840. the button will keep the image's x and y proportions
  32841. correct - i.e. it won't distort its shape, although
  32842. this might create gaps around the edges
  32843. @param normalImage the image to use when the button is in its normal state.
  32844. button no longer needs it.
  32845. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  32846. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  32847. normal image - if this colour is transparent, no overlay
  32848. will be drawn. The overlay will be drawn over the top of the
  32849. image, so you can basically add a solid or semi-transparent
  32850. colour to the image to brighten or darken it
  32851. @param overImage the image to use when the mouse is over the button. If
  32852. you want to use the same image as was set in the normalImage
  32853. parameter, this value can be a null image.
  32854. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  32855. is over the button
  32856. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  32857. image when the mouse is over - if this colour is transparent,
  32858. no overlay will be drawn
  32859. @param downImage an image to use when the button is pressed down. If set
  32860. to a null image, the 'over' image will be drawn instead (or the
  32861. normal image if there isn't an 'over' image either).
  32862. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  32863. is pressed
  32864. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  32865. image when the button is pressed down - if this colour is
  32866. transparent, no overlay will be drawn
  32867. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  32868. whenever it's inside the button's bounding rectangle. If
  32869. set to values higher than 0, the mouse will only be
  32870. considered to be over the image when the value of the
  32871. image's alpha channel at that position is greater than
  32872. this level.
  32873. */
  32874. void setImages (bool resizeButtonNowToFitThisImage,
  32875. bool rescaleImagesWhenButtonSizeChanges,
  32876. bool preserveImageProportions,
  32877. const Image& normalImage,
  32878. float imageOpacityWhenNormal,
  32879. const Colour& overlayColourWhenNormal,
  32880. const Image& overImage,
  32881. float imageOpacityWhenOver,
  32882. const Colour& overlayColourWhenOver,
  32883. const Image& downImage,
  32884. float imageOpacityWhenDown,
  32885. const Colour& overlayColourWhenDown,
  32886. float hitTestAlphaThreshold = 0.0f);
  32887. /** Returns the currently set 'normal' image. */
  32888. const Image getNormalImage() const;
  32889. /** Returns the image that's drawn when the mouse is over the button.
  32890. If a valid 'over' image has been set, this will return it; otherwise it'll
  32891. just return the normal image.
  32892. */
  32893. const Image getOverImage() const;
  32894. /** Returns the image that's drawn when the button is held down.
  32895. If a valid 'down' image has been set, this will return it; otherwise it'll
  32896. return the 'over' image or normal image, depending on what's available.
  32897. */
  32898. const Image getDownImage() const;
  32899. juce_UseDebuggingNewOperator
  32900. protected:
  32901. /** @internal */
  32902. bool hitTest (int x, int y);
  32903. /** @internal */
  32904. void paintButton (Graphics& g,
  32905. bool isMouseOverButton,
  32906. bool isButtonDown);
  32907. private:
  32908. bool scaleImageToFit, preserveProportions;
  32909. unsigned char alphaThreshold;
  32910. int imageX, imageY, imageW, imageH;
  32911. Image normalImage, overImage, downImage;
  32912. float normalOpacity, overOpacity, downOpacity;
  32913. Colour normalOverlay, overOverlay, downOverlay;
  32914. const Image getCurrentImage() const;
  32915. ImageButton (const ImageButton&);
  32916. ImageButton& operator= (const ImageButton&);
  32917. };
  32918. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  32919. /*** End of inlined file: juce_ImageButton.h ***/
  32920. #endif
  32921. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32922. /*** Start of inlined file: juce_ShapeButton.h ***/
  32923. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32924. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  32925. /**
  32926. A button that contains a filled shape.
  32927. @see Button, ImageButton, TextButton, ArrowButton
  32928. */
  32929. class JUCE_API ShapeButton : public Button
  32930. {
  32931. public:
  32932. /** Creates a ShapeButton.
  32933. @param name a name to give the component - see Component::setName()
  32934. @param normalColour the colour to fill the shape with when the mouse isn't over
  32935. @param overColour the colour to use when the mouse is over the shape
  32936. @param downColour the colour to use when the button is in the pressed-down state
  32937. */
  32938. ShapeButton (const String& name,
  32939. const Colour& normalColour,
  32940. const Colour& overColour,
  32941. const Colour& downColour);
  32942. /** Destructor. */
  32943. ~ShapeButton();
  32944. /** Sets the shape to use.
  32945. @param newShape the shape to use
  32946. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  32947. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  32948. the button is resized
  32949. @param hasDropShadow if true, the button will be given a drop-shadow effect
  32950. */
  32951. void setShape (const Path& newShape,
  32952. bool resizeNowToFitThisShape,
  32953. bool maintainShapeProportions,
  32954. bool hasDropShadow);
  32955. /** Set the colours to use for drawing the shape.
  32956. @param normalColour the colour to fill the shape with when the mouse isn't over
  32957. @param overColour the colour to use when the mouse is over the shape
  32958. @param downColour the colour to use when the button is in the pressed-down state
  32959. */
  32960. void setColours (const Colour& normalColour,
  32961. const Colour& overColour,
  32962. const Colour& downColour);
  32963. /** Sets up an outline to draw around the shape.
  32964. @param outlineColour the colour to use
  32965. @param outlineStrokeWidth the thickness of line to draw
  32966. */
  32967. void setOutline (const Colour& outlineColour,
  32968. float outlineStrokeWidth);
  32969. juce_UseDebuggingNewOperator
  32970. protected:
  32971. /** @internal */
  32972. void paintButton (Graphics& g,
  32973. bool isMouseOverButton,
  32974. bool isButtonDown);
  32975. private:
  32976. Colour normalColour, overColour, downColour, outlineColour;
  32977. DropShadowEffect shadow;
  32978. Path shape;
  32979. bool maintainShapeProportions;
  32980. float outlineWidth;
  32981. ShapeButton (const ShapeButton&);
  32982. ShapeButton& operator= (const ShapeButton&);
  32983. };
  32984. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  32985. /*** End of inlined file: juce_ShapeButton.h ***/
  32986. #endif
  32987. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  32988. #endif
  32989. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32990. /*** Start of inlined file: juce_ToggleButton.h ***/
  32991. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32992. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32993. /**
  32994. A button that can be toggled on/off.
  32995. All buttons can be toggle buttons, but this lets you create one of the
  32996. standard ones which has a tick-box and a text label next to it.
  32997. @see Button, DrawableButton, TextButton
  32998. */
  32999. class JUCE_API ToggleButton : public Button
  33000. {
  33001. public:
  33002. /** Creates a ToggleButton.
  33003. @param buttonText the text to put in the button (the component's name is also
  33004. initially set to this string, but these can be changed later
  33005. using the setName() and setButtonText() methods)
  33006. */
  33007. explicit ToggleButton (const String& buttonText = String::empty);
  33008. /** Destructor. */
  33009. ~ToggleButton();
  33010. /** Resizes the button to fit neatly around its current text.
  33011. The button's height won't be affected, only its width.
  33012. */
  33013. void changeWidthToFitText();
  33014. /** A set of colour IDs to use to change the colour of various aspects of the button.
  33015. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33016. methods.
  33017. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33018. */
  33019. enum ColourIds
  33020. {
  33021. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  33022. };
  33023. juce_UseDebuggingNewOperator
  33024. protected:
  33025. /** @internal */
  33026. void paintButton (Graphics& g,
  33027. bool isMouseOverButton,
  33028. bool isButtonDown);
  33029. /** @internal */
  33030. void colourChanged();
  33031. private:
  33032. ToggleButton (const ToggleButton&);
  33033. ToggleButton& operator= (const ToggleButton&);
  33034. };
  33035. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33036. /*** End of inlined file: juce_ToggleButton.h ***/
  33037. #endif
  33038. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33039. /*** Start of inlined file: juce_ToolbarButton.h ***/
  33040. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33041. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33042. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  33043. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33044. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33045. /*** Start of inlined file: juce_Toolbar.h ***/
  33046. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  33047. #define __JUCE_TOOLBAR_JUCEHEADER__
  33048. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  33049. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33050. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33051. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  33052. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33053. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33054. /**
  33055. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  33056. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  33057. derive your component from this class, and make sure that it is somewhere inside a
  33058. DragAndDropContainer component.
  33059. Note: If all that you need to do is to respond to files being drag-and-dropped from
  33060. the operating system onto your component, you don't need any of these classes: instead
  33061. see the FileDragAndDropTarget class.
  33062. @see DragAndDropContainer, FileDragAndDropTarget
  33063. */
  33064. class JUCE_API DragAndDropTarget
  33065. {
  33066. public:
  33067. /** Destructor. */
  33068. virtual ~DragAndDropTarget() {}
  33069. /** Callback to check whether this target is interested in the type of object being
  33070. dragged.
  33071. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33072. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33073. @returns true if this component wants to receive the other callbacks regarging this
  33074. type of object; if it returns false, no other callbacks will be made.
  33075. */
  33076. virtual bool isInterestedInDragSource (const String& sourceDescription,
  33077. Component* sourceComponent) = 0;
  33078. /** Callback to indicate that something is being dragged over this component.
  33079. This gets called when the user moves the mouse into this component while dragging
  33080. something.
  33081. Use this callback as a trigger to make your component repaint itself to give the
  33082. user feedback about whether the item can be dropped here or not.
  33083. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33084. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33085. @param x the mouse x position, relative to this component
  33086. @param y the mouse y position, relative to this component
  33087. @see itemDragExit
  33088. */
  33089. virtual void itemDragEnter (const String& sourceDescription,
  33090. Component* sourceComponent,
  33091. int x, int y);
  33092. /** Callback to indicate that the user is dragging something over this component.
  33093. This gets called when the user moves the mouse over this component while dragging
  33094. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  33095. this lets you know what happens in-between.
  33096. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33097. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33098. @param x the mouse x position, relative to this component
  33099. @param y the mouse y position, relative to this component
  33100. */
  33101. virtual void itemDragMove (const String& sourceDescription,
  33102. Component* sourceComponent,
  33103. int x, int y);
  33104. /** Callback to indicate that something has been dragged off the edge of this component.
  33105. This gets called when the user moves the mouse out of this component while dragging
  33106. something.
  33107. If you've used itemDragEnter() to repaint your component and give feedback, use this
  33108. as a signal to repaint it in its normal state.
  33109. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33110. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33111. @see itemDragEnter
  33112. */
  33113. virtual void itemDragExit (const String& sourceDescription,
  33114. Component* sourceComponent);
  33115. /** Callback to indicate that the user has dropped something onto this component.
  33116. When the user drops an item this get called, and you can use the description to
  33117. work out whether your object wants to deal with it or not.
  33118. Note that after this is called, the itemDragExit method may not be called, so you should
  33119. clean up in here if there's anything you need to do when the drag finishes.
  33120. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33121. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33122. @param x the mouse x position, relative to this component
  33123. @param y the mouse y position, relative to this component
  33124. */
  33125. virtual void itemDropped (const String& sourceDescription,
  33126. Component* sourceComponent,
  33127. int x, int y) = 0;
  33128. /** Overriding this allows the target to tell the drag container whether to
  33129. draw the drag image while the cursor is over it.
  33130. By default it returns true, but if you return false, then the normal drag
  33131. image will not be shown when the cursor is over this target.
  33132. */
  33133. virtual bool shouldDrawDragImageWhenOver();
  33134. };
  33135. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33136. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  33137. /**
  33138. Enables drag-and-drop behaviour for a component and all its sub-components.
  33139. For a component to be able to make or receive drag-and-drop events, one of its parent
  33140. components must derive from this class. It's probably best for the top-level
  33141. component to implement it.
  33142. Then to start a drag operation, any sub-component can just call the startDragging()
  33143. method, and this object will take over, tracking the mouse and sending appropriate
  33144. callbacks to any child components derived from DragAndDropTarget which the mouse
  33145. moves over.
  33146. Note: If all that you need to do is to respond to files being drag-and-dropped from
  33147. the operating system onto your component, you don't need any of these classes: you can do this
  33148. simply by overriding Component::filesDropped().
  33149. @see DragAndDropTarget
  33150. */
  33151. class JUCE_API DragAndDropContainer
  33152. {
  33153. public:
  33154. /** Creates a DragAndDropContainer.
  33155. The object that derives from this class must also be a Component.
  33156. */
  33157. DragAndDropContainer();
  33158. /** Destructor. */
  33159. virtual ~DragAndDropContainer();
  33160. /** Begins a drag-and-drop operation.
  33161. This starts a drag-and-drop operation - call it when the user drags the
  33162. mouse in your drag-source component, and this object will track mouse
  33163. movements until the user lets go of the mouse button, and will send
  33164. appropriate messages to DragAndDropTarget objects that the mouse moves
  33165. over.
  33166. findParentDragContainerFor() is a handy method to call to find the
  33167. drag container to use for a component.
  33168. @param sourceDescription a string to use as the description of the thing being
  33169. dragged - this will be passed to the objects that might be
  33170. dropped-onto so they can decide if they want to handle it or
  33171. not
  33172. @param sourceComponent the component that is being dragged
  33173. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  33174. a snapshot of the sourceComponent will be used instead.
  33175. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  33176. window, and can be dragged to DragAndDropTargets that are the
  33177. children of components other than this one.
  33178. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  33179. at which the image should be drawn from the mouse. If it isn't
  33180. specified, then the image will be centred around the mouse. If
  33181. an image hasn't been passed-in, this will be ignored.
  33182. */
  33183. void startDragging (const String& sourceDescription,
  33184. Component* sourceComponent,
  33185. const Image& dragImage = Image(),
  33186. bool allowDraggingToOtherJuceWindows = false,
  33187. const Point<int>* imageOffsetFromMouse = 0);
  33188. /** Returns true if something is currently being dragged. */
  33189. bool isDragAndDropActive() const;
  33190. /** Returns the description of the thing that's currently being dragged.
  33191. If nothing's being dragged, this will return an empty string, otherwise it's the
  33192. string that was passed into startDragging().
  33193. @see startDragging
  33194. */
  33195. const String getCurrentDragDescription() const;
  33196. /** Utility to find the DragAndDropContainer for a given Component.
  33197. This will search up this component's parent hierarchy looking for the first
  33198. parent component which is a DragAndDropContainer.
  33199. It's useful when a component wants to call startDragging but doesn't know
  33200. the DragAndDropContainer it should to use.
  33201. Obviously this may return 0 if it doesn't find a suitable component.
  33202. */
  33203. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  33204. /** This performs a synchronous drag-and-drop of a set of files to some external
  33205. application.
  33206. You can call this function in response to a mouseDrag callback, and it will
  33207. block, running its own internal message loop and tracking the mouse, while it
  33208. uses a native operating system drag-and-drop operation to move or copy some
  33209. files to another application.
  33210. @param files a list of filenames to drag
  33211. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  33212. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  33213. @returns true if the files were successfully dropped somewhere, or false if it
  33214. was interrupted
  33215. @see performExternalDragDropOfText
  33216. */
  33217. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  33218. /** This performs a synchronous drag-and-drop of a block of text to some external
  33219. application.
  33220. You can call this function in response to a mouseDrag callback, and it will
  33221. block, running its own internal message loop and tracking the mouse, while it
  33222. uses a native operating system drag-and-drop operation to move or copy some
  33223. text to another application.
  33224. @param text the text to copy
  33225. @returns true if the text was successfully dropped somewhere, or false if it
  33226. was interrupted
  33227. @see performExternalDragDropOfFiles
  33228. */
  33229. static bool performExternalDragDropOfText (const String& text);
  33230. juce_UseDebuggingNewOperator
  33231. protected:
  33232. /** Override this if you want to be able to perform an external drag a set of files
  33233. when the user drags outside of this container component.
  33234. This method will be called when a drag operation moves outside the Juce-based window,
  33235. and if you want it to then perform a file drag-and-drop, add the filenames you want
  33236. to the array passed in, and return true.
  33237. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  33238. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  33239. @param files on return, the filenames you want to drag
  33240. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  33241. it must make a copy of them (see the performExternalDragDropOfFiles()
  33242. method)
  33243. @see performExternalDragDropOfFiles
  33244. */
  33245. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  33246. Component* dragSourceComponent,
  33247. StringArray& files,
  33248. bool& canMoveFiles);
  33249. private:
  33250. friend class DragImageComponent;
  33251. ScopedPointer <Component> dragImageComponent;
  33252. String currentDragDesc;
  33253. };
  33254. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33255. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  33256. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  33257. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33258. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33259. /**
  33260. Animates a set of components, moving it to a new position.
  33261. To use this, create a ComponentAnimator, and use its animateComponent() method
  33262. to tell it to move components to destination positions. Any number of
  33263. components can be animated by one ComponentAnimator object (if you've got a
  33264. lot of components to move, it's much more efficient to share a single animator
  33265. than to have many animators running at once).
  33266. You'll need to make sure the animator object isn't deleted before it finishes
  33267. moving the components.
  33268. The class is a ChangeBroadcaster and sends a notification when any components
  33269. start or finish being animated.
  33270. */
  33271. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  33272. private Timer
  33273. {
  33274. public:
  33275. /** Creates a ComponentAnimator. */
  33276. ComponentAnimator();
  33277. /** Destructor. */
  33278. ~ComponentAnimator();
  33279. /** Starts a component moving from its current position to a specified position.
  33280. If the component is already in the middle of an animation, that will be abandoned,
  33281. and a new animation will begin, moving the component from its current location.
  33282. The start and end speed parameters let you apply some acceleration to the component's
  33283. movement.
  33284. @param component the component to move
  33285. @param finalPosition the destination position and size to move it to
  33286. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  33287. to arrive at its destination
  33288. @param startSpeed a value to indicate the relative start speed of the
  33289. animation. If this is 0, the component will start
  33290. by accelerating from rest; higher values mean that it
  33291. will have an initial speed greater than zero. If the
  33292. value if greater than 1, it will decelerate towards the
  33293. middle of its journey. To move the component at a constant
  33294. rate for its entire animation, set both the start and
  33295. end speeds to 1.0
  33296. @param endSpeed a relative speed at which the component should be moving
  33297. when the animation finishes. If this is 0, the component
  33298. will decelerate to a standstill at its final position; higher
  33299. values mean the component will still be moving when it stops.
  33300. To move the component at a constant rate for its entire
  33301. animation, set both the start and end speeds to 1.0
  33302. */
  33303. void animateComponent (Component* component,
  33304. const Rectangle<int>& finalPosition,
  33305. int millisecondsToSpendMoving,
  33306. double startSpeed = 1.0,
  33307. double endSpeed = 1.0);
  33308. /** Stops a component if it's currently being animated.
  33309. If moveComponentToItsFinalPosition is true, then the component will
  33310. be immediately moved to its destination position and size. If false, it will be
  33311. left in whatever location it currently occupies.
  33312. */
  33313. void cancelAnimation (Component* component,
  33314. bool moveComponentToItsFinalPosition);
  33315. /** Clears all of the active animations.
  33316. If moveComponentsToTheirFinalPositions is true, all the components will
  33317. be immediately set to their final positions. If false, they will be
  33318. left in whatever locations they currently occupy.
  33319. */
  33320. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  33321. /** Returns the destination position for a component.
  33322. If the component is being animated, this will return the target position that
  33323. was specified when animateComponent() was called.
  33324. If the specified component isn't currently being animated, this method will just
  33325. return its current position.
  33326. */
  33327. const Rectangle<int> getComponentDestination (Component* component);
  33328. /** Returns true if the specified component is currently being animated.
  33329. */
  33330. bool isAnimating (Component* component) const;
  33331. juce_UseDebuggingNewOperator
  33332. private:
  33333. class AnimationTask;
  33334. Array <AnimationTask*> tasks;
  33335. uint32 lastTime;
  33336. AnimationTask* findTaskFor (Component* component) const;
  33337. void timerCallback();
  33338. };
  33339. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33340. /*** End of inlined file: juce_ComponentAnimator.h ***/
  33341. class ToolbarItemComponent;
  33342. class ToolbarItemFactory;
  33343. class MissingItemsComponent;
  33344. /**
  33345. A toolbar component.
  33346. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  33347. and looks after their order and layout.
  33348. Items (icon buttons or other custom components) are added to a toolbar using a
  33349. ToolbarItemFactory - each type of item is given a unique ID number, and a
  33350. toolbar might contain more than one instance of a particular item type.
  33351. Toolbars can be interactively customised, allowing the user to drag the items
  33352. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  33353. component as a source of new items.
  33354. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  33355. */
  33356. class JUCE_API Toolbar : public Component,
  33357. public DragAndDropContainer,
  33358. public DragAndDropTarget,
  33359. private ButtonListener
  33360. {
  33361. public:
  33362. /** Creates an empty toolbar component.
  33363. To add some icons or other components to your toolbar, you'll need to
  33364. create a ToolbarItemFactory class that can create a suitable set of
  33365. ToolbarItemComponents.
  33366. @see ToolbarItemFactory, ToolbarItemComponents
  33367. */
  33368. Toolbar();
  33369. /** Destructor.
  33370. Any items on the bar will be deleted when the toolbar is deleted.
  33371. */
  33372. ~Toolbar();
  33373. /** Changes the bar's orientation.
  33374. @see isVertical
  33375. */
  33376. void setVertical (bool shouldBeVertical);
  33377. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  33378. You can change the bar's orientation with setVertical().
  33379. */
  33380. bool isVertical() const throw() { return vertical; }
  33381. /** Returns the depth of the bar.
  33382. If the bar is horizontal, this will return its height; if it's vertical, it
  33383. will return its width.
  33384. @see getLength
  33385. */
  33386. int getThickness() const throw();
  33387. /** Returns the length of the bar.
  33388. If the bar is horizontal, this will return its width; if it's vertical, it
  33389. will return its height.
  33390. @see getThickness
  33391. */
  33392. int getLength() const throw();
  33393. /** Deletes all items from the bar.
  33394. */
  33395. void clear();
  33396. /** Adds an item to the toolbar.
  33397. The factory's ToolbarItemFactory::createItem() will be called by this method
  33398. to create the component that will actually be added to the bar.
  33399. The new item will be inserted at the specified index (if the index is -1, it
  33400. will be added to the right-hand or bottom end of the bar).
  33401. Once added, the component will be automatically deleted by this object when it
  33402. is no longer needed.
  33403. @see ToolbarItemFactory
  33404. */
  33405. void addItem (ToolbarItemFactory& factory,
  33406. int itemId,
  33407. int insertIndex = -1);
  33408. /** Deletes one of the items from the bar.
  33409. */
  33410. void removeToolbarItem (int itemIndex);
  33411. /** Returns the number of items currently on the toolbar.
  33412. @see getItemId, getItemComponent
  33413. */
  33414. int getNumItems() const throw();
  33415. /** Returns the ID of the item with the given index.
  33416. If the index is less than zero or greater than the number of items,
  33417. this will return 0.
  33418. @see getNumItems
  33419. */
  33420. int getItemId (int itemIndex) const throw();
  33421. /** Returns the component being used for the item with the given index.
  33422. If the index is less than zero or greater than the number of items,
  33423. this will return 0.
  33424. @see getNumItems
  33425. */
  33426. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  33427. /** Clears this toolbar and adds to it the default set of items that the specified
  33428. factory creates.
  33429. @see ToolbarItemFactory::getDefaultItemSet
  33430. */
  33431. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  33432. /** Options for the way items should be displayed.
  33433. @see setStyle, getStyle
  33434. */
  33435. enum ToolbarItemStyle
  33436. {
  33437. iconsOnly, /**< Means that the toolbar should just contain icons. */
  33438. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  33439. textOnly /**< Means that the toolbar only display text labels for each item. */
  33440. };
  33441. /** Returns the toolbar's current style.
  33442. @see ToolbarItemStyle, setStyle
  33443. */
  33444. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33445. /** Changes the toolbar's current style.
  33446. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  33447. */
  33448. void setStyle (const ToolbarItemStyle& newStyle);
  33449. /** Flags used by the showCustomisationDialog() method. */
  33450. enum CustomisationFlags
  33451. {
  33452. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  33453. show the "icons only" option on its choice of toolbar styles. */
  33454. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  33455. show the "icons with text" option on its choice of toolbar styles. */
  33456. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  33457. show the "text only" option on its choice of toolbar styles. */
  33458. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  33459. show a button to reset the toolbar to its default set of items. */
  33460. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  33461. };
  33462. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  33463. The dialog contains a ToolbarItemPalette and various controls for editing other
  33464. aspects of the toolbar. This method will block and run the dialog box modally,
  33465. returning when the user closes it.
  33466. The factory is used to determine the set of items that will be shown on the
  33467. palette.
  33468. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  33469. enum.
  33470. @see ToolbarItemPalette
  33471. */
  33472. void showCustomisationDialog (ToolbarItemFactory& factory,
  33473. int optionFlags = allCustomisationOptionsEnabled);
  33474. /** Turns on or off the toolbar's editing mode, in which its items can be
  33475. rearranged by the user.
  33476. (In most cases it's easier just to use showCustomisationDialog() instead of
  33477. trying to enable editing directly).
  33478. @see ToolbarItemPalette
  33479. */
  33480. void setEditingActive (bool editingEnabled);
  33481. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  33482. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33483. methods.
  33484. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33485. */
  33486. enum ColourIds
  33487. {
  33488. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  33489. more control over this, override LookAndFeel::paintToolbarBackground(). */
  33490. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  33491. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  33492. over them. */
  33493. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  33494. held down on them. */
  33495. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  33496. when the style is set to iconsWithText or textOnly. */
  33497. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  33498. the customisation dialog is active and the mouse moves over them. */
  33499. };
  33500. /** Returns a string that represents the toolbar's current set of items.
  33501. This lets you later restore the same item layout using restoreFromString().
  33502. @see restoreFromString
  33503. */
  33504. const String toString() const;
  33505. /** Restores a set of items that was previously stored in a string by the toString()
  33506. method.
  33507. The factory object is used to create any item components that are needed.
  33508. @see toString
  33509. */
  33510. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  33511. const String& savedVersion);
  33512. /** @internal */
  33513. void paint (Graphics& g);
  33514. /** @internal */
  33515. void resized();
  33516. /** @internal */
  33517. void buttonClicked (Button*);
  33518. /** @internal */
  33519. void mouseDown (const MouseEvent&);
  33520. /** @internal */
  33521. bool isInterestedInDragSource (const String&, Component*);
  33522. /** @internal */
  33523. void itemDragMove (const String&, Component*, int, int);
  33524. /** @internal */
  33525. void itemDragExit (const String&, Component*);
  33526. /** @internal */
  33527. void itemDropped (const String&, Component*, int, int);
  33528. /** @internal */
  33529. void updateAllItemPositions (const bool animate);
  33530. /** @internal */
  33531. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  33532. juce_UseDebuggingNewOperator
  33533. private:
  33534. Button* missingItemsButton;
  33535. bool vertical, isEditingActive;
  33536. ToolbarItemStyle toolbarStyle;
  33537. ComponentAnimator animator;
  33538. friend class MissingItemsComponent;
  33539. Array <ToolbarItemComponent*> items;
  33540. friend class ItemDragAndDropOverlayComponent;
  33541. static const char* const toolbarDragDescriptor;
  33542. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  33543. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  33544. Toolbar (const Toolbar&);
  33545. Toolbar& operator= (const Toolbar&);
  33546. };
  33547. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  33548. /*** End of inlined file: juce_Toolbar.h ***/
  33549. class ItemDragAndDropOverlayComponent;
  33550. /**
  33551. A component that can be used as one of the items in a Toolbar.
  33552. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  33553. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  33554. class for further info about creating them.
  33555. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  33556. components too. To do this, set the value of isBeingUsedAsAButton to false when
  33557. calling the constructor, and override contentAreaChanged(), in which you can position
  33558. any sub-components you need to add.
  33559. To add basic buttons without writing a special subclass, have a look at the
  33560. ToolbarButton class.
  33561. @see ToolbarButton, Toolbar, ToolbarItemFactory
  33562. */
  33563. class JUCE_API ToolbarItemComponent : public Button
  33564. {
  33565. public:
  33566. /** Constructor.
  33567. @param itemId the ID of the type of toolbar item which this represents
  33568. @param labelText the text to display if the toolbar's style is set to
  33569. Toolbar::iconsWithText or Toolbar::textOnly
  33570. @param isBeingUsedAsAButton set this to false if you don't want the button
  33571. to draw itself with button over/down states when the mouse
  33572. moves over it or clicks
  33573. */
  33574. ToolbarItemComponent (int itemId,
  33575. const String& labelText,
  33576. bool isBeingUsedAsAButton);
  33577. /** Destructor. */
  33578. ~ToolbarItemComponent();
  33579. /** Returns the item type ID that this component represents.
  33580. This value is in the constructor.
  33581. */
  33582. int getItemId() const throw() { return itemId; }
  33583. /** Returns the toolbar that contains this component, or 0 if it's not currently
  33584. inside one.
  33585. */
  33586. Toolbar* getToolbar() const;
  33587. /** Returns true if this component is currently inside a toolbar which is vertical.
  33588. @see Toolbar::isVertical
  33589. */
  33590. bool isToolbarVertical() const;
  33591. /** Returns the current style setting of this item.
  33592. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  33593. @see setStyle, Toolbar::getStyle
  33594. */
  33595. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33596. /** Changes the current style setting of this item.
  33597. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  33598. by the toolbar that holds this item.
  33599. @see setStyle, Toolbar::setStyle
  33600. */
  33601. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  33602. /** Returns the area of the component that should be used to display the button image or
  33603. other contents of the item.
  33604. This content area may change when the item's style changes, and may leave a space around the
  33605. edge of the component where the text label can be shown.
  33606. @see contentAreaChanged
  33607. */
  33608. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  33609. /** This method must return the size criteria for this item, based on a given toolbar
  33610. size and orientation.
  33611. The preferredSize, minSize and maxSize values must all be set by your implementation
  33612. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  33613. toolbar, they refer to the item's height.
  33614. The preferredSize is the size that the component would like to be, and this must be
  33615. between the min and max sizes. For a fixed-size item, simply set all three variables to
  33616. the same value.
  33617. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  33618. Toolbar::getThickness().
  33619. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  33620. vertically.
  33621. */
  33622. virtual bool getToolbarItemSizes (int toolbarThickness,
  33623. bool isToolbarVertical,
  33624. int& preferredSize,
  33625. int& minSize,
  33626. int& maxSize) = 0;
  33627. /** Your subclass should use this method to draw its content area.
  33628. The graphics object that is passed-in will have been clipped and had its origin
  33629. moved to fit the content area as specified get getContentArea(). The width and height
  33630. parameters are the width and height of the content area.
  33631. If the component you're writing isn't a button, you can just do nothing in this method.
  33632. */
  33633. virtual void paintButtonArea (Graphics& g,
  33634. int width, int height,
  33635. bool isMouseOver, bool isMouseDown) = 0;
  33636. /** Callback to indicate that the content area of this item has changed.
  33637. This might be because the component was resized, or because the style changed and
  33638. the space needed for the text label is different.
  33639. See getContentArea() for a description of what the area is.
  33640. */
  33641. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  33642. /** Editing modes.
  33643. These are used by setEditingMode(), but will be rarely needed in user code.
  33644. */
  33645. enum ToolbarEditingMode
  33646. {
  33647. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  33648. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  33649. customisation mode, and the items can be dragged around. */
  33650. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  33651. dragged onto a toolbar to add it to that bar.*/
  33652. };
  33653. /** Changes the editing mode of this component.
  33654. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33655. and is unlikely to be of much use in end-user-code.
  33656. */
  33657. void setEditingMode (const ToolbarEditingMode newMode);
  33658. /** Returns the current editing mode of this component.
  33659. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33660. and is unlikely to be of much use in end-user-code.
  33661. */
  33662. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  33663. /** @internal */
  33664. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  33665. /** @internal */
  33666. void resized();
  33667. juce_UseDebuggingNewOperator
  33668. private:
  33669. friend class Toolbar;
  33670. friend class ItemDragAndDropOverlayComponent;
  33671. const int itemId;
  33672. ToolbarEditingMode mode;
  33673. Toolbar::ToolbarItemStyle toolbarStyle;
  33674. ScopedPointer <Component> overlayComp;
  33675. int dragOffsetX, dragOffsetY;
  33676. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  33677. Rectangle<int> contentArea;
  33678. ToolbarItemComponent (const ToolbarItemComponent&);
  33679. ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  33680. };
  33681. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33682. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  33683. /**
  33684. A type of button designed to go on a toolbar.
  33685. This simple button can have two Drawable objects specified - one for normal
  33686. use and another one (optionally) for the button's "on" state if it's a
  33687. toggle button.
  33688. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  33689. */
  33690. class JUCE_API ToolbarButton : public ToolbarItemComponent
  33691. {
  33692. public:
  33693. /** Creates a ToolbarButton.
  33694. @param itemId the ID for this toolbar item type. This is passed through to the
  33695. ToolbarItemComponent constructor
  33696. @param labelText the text to display on the button (if the toolbar is using a style
  33697. that shows text labels). This is passed through to the
  33698. ToolbarItemComponent constructor
  33699. @param normalImage a drawable object that the button should use as its icon. The object
  33700. that is passed-in here will be kept by this object and will be
  33701. deleted when no longer needed or when this button is deleted.
  33702. @param toggledOnImage a drawable object that the button can use as its icon if the button
  33703. is in a toggled-on state (see the Button::getToggleState() method). If
  33704. 0 is passed-in here, then the normal image will be used instead, regardless
  33705. of the toggle state. The object that is passed-in here will be kept by
  33706. this object and will be deleted when no longer needed or when this button
  33707. is deleted.
  33708. */
  33709. ToolbarButton (int itemId,
  33710. const String& labelText,
  33711. Drawable* normalImage,
  33712. Drawable* toggledOnImage);
  33713. /** Destructor. */
  33714. ~ToolbarButton();
  33715. /** @internal */
  33716. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  33717. int& minSize, int& maxSize);
  33718. /** @internal */
  33719. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  33720. /** @internal */
  33721. void contentAreaChanged (const Rectangle<int>& newBounds);
  33722. juce_UseDebuggingNewOperator
  33723. private:
  33724. ScopedPointer <Drawable> normalImage, toggledOnImage;
  33725. ToolbarButton (const ToolbarButton&);
  33726. ToolbarButton& operator= (const ToolbarButton&);
  33727. };
  33728. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33729. /*** End of inlined file: juce_ToolbarButton.h ***/
  33730. #endif
  33731. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33732. /*** Start of inlined file: juce_CodeDocument.h ***/
  33733. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33734. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  33735. class CodeDocumentLine;
  33736. /**
  33737. A class for storing and manipulating a source code file.
  33738. When using a CodeEditorComponent, it takes one of these as its source object.
  33739. The CodeDocument stores its content as an array of lines, which makes it
  33740. quick to insert and delete.
  33741. @see CodeEditorComponent
  33742. */
  33743. class JUCE_API CodeDocument
  33744. {
  33745. public:
  33746. /** Creates a new, empty document.
  33747. */
  33748. CodeDocument();
  33749. /** Destructor. */
  33750. ~CodeDocument();
  33751. /** A position in a code document.
  33752. Using this class you can find a position in a code document and quickly get its
  33753. character position, line, and index. By calling setPositionMaintained (true), the
  33754. position is automatically updated when text is inserted or deleted in the document,
  33755. so that it maintains its original place in the text.
  33756. */
  33757. class JUCE_API Position
  33758. {
  33759. public:
  33760. /** Creates an uninitialised postion.
  33761. Don't attempt to call any methods on this until you've given it an owner document
  33762. to refer to!
  33763. */
  33764. Position() throw();
  33765. /** Creates a position based on a line and index in a document.
  33766. Note that this index is NOT the column number, it's the number of characters from the
  33767. start of the line. The "column" number isn't quite the same, because if the line
  33768. contains any tab characters, the relationship of the index to its visual column depends on
  33769. the number of spaces per tab being used!
  33770. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33771. they will be adjusted to keep them within its limits.
  33772. */
  33773. Position (const CodeDocument* ownerDocument,
  33774. int line, int indexInLine) throw();
  33775. /** Creates a position based on a character index in a document.
  33776. This position is placed at the specified number of characters from the start of the
  33777. document. The line and column are auto-calculated.
  33778. If the position is beyond the range of the document, it'll be adjusted to keep it
  33779. inside.
  33780. */
  33781. Position (const CodeDocument* ownerDocument,
  33782. int charactersFromStartOfDocument) throw();
  33783. /** Creates a copy of another position.
  33784. This will copy the position, but the new object will not be set to maintain its position,
  33785. even if the source object was set to do so.
  33786. */
  33787. Position (const Position& other) throw();
  33788. /** Destructor. */
  33789. ~Position() throw();
  33790. Position& operator= (const Position& other) throw();
  33791. bool operator== (const Position& other) const throw();
  33792. bool operator!= (const Position& other) const throw();
  33793. /** Points this object at a new position within the document.
  33794. If the position is beyond the range of the document, it'll be adjusted to keep it
  33795. inside.
  33796. @see getPosition, setLineAndIndex
  33797. */
  33798. void setPosition (int charactersFromStartOfDocument) throw();
  33799. /** Returns the position as the number of characters from the start of the document.
  33800. @see setPosition, getLineNumber, getIndexInLine
  33801. */
  33802. int getPosition() const throw() { return characterPos; }
  33803. /** Moves the position to a new line and index within the line.
  33804. Note that the index is NOT the column at which the position appears in an editor.
  33805. If the line contains any tab characters, the relationship of the index to its
  33806. visual position depends on the number of spaces per tab being used!
  33807. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33808. they will be adjusted to keep them within its limits.
  33809. */
  33810. void setLineAndIndex (int newLine, int newIndexInLine) throw();
  33811. /** Returns the line number of this position.
  33812. The first line in the document is numbered zero, not one!
  33813. */
  33814. int getLineNumber() const throw() { return line; }
  33815. /** Returns the number of characters from the start of the line.
  33816. Note that this value is NOT the column at which the position appears in an editor.
  33817. If the line contains any tab characters, the relationship of the index to its
  33818. visual position depends on the number of spaces per tab being used!
  33819. */
  33820. int getIndexInLine() const throw() { return indexInLine; }
  33821. /** Allows the position to be automatically updated when the document changes.
  33822. If this is set to true, the positon will register with its document so that
  33823. when the document has text inserted or deleted, this position will be automatically
  33824. moved to keep it at the same position in the text.
  33825. */
  33826. void setPositionMaintained (bool isMaintained) throw();
  33827. /** Moves the position forwards or backwards by the specified number of characters.
  33828. @see movedBy
  33829. */
  33830. void moveBy (int characterDelta) throw();
  33831. /** Returns a position which is the same as this one, moved by the specified number of
  33832. characters.
  33833. @see moveBy
  33834. */
  33835. const Position movedBy (int characterDelta) const throw();
  33836. /** Returns a position which is the same as this one, moved up or down by the specified
  33837. number of lines.
  33838. @see movedBy
  33839. */
  33840. const Position movedByLines (int deltaLines) const throw();
  33841. /** Returns the character in the document at this position.
  33842. @see getLineText
  33843. */
  33844. const juce_wchar getCharacter() const throw();
  33845. /** Returns the line from the document that this position is within.
  33846. @see getCharacter, getLineNumber
  33847. */
  33848. const String getLineText() const throw();
  33849. private:
  33850. CodeDocument* owner;
  33851. int characterPos, line, indexInLine;
  33852. bool positionMaintained;
  33853. };
  33854. /** Returns the full text of the document. */
  33855. const String getAllContent() const throw();
  33856. /** Returns a section of the document's text. */
  33857. const String getTextBetween (const Position& start, const Position& end) const throw();
  33858. /** Returns a line from the document. */
  33859. const String getLine (int lineIndex) const throw();
  33860. /** Returns the number of characters in the document. */
  33861. int getNumCharacters() const throw();
  33862. /** Returns the number of lines in the document. */
  33863. int getNumLines() const throw() { return lines.size(); }
  33864. /** Returns the number of characters in the longest line of the document. */
  33865. int getMaximumLineLength() throw();
  33866. /** Deletes a section of the text.
  33867. This operation is undoable.
  33868. */
  33869. void deleteSection (const Position& startPosition, const Position& endPosition);
  33870. /** Inserts some text into the document at a given position.
  33871. This operation is undoable.
  33872. */
  33873. void insertText (const Position& position, const String& text);
  33874. /** Clears the document and replaces it with some new text.
  33875. This operation is undoable - if you're trying to completely reset the document, you
  33876. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  33877. */
  33878. void replaceAllContent (const String& newContent);
  33879. /** Replaces the editor's contents with the contents of a stream.
  33880. This will also reset the undo history and save point marker.
  33881. */
  33882. bool loadFromStream (InputStream& stream);
  33883. /** Writes the editor's current contents to a stream. */
  33884. bool writeToStream (OutputStream& stream);
  33885. /** Returns the preferred new-line characters for the document.
  33886. This will be either "\n", "\r\n", or (rarely) "\r".
  33887. @see setNewLineCharacters
  33888. */
  33889. const String getNewLineCharacters() const throw() { return newLineChars; }
  33890. /** Sets the new-line characters that the document should use.
  33891. The string must be either "\n", "\r\n", or (rarely) "\r".
  33892. @see getNewLineCharacters
  33893. */
  33894. void setNewLineCharacters (const String& newLine) throw();
  33895. /** Begins a new undo transaction.
  33896. The document itself will not call this internally, so relies on whatever is using the
  33897. document to periodically call this to break up the undo sequence into sensible chunks.
  33898. @see UndoManager::beginNewTransaction
  33899. */
  33900. void newTransaction();
  33901. /** Undo the last operation.
  33902. @see UndoManager::undo
  33903. */
  33904. void undo();
  33905. /** Redo the last operation.
  33906. @see UndoManager::redo
  33907. */
  33908. void redo();
  33909. /** Clears the undo history.
  33910. @see UndoManager::clearUndoHistory
  33911. */
  33912. void clearUndoHistory();
  33913. /** Returns the document's UndoManager */
  33914. UndoManager& getUndoManager() throw() { return undoManager; }
  33915. /** Makes a note that the document's current state matches the one that is saved.
  33916. After this has been called, hasChangedSinceSavePoint() will return false until
  33917. the document has been altered, and then it'll start returning true. If the document is
  33918. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  33919. will again return false.
  33920. @see hasChangedSinceSavePoint
  33921. */
  33922. void setSavePoint() throw();
  33923. /** Returns true if the state of the document differs from the state it was in when
  33924. setSavePoint() was last called.
  33925. @see setSavePoint
  33926. */
  33927. bool hasChangedSinceSavePoint() const throw();
  33928. /** Searches for a word-break. */
  33929. const Position findWordBreakAfter (const Position& position) const throw();
  33930. /** Searches for a word-break. */
  33931. const Position findWordBreakBefore (const Position& position) const throw();
  33932. /** An object that receives callbacks from the CodeDocument when its text changes.
  33933. @see CodeDocument::addListener, CodeDocument::removeListener
  33934. */
  33935. class JUCE_API Listener
  33936. {
  33937. public:
  33938. Listener() {}
  33939. virtual ~Listener() {}
  33940. /** Called by a CodeDocument when it is altered.
  33941. */
  33942. virtual void codeDocumentChanged (const Position& affectedTextStart,
  33943. const Position& affectedTextEnd) = 0;
  33944. };
  33945. /** Registers a listener object to receive callbacks when the document changes.
  33946. If the listener is already registered, this method has no effect.
  33947. @see removeListener
  33948. */
  33949. void addListener (Listener* listener) throw();
  33950. /** Deregisters a listener.
  33951. @see addListener
  33952. */
  33953. void removeListener (Listener* listener) throw();
  33954. /** Iterates the text in a CodeDocument.
  33955. This class lets you read characters from a CodeDocument. It's designed to be used
  33956. by a SyntaxAnalyser object.
  33957. @see CodeDocument, SyntaxAnalyser
  33958. */
  33959. class Iterator
  33960. {
  33961. public:
  33962. Iterator (CodeDocument* document);
  33963. Iterator (const Iterator& other);
  33964. Iterator& operator= (const Iterator& other) throw();
  33965. ~Iterator() throw();
  33966. /** Reads the next character and returns it.
  33967. @see peekNextChar
  33968. */
  33969. juce_wchar nextChar();
  33970. /** Reads the next character without advancing the current position. */
  33971. juce_wchar peekNextChar() const;
  33972. /** Advances the position by one character. */
  33973. void skip();
  33974. /** Returns the position of the next character as its position within the
  33975. whole document.
  33976. */
  33977. int getPosition() const throw() { return position; }
  33978. /** Skips over any whitespace characters until the next character is non-whitespace. */
  33979. void skipWhitespace();
  33980. /** Skips forward until the next character will be the first character on the next line */
  33981. void skipToEndOfLine();
  33982. /** Returns the line number of the next character. */
  33983. int getLine() const throw() { return line; }
  33984. /** Returns true if the iterator has reached the end of the document. */
  33985. bool isEOF() const throw();
  33986. private:
  33987. CodeDocument* document;
  33988. CodeDocumentLine* currentLine;
  33989. int line, position;
  33990. };
  33991. juce_UseDebuggingNewOperator
  33992. private:
  33993. friend class CodeDocumentInsertAction;
  33994. friend class CodeDocumentDeleteAction;
  33995. friend class Iterator;
  33996. friend class Position;
  33997. OwnedArray <CodeDocumentLine> lines;
  33998. Array <Position*> positionsToMaintain;
  33999. UndoManager undoManager;
  34000. int currentActionIndex, indexOfSavedState;
  34001. int maximumLineLength;
  34002. ListenerList <Listener> listeners;
  34003. String newLineChars;
  34004. void sendListenerChangeMessage (int startLine, int endLine);
  34005. void insert (const String& text, int insertPos, bool undoable);
  34006. void remove (int startPos, int endPos, bool undoable);
  34007. void checkLastLineStatus();
  34008. CodeDocument (const CodeDocument&);
  34009. CodeDocument& operator= (const CodeDocument&);
  34010. };
  34011. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  34012. /*** End of inlined file: juce_CodeDocument.h ***/
  34013. #endif
  34014. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34015. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  34016. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34017. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34018. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  34019. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  34020. #define __JUCE_CODETOKENISER_JUCEHEADER__
  34021. /**
  34022. A base class for tokenising code so that the syntax can be displayed in a
  34023. code editor.
  34024. @see CodeDocument, CodeEditorComponent
  34025. */
  34026. class JUCE_API CodeTokeniser
  34027. {
  34028. public:
  34029. CodeTokeniser() {}
  34030. virtual ~CodeTokeniser() {}
  34031. /** Reads the next token from the source and returns its token type.
  34032. This must leave the source pointing to the first character in the
  34033. next token.
  34034. */
  34035. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  34036. /** Returns a list of the names of the token types this analyser uses.
  34037. The index in this list must match the token type numbers that are
  34038. returned by readNextToken().
  34039. */
  34040. virtual const StringArray getTokenTypes() = 0;
  34041. /** Returns a suggested syntax highlighting colour for a specified
  34042. token type.
  34043. */
  34044. virtual const Colour getDefaultColour (int tokenType) = 0;
  34045. juce_UseDebuggingNewOperator
  34046. };
  34047. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  34048. /*** End of inlined file: juce_CodeTokeniser.h ***/
  34049. /**
  34050. A text editor component designed specifically for source code.
  34051. This is designed to handle syntax highlighting and fast editing of very large
  34052. files.
  34053. */
  34054. class JUCE_API CodeEditorComponent : public Component,
  34055. public TextInputTarget,
  34056. public Timer,
  34057. public ScrollBarListener,
  34058. public CodeDocument::Listener,
  34059. public AsyncUpdater
  34060. {
  34061. public:
  34062. /** Creates an editor for a document.
  34063. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  34064. The object that you pass in is not owned or deleted by the editor - you must
  34065. make sure that it doesn't get deleted while this component is still using it.
  34066. @see CodeDocument
  34067. */
  34068. CodeEditorComponent (CodeDocument& document,
  34069. CodeTokeniser* codeTokeniser);
  34070. /** Destructor. */
  34071. ~CodeEditorComponent();
  34072. /** Returns the code document that this component is editing. */
  34073. CodeDocument& getDocument() const throw() { return document; }
  34074. /** Loads the given content into the document.
  34075. This will completely reset the CodeDocument object, clear its undo history,
  34076. and fill it with this text.
  34077. */
  34078. void loadContent (const String& newContent);
  34079. /** Returns the standard character width. */
  34080. float getCharWidth() const throw() { return charWidth; }
  34081. /** Returns the height of a line of text, in pixels. */
  34082. int getLineHeight() const throw() { return lineHeight; }
  34083. /** Returns the number of whole lines visible on the screen,
  34084. This doesn't include a cut-off line that might be visible at the bottom if the
  34085. component's height isn't an exact multiple of the line-height.
  34086. */
  34087. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  34088. /** Returns the number of whole columns visible on the screen.
  34089. This doesn't include any cut-off columns at the right-hand edge.
  34090. */
  34091. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  34092. /** Returns the current caret position. */
  34093. const CodeDocument::Position getCaretPos() const { return caretPos; }
  34094. /** Moves the caret.
  34095. If selecting is true, the section of the document between the current
  34096. caret position and the new one will become selected. If false, any currently
  34097. selected region will be deselected.
  34098. */
  34099. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  34100. /** Returns the on-screen position of a character in the document.
  34101. The rectangle returned is relative to this component's top-left origin.
  34102. */
  34103. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const throw();
  34104. /** Finds the character at a given on-screen position.
  34105. The co-ordinates are relative to this component's top-left origin.
  34106. */
  34107. const CodeDocument::Position getPositionAt (int x, int y);
  34108. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  34109. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  34110. void cursorDown (bool selecting);
  34111. void cursorUp (bool selecting);
  34112. void pageDown (bool selecting);
  34113. void pageUp (bool selecting);
  34114. void scrollDown();
  34115. void scrollUp();
  34116. void scrollToLine (int newFirstLineOnScreen);
  34117. void scrollBy (int deltaLines);
  34118. void scrollToColumn (int newFirstColumnOnScreen);
  34119. void scrollToKeepCaretOnScreen();
  34120. void goToStartOfDocument (bool selecting);
  34121. void goToStartOfLine (bool selecting);
  34122. void goToEndOfDocument (bool selecting);
  34123. void goToEndOfLine (bool selecting);
  34124. void deselectAll();
  34125. void selectAll();
  34126. void insertTextAtCaret (const String& textToInsert);
  34127. void insertTabAtCaret();
  34128. void cut();
  34129. void copy();
  34130. void copyThenCut();
  34131. void paste();
  34132. void backspace (bool moveInWholeWordSteps);
  34133. void deleteForward (bool moveInWholeWordSteps);
  34134. void undo();
  34135. void redo();
  34136. const Range<int> getHighlightedRegion() const;
  34137. void setHighlightedRegion (const Range<int>& newRange);
  34138. const String getTextInRange (const Range<int>& range) const;
  34139. /** Changes the current tab settings.
  34140. This lets you change the tab size and whether pressing the tab key inserts a
  34141. tab character, or its equivalent number of spaces.
  34142. */
  34143. void setTabSize (int numSpacesPerTab,
  34144. bool insertSpacesInsteadOfTabCharacters) throw();
  34145. /** Returns the current number of spaces per tab.
  34146. @see setTabSize
  34147. */
  34148. int getTabSize() const throw() { return spacesPerTab; }
  34149. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  34150. @see setTabSize
  34151. */
  34152. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  34153. /** Changes the font.
  34154. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  34155. */
  34156. void setFont (const Font& newFont);
  34157. /** Returns the font that the editor is using. */
  34158. const Font& getFont() const throw() { return font; }
  34159. /** Resets the syntax highlighting colours to the default ones provided by the
  34160. code tokeniser.
  34161. @see CodeTokeniser::getDefaultColour
  34162. */
  34163. void resetToDefaultColours();
  34164. /** Changes one of the syntax highlighting colours.
  34165. The token type values are dependent on the tokeniser being used - use
  34166. CodeTokeniser::getTokenTypes() to get a list of the token types.
  34167. @see getColourForTokenType
  34168. */
  34169. void setColourForTokenType (int tokenType, const Colour& colour);
  34170. /** Returns one of the syntax highlighting colours.
  34171. The token type values are dependent on the tokeniser being used - use
  34172. CodeTokeniser::getTokenTypes() to get a list of the token types.
  34173. @see setColourForTokenType
  34174. */
  34175. const Colour getColourForTokenType (int tokenType) const throw();
  34176. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  34177. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34178. methods.
  34179. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34180. */
  34181. enum ColourIds
  34182. {
  34183. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  34184. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  34185. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  34186. selected text. */
  34187. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  34188. enabled. */
  34189. };
  34190. /** Changes the size of the scrollbars. */
  34191. void setScrollbarThickness (int thickness) throw();
  34192. /** Returns the thickness of the scrollbars. */
  34193. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  34194. /** @internal */
  34195. void resized();
  34196. /** @internal */
  34197. void paint (Graphics& g);
  34198. /** @internal */
  34199. bool keyPressed (const KeyPress& key);
  34200. /** @internal */
  34201. void mouseDown (const MouseEvent& e);
  34202. /** @internal */
  34203. void mouseDrag (const MouseEvent& e);
  34204. /** @internal */
  34205. void mouseUp (const MouseEvent& e);
  34206. /** @internal */
  34207. void mouseDoubleClick (const MouseEvent& e);
  34208. /** @internal */
  34209. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34210. /** @internal */
  34211. void focusGained (FocusChangeType cause);
  34212. /** @internal */
  34213. void focusLost (FocusChangeType cause);
  34214. /** @internal */
  34215. void timerCallback();
  34216. /** @internal */
  34217. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  34218. /** @internal */
  34219. void handleAsyncUpdate();
  34220. /** @internal */
  34221. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  34222. const CodeDocument::Position& affectedTextEnd);
  34223. /** @internal */
  34224. bool isTextInputActive() const;
  34225. juce_UseDebuggingNewOperator
  34226. private:
  34227. CodeDocument& document;
  34228. Font font;
  34229. int firstLineOnScreen, gutter, spacesPerTab;
  34230. float charWidth;
  34231. int lineHeight, linesOnScreen, columnsOnScreen;
  34232. int scrollbarThickness, columnToTryToMaintain;
  34233. bool useSpacesForTabs;
  34234. double xOffset;
  34235. CodeDocument::Position caretPos;
  34236. CodeDocument::Position selectionStart, selectionEnd;
  34237. class CaretComponent;
  34238. CaretComponent* caret;
  34239. ScrollBar* verticalScrollBar;
  34240. ScrollBar* horizontalScrollBar;
  34241. enum DragType
  34242. {
  34243. notDragging,
  34244. draggingSelectionStart,
  34245. draggingSelectionEnd
  34246. };
  34247. DragType dragType;
  34248. CodeTokeniser* codeTokeniser;
  34249. Array <Colour> coloursForTokenCategories;
  34250. class CodeEditorLine;
  34251. OwnedArray <CodeEditorLine> lines;
  34252. void rebuildLineTokens();
  34253. OwnedArray <CodeDocument::Iterator> cachedIterators;
  34254. void clearCachedIterators (int firstLineToBeInvalid) throw();
  34255. void updateCachedIterators (int maxLineNum);
  34256. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  34257. void moveLineDelta (int delta, bool selecting);
  34258. void updateScrollBars();
  34259. void scrollToLineInternal (int line);
  34260. void scrollToColumnInternal (double column);
  34261. void newTransaction();
  34262. int indexToColumn (int line, int index) const throw();
  34263. int columnToIndex (int line, int column) const throw();
  34264. CodeEditorComponent (const CodeEditorComponent&);
  34265. CodeEditorComponent& operator= (const CodeEditorComponent&);
  34266. };
  34267. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34268. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  34269. #endif
  34270. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  34271. #endif
  34272. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34273. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  34274. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34275. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34276. /**
  34277. A simple lexical analyser for syntax colouring of C++ code.
  34278. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  34279. */
  34280. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  34281. {
  34282. public:
  34283. CPlusPlusCodeTokeniser();
  34284. ~CPlusPlusCodeTokeniser();
  34285. enum TokenType
  34286. {
  34287. tokenType_error = 0,
  34288. tokenType_comment,
  34289. tokenType_builtInKeyword,
  34290. tokenType_identifier,
  34291. tokenType_integerLiteral,
  34292. tokenType_floatLiteral,
  34293. tokenType_stringLiteral,
  34294. tokenType_operator,
  34295. tokenType_bracket,
  34296. tokenType_punctuation,
  34297. tokenType_preprocessor
  34298. };
  34299. int readNextToken (CodeDocument::Iterator& source);
  34300. const StringArray getTokenTypes();
  34301. const Colour getDefaultColour (int tokenType);
  34302. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  34303. static bool isReservedKeyword (const String& token) throw();
  34304. juce_UseDebuggingNewOperator
  34305. };
  34306. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34307. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  34308. #endif
  34309. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34310. #endif
  34311. #ifndef __JUCE_LABEL_JUCEHEADER__
  34312. #endif
  34313. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34314. #endif
  34315. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34316. /*** Start of inlined file: juce_ProgressBar.h ***/
  34317. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34318. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34319. /**
  34320. A progress bar component.
  34321. To use this, just create one and make it visible. It'll run its own timer
  34322. to keep an eye on a variable that you give it, and will automatically
  34323. redraw itself when the variable changes.
  34324. For an easy way of running a background task with a dialog box showing its
  34325. progress, see the ThreadWithProgressWindow class.
  34326. @see ThreadWithProgressWindow
  34327. */
  34328. class JUCE_API ProgressBar : public Component,
  34329. public SettableTooltipClient,
  34330. private Timer
  34331. {
  34332. public:
  34333. /** Creates a ProgressBar.
  34334. @param progress pass in a reference to a double that you're going to
  34335. update with your task's progress. The ProgressBar will
  34336. monitor the value of this variable and will redraw itself
  34337. when the value changes. The range is from 0 to 1.0. Obviously
  34338. you'd better be careful not to delete this variable while the
  34339. ProgressBar still exists!
  34340. */
  34341. explicit ProgressBar (double& progress);
  34342. /** Destructor. */
  34343. ~ProgressBar();
  34344. /** Turns the percentage display on or off.
  34345. By default this is on, and the progress bar will display a text string showing
  34346. its current percentage.
  34347. */
  34348. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34349. /** Gives the progress bar a string to display inside it.
  34350. If you call this, it will turn off the percentage display.
  34351. @see setPercentageDisplay
  34352. */
  34353. void setTextToDisplay (const String& text);
  34354. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34355. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34356. methods.
  34357. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34358. */
  34359. enum ColourIds
  34360. {
  34361. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34362. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34363. classes will probably use variations on this colour. */
  34364. };
  34365. juce_UseDebuggingNewOperator
  34366. protected:
  34367. /** @internal */
  34368. void paint (Graphics& g);
  34369. /** @internal */
  34370. void lookAndFeelChanged();
  34371. /** @internal */
  34372. void visibilityChanged();
  34373. /** @internal */
  34374. void colourChanged();
  34375. private:
  34376. double& progress;
  34377. double currentValue;
  34378. bool displayPercentage;
  34379. String displayedMessage, currentMessage;
  34380. uint32 lastCallbackTime;
  34381. void timerCallback();
  34382. ProgressBar (const ProgressBar&);
  34383. ProgressBar& operator= (const ProgressBar&);
  34384. };
  34385. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34386. /*** End of inlined file: juce_ProgressBar.h ***/
  34387. #endif
  34388. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34389. /*** Start of inlined file: juce_Slider.h ***/
  34390. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34391. #define __JUCE_SLIDER_JUCEHEADER__
  34392. /*** Start of inlined file: juce_SliderListener.h ***/
  34393. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34394. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  34395. class Slider;
  34396. /**
  34397. A class for receiving callbacks from a Slider.
  34398. To be told when a slider's value changes, you can register a SliderListener
  34399. object using Slider::addListener().
  34400. @see Slider::addListener, Slider::removeListener
  34401. */
  34402. class JUCE_API SliderListener
  34403. {
  34404. public:
  34405. /** Destructor. */
  34406. virtual ~SliderListener() {}
  34407. /** Called when the slider's value is changed.
  34408. This may be caused by dragging it, or by typing in its text entry box,
  34409. or by a call to Slider::setValue().
  34410. You can find out the new value using Slider::getValue().
  34411. @see Slider::valueChanged
  34412. */
  34413. virtual void sliderValueChanged (Slider* slider) = 0;
  34414. /** Called when the slider is about to be dragged.
  34415. This is called when a drag begins, then it's followed by multiple calls
  34416. to sliderValueChanged(), and then sliderDragEnded() is called after the
  34417. user lets go.
  34418. @see sliderDragEnded, Slider::startedDragging
  34419. */
  34420. virtual void sliderDragStarted (Slider* slider);
  34421. /** Called after a drag operation has finished.
  34422. @see sliderDragStarted, Slider::stoppedDragging
  34423. */
  34424. virtual void sliderDragEnded (Slider* slider);
  34425. };
  34426. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  34427. /*** End of inlined file: juce_SliderListener.h ***/
  34428. /**
  34429. A slider control for changing a value.
  34430. The slider can be horizontal, vertical, or rotary, and can optionally have
  34431. a text-box inside it to show an editable display of the current value.
  34432. To use it, create a Slider object and use the setSliderStyle() method
  34433. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  34434. To define the values that it can be set to, see the setRange() and setValue() methods.
  34435. There are also lots of custom tweaks you can do by subclassing and overriding
  34436. some of the virtual methods, such as changing the scaling, changing the format of
  34437. the text display, custom ways of limiting the values, etc.
  34438. You can register SliderListeners with a slider, which will be informed when the value
  34439. changes, or a subclass can override valueChanged() to be informed synchronously.
  34440. @see SliderListener
  34441. */
  34442. class JUCE_API Slider : public Component,
  34443. public SettableTooltipClient,
  34444. private AsyncUpdater,
  34445. private ButtonListener,
  34446. private LabelListener,
  34447. private Value::Listener
  34448. {
  34449. public:
  34450. /** Creates a slider.
  34451. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  34452. setRange(), etc.
  34453. */
  34454. explicit Slider (const String& componentName = String::empty);
  34455. /** Destructor. */
  34456. ~Slider();
  34457. /** The types of slider available.
  34458. @see setSliderStyle, setRotaryParameters
  34459. */
  34460. enum SliderStyle
  34461. {
  34462. LinearHorizontal, /**< A traditional horizontal slider. */
  34463. LinearVertical, /**< A traditional vertical slider. */
  34464. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  34465. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  34466. @see setRotaryParameters */
  34467. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  34468. @see setRotaryParameters */
  34469. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  34470. @see setRotaryParameters */
  34471. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  34472. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34473. @see setMinValue, setMaxValue */
  34474. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34475. @see setMinValue, setMaxValue */
  34476. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  34477. value, with the current value being somewhere between them.
  34478. @see setMinValue, setMaxValue */
  34479. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  34480. value, with the current value being somewhere between them.
  34481. @see setMinValue, setMaxValue */
  34482. };
  34483. /** Changes the type of slider interface being used.
  34484. @param newStyle the type of interface
  34485. @see setRotaryParameters, setVelocityBasedMode,
  34486. */
  34487. void setSliderStyle (SliderStyle newStyle);
  34488. /** Returns the slider's current style.
  34489. @see setSliderStyle
  34490. */
  34491. SliderStyle getSliderStyle() const { return style; }
  34492. /** Changes the properties of a rotary slider.
  34493. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  34494. the slider's minimum value is represented
  34495. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  34496. the slider's maximum value is represented. This must be
  34497. greater than startAngleRadians
  34498. @param stopAtEnd if true, then when the slider is dragged around past the
  34499. minimum or maximum, it'll stop there; if false, it'll wrap
  34500. back to the opposite value
  34501. */
  34502. void setRotaryParameters (float startAngleRadians,
  34503. float endAngleRadians,
  34504. bool stopAtEnd);
  34505. /** Sets the distance the mouse has to move to drag the slider across
  34506. the full extent of its range.
  34507. This only applies when in modes like RotaryHorizontalDrag, where it's using
  34508. relative mouse movements to adjust the slider.
  34509. */
  34510. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  34511. /** Changes the way the the mouse is used when dragging the slider.
  34512. If true, this will turn on velocity-sensitive dragging, so that
  34513. the faster the mouse moves, the bigger the movement to the slider. This
  34514. helps when making accurate adjustments if the slider's range is quite large.
  34515. If false, the slider will just try to snap to wherever the mouse is.
  34516. */
  34517. void setVelocityBasedMode (bool isVelocityBased);
  34518. /** Returns true if velocity-based mode is active.
  34519. @see setVelocityBasedMode
  34520. */
  34521. bool getVelocityBasedMode() const { return isVelocityBased; }
  34522. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  34523. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  34524. or if you're holding down ctrl.
  34525. @param sensitivity higher values than 1.0 increase the range of acceleration used
  34526. @param threshold the minimum number of pixels that the mouse needs to move for it
  34527. to be treated as a movement
  34528. @param offset values greater than 0.0 increase the minimum speed that will be used when
  34529. the threshold is reached
  34530. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  34531. key to toggle velocity-sensitive mode
  34532. */
  34533. void setVelocityModeParameters (double sensitivity = 1.0,
  34534. int threshold = 1,
  34535. double offset = 0.0,
  34536. bool userCanPressKeyToSwapMode = true);
  34537. /** Returns the velocity sensitivity setting.
  34538. @see setVelocityModeParameters
  34539. */
  34540. double getVelocitySensitivity() const { return velocityModeSensitivity; }
  34541. /** Returns the velocity threshold setting.
  34542. @see setVelocityModeParameters
  34543. */
  34544. int getVelocityThreshold() const { return velocityModeThreshold; }
  34545. /** Returns the velocity offset setting.
  34546. @see setVelocityModeParameters
  34547. */
  34548. double getVelocityOffset() const { return velocityModeOffset; }
  34549. /** Returns the velocity user key setting.
  34550. @see setVelocityModeParameters
  34551. */
  34552. bool getVelocityModeIsSwappable() const { return userKeyOverridesVelocity; }
  34553. /** Sets up a skew factor to alter the way values are distributed.
  34554. You may want to use a range of values on the slider where more accuracy
  34555. is required towards one end of the range, so this will logarithmically
  34556. spread the values across the length of the slider.
  34557. If the factor is < 1.0, the lower end of the range will fill more of the
  34558. slider's length; if the factor is > 1.0, the upper end of the range
  34559. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  34560. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  34561. method instead.
  34562. @see getSkewFactor, setSkewFactorFromMidPoint
  34563. */
  34564. void setSkewFactor (double factor);
  34565. /** Sets up a skew factor to alter the way values are distributed.
  34566. This allows you to specify the slider value that should appear in the
  34567. centre of the slider's visible range.
  34568. @see setSkewFactor, getSkewFactor
  34569. */
  34570. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  34571. /** Returns the current skew factor.
  34572. See setSkewFactor for more info.
  34573. @see setSkewFactor, setSkewFactorFromMidPoint
  34574. */
  34575. double getSkewFactor() const { return skewFactor; }
  34576. /** Used by setIncDecButtonsMode().
  34577. */
  34578. enum IncDecButtonMode
  34579. {
  34580. incDecButtonsNotDraggable,
  34581. incDecButtonsDraggable_AutoDirection,
  34582. incDecButtonsDraggable_Horizontal,
  34583. incDecButtonsDraggable_Vertical
  34584. };
  34585. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  34586. can be dragged on the buttons to drag the values.
  34587. By default this is turned off. When enabled, clicking on the buttons still works
  34588. them as normal, but by holding down the mouse on a button and dragging it a little
  34589. distance, it flips into a mode where the value can be dragged. The drag direction can
  34590. either be set explicitly to be vertical or horizontal, or can be set to
  34591. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  34592. are side-by-side or above each other.
  34593. */
  34594. void setIncDecButtonsMode (IncDecButtonMode mode);
  34595. /** The position of the slider's text-entry box.
  34596. @see setTextBoxStyle
  34597. */
  34598. enum TextEntryBoxPosition
  34599. {
  34600. NoTextBox, /**< Doesn't display a text box. */
  34601. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  34602. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  34603. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  34604. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  34605. };
  34606. /** Changes the location and properties of the text-entry box.
  34607. @param newPosition where it should go (or NoTextBox to not have one at all)
  34608. @param isReadOnly if true, it's a read-only display
  34609. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  34610. room for the slider as well!
  34611. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  34612. room for the slider as well!
  34613. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  34614. */
  34615. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  34616. bool isReadOnly,
  34617. int textEntryBoxWidth,
  34618. int textEntryBoxHeight);
  34619. /** Returns the status of the text-box.
  34620. @see setTextBoxStyle
  34621. */
  34622. const TextEntryBoxPosition getTextBoxPosition() const { return textBoxPos; }
  34623. /** Returns the width used for the text-box.
  34624. @see setTextBoxStyle
  34625. */
  34626. int getTextBoxWidth() const { return textBoxWidth; }
  34627. /** Returns the height used for the text-box.
  34628. @see setTextBoxStyle
  34629. */
  34630. int getTextBoxHeight() const { return textBoxHeight; }
  34631. /** Makes the text-box editable.
  34632. By default this is true, and the user can enter values into the textbox,
  34633. but it can be turned off if that's not suitable.
  34634. @see setTextBoxStyle, getValueFromText, getTextFromValue
  34635. */
  34636. void setTextBoxIsEditable (bool shouldBeEditable);
  34637. /** Returns true if the text-box is read-only.
  34638. @see setTextBoxStyle
  34639. */
  34640. bool isTextBoxEditable() const { return editableText; }
  34641. /** If the text-box is editable, this will give it the focus so that the user can
  34642. type directly into it.
  34643. This is basically the effect as the user clicking on it.
  34644. */
  34645. void showTextBox();
  34646. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  34647. focus away from it.
  34648. @param discardCurrentEditorContents if true, the slider's value will be left
  34649. unchanged; if false, the current contents of the
  34650. text editor will be used to set the slider position
  34651. before it is hidden.
  34652. */
  34653. void hideTextBox (bool discardCurrentEditorContents);
  34654. /** Changes the slider's current value.
  34655. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34656. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34657. want to handle it.
  34658. @param newValue the new value to set - this will be restricted by the
  34659. minimum and maximum range, and will be snapped to the
  34660. nearest interval if one has been set
  34661. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34662. any SliderListeners or the valueChanged() method
  34663. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34664. synchronously; if false, it will be asynchronous
  34665. */
  34666. void setValue (double newValue,
  34667. bool sendUpdateMessage = true,
  34668. bool sendMessageSynchronously = false);
  34669. /** Returns the slider's current value. */
  34670. double getValue() const;
  34671. /** Returns the Value object that represents the slider's current position.
  34672. You can use this Value object to connect the slider's position to external values or setters,
  34673. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34674. your own Value object.
  34675. @see Value, getMaxValue, getMinValueObject
  34676. */
  34677. Value& getValueObject() { return currentValue; }
  34678. /** Sets the limits that the slider's value can take.
  34679. @param newMinimum the lowest value allowed
  34680. @param newMaximum the highest value allowed
  34681. @param newInterval the steps in which the value is allowed to increase - if this
  34682. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  34683. */
  34684. void setRange (double newMinimum,
  34685. double newMaximum,
  34686. double newInterval = 0);
  34687. /** Returns the current maximum value.
  34688. @see setRange
  34689. */
  34690. double getMaximum() const { return maximum; }
  34691. /** Returns the current minimum value.
  34692. @see setRange
  34693. */
  34694. double getMinimum() const { return minimum; }
  34695. /** Returns the current step-size for values.
  34696. @see setRange
  34697. */
  34698. double getInterval() const { return interval; }
  34699. /** For a slider with two or three thumbs, this returns the lower of its values.
  34700. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34701. A slider with three values also uses the normal getValue() and setValue() methods to
  34702. control the middle value.
  34703. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34704. */
  34705. double getMinValue() const;
  34706. /** For a slider with two or three thumbs, this returns the lower of its values.
  34707. You can use this Value object to connect the slider's position to external values or setters,
  34708. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34709. your own Value object.
  34710. @see Value, getMinValue, getMaxValueObject
  34711. */
  34712. Value& getMinValueObject() { return valueMin; }
  34713. /** For a slider with two or three thumbs, this sets the lower of its values.
  34714. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34715. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34716. want to handle it.
  34717. @param newValue the new value to set - this will be restricted by the
  34718. minimum and maximum range, and will be snapped to the nearest
  34719. interval if one has been set.
  34720. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34721. any SliderListeners or the valueChanged() method
  34722. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34723. synchronously; if false, it will be asynchronous
  34724. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34725. max value (in a two-value slider) or the mid value (in a three-value
  34726. slider). If false, then if this value goes beyond those values,
  34727. it will push them along with it.
  34728. @see getMinValue, setMaxValue, setValue
  34729. */
  34730. void setMinValue (double newValue,
  34731. bool sendUpdateMessage = true,
  34732. bool sendMessageSynchronously = false,
  34733. bool allowNudgingOfOtherValues = false);
  34734. /** For a slider with two or three thumbs, this returns the higher of its values.
  34735. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34736. A slider with three values also uses the normal getValue() and setValue() methods to
  34737. control the middle value.
  34738. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34739. */
  34740. double getMaxValue() const;
  34741. /** For a slider with two or three thumbs, this returns the higher of its values.
  34742. You can use this Value object to connect the slider's position to external values or setters,
  34743. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34744. your own Value object.
  34745. @see Value, getMaxValue, getMinValueObject
  34746. */
  34747. Value& getMaxValueObject() { return valueMax; }
  34748. /** For a slider with two or three thumbs, this sets the lower of its values.
  34749. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34750. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34751. want to handle it.
  34752. @param newValue the new value to set - this will be restricted by the
  34753. minimum and maximum range, and will be snapped to the nearest
  34754. interval if one has been set.
  34755. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34756. any SliderListeners or the valueChanged() method
  34757. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34758. synchronously; if false, it will be asynchronous
  34759. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34760. min value (in a two-value slider) or the mid value (in a three-value
  34761. slider). If false, then if this value goes beyond those values,
  34762. it will push them along with it.
  34763. @see getMaxValue, setMinValue, setValue
  34764. */
  34765. void setMaxValue (double newValue,
  34766. bool sendUpdateMessage = true,
  34767. bool sendMessageSynchronously = false,
  34768. bool allowNudgingOfOtherValues = false);
  34769. /** Adds a listener to be called when this slider's value changes. */
  34770. void addListener (SliderListener* listener);
  34771. /** Removes a previously-registered listener. */
  34772. void removeListener (SliderListener* listener);
  34773. /** This lets you choose whether double-clicking moves the slider to a given position.
  34774. By default this is turned off, but it's handy if you want a double-click to act
  34775. as a quick way of resetting a slider. Just pass in the value you want it to
  34776. go to when double-clicked.
  34777. @see getDoubleClickReturnValue
  34778. */
  34779. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  34780. double valueToSetOnDoubleClick);
  34781. /** Returns the values last set by setDoubleClickReturnValue() method.
  34782. Sets isEnabled to true if double-click is enabled, and returns the value
  34783. that was set.
  34784. @see setDoubleClickReturnValue
  34785. */
  34786. double getDoubleClickReturnValue (bool& isEnabled) const;
  34787. /** Tells the slider whether to keep sending change messages while the user
  34788. is dragging the slider.
  34789. If set to true, a change message will only be sent when the user has
  34790. dragged the slider and let go. If set to false (the default), then messages
  34791. will be continuously sent as they drag it while the mouse button is still
  34792. held down.
  34793. */
  34794. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  34795. /** This lets you change whether the slider thumb jumps to the mouse position
  34796. when you click.
  34797. By default, this is true. If it's false, then the slider moves with relative
  34798. motion when you drag it.
  34799. This only applies to linear bars, and won't affect two- or three- value
  34800. sliders.
  34801. */
  34802. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  34803. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34804. slider is being dragged.
  34805. This can be handy if your slider doesn't have a text-box, so that users can
  34806. see the value just when they're changing it.
  34807. If you pass a component as the parentComponentToUse parameter, the pop-up
  34808. bubble will be added as a child of that component when it's needed. If you
  34809. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34810. transparent window, so if you're using an OS that can't do transparent windows
  34811. you'll have to add it to a parent component instead).
  34812. */
  34813. void setPopupDisplayEnabled (bool isEnabled,
  34814. Component* parentComponentToUse);
  34815. /** If this is set to true, then right-clicking on the slider will pop-up
  34816. a menu to let the user change the way it works.
  34817. By default this is turned off, but when turned on, the menu will include
  34818. things like velocity sensitivity, and for rotary sliders, whether they
  34819. use a linear or rotary mouse-drag to move them.
  34820. */
  34821. void setPopupMenuEnabled (bool menuEnabled);
  34822. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34823. By default it's enabled.
  34824. */
  34825. void setScrollWheelEnabled (bool enabled);
  34826. /** Returns a number to indicate which thumb is currently being dragged by the
  34827. mouse.
  34828. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34829. the maximum-value thumb, or -1 if none is currently down.
  34830. */
  34831. int getThumbBeingDragged() const { return sliderBeingDragged; }
  34832. /** Callback to indicate that the user is about to start dragging the slider.
  34833. @see SliderListener::sliderDragStarted
  34834. */
  34835. virtual void startedDragging();
  34836. /** Callback to indicate that the user has just stopped dragging the slider.
  34837. @see SliderListener::sliderDragEnded
  34838. */
  34839. virtual void stoppedDragging();
  34840. /** Callback to indicate that the user has just moved the slider.
  34841. @see SliderListener::sliderValueChanged
  34842. */
  34843. virtual void valueChanged();
  34844. /** Subclasses can override this to convert a text string to a value.
  34845. When the user enters something into the text-entry box, this method is
  34846. called to convert it to a value.
  34847. The default routine just tries to convert it to a double.
  34848. @see getTextFromValue
  34849. */
  34850. virtual double getValueFromText (const String& text);
  34851. /** Turns the slider's current value into a text string.
  34852. Subclasses can override this to customise the formatting of the text-entry box.
  34853. The default implementation just turns the value into a string, using
  34854. a number of decimal places based on the range interval. If a suffix string
  34855. has been set using setTextValueSuffix(), this will be appended to the text.
  34856. @see getValueFromText
  34857. */
  34858. virtual const String getTextFromValue (double value);
  34859. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34860. a string.
  34861. This is used by the default implementation of getTextFromValue(), and is just
  34862. appended to the numeric value. For more advanced formatting, you can override
  34863. getTextFromValue() and do something else.
  34864. */
  34865. void setTextValueSuffix (const String& suffix);
  34866. /** Returns the suffix that was set by setTextValueSuffix(). */
  34867. const String getTextValueSuffix() const;
  34868. /** Allows a user-defined mapping of distance along the slider to its value.
  34869. The default implementation for this performs the skewing operation that
  34870. can be set up in the setSkewFactor() method. Override it if you need
  34871. some kind of custom mapping instead, but make sure you also implement the
  34872. inverse function in valueToProportionOfLength().
  34873. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34874. @returns the slider value that is represented by this position
  34875. @see valueToProportionOfLength
  34876. */
  34877. virtual double proportionOfLengthToValue (double proportion);
  34878. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34879. The default implementation for this performs the skewing operation that
  34880. can be set up in the setSkewFactor() method. Override it if you need
  34881. some kind of custom mapping instead, but make sure you also implement the
  34882. inverse function in proportionOfLengthToValue().
  34883. @param value a valid slider value, between the range of values specified in
  34884. setRange()
  34885. @returns a value 0 to 1.0 indicating the distance along the slider that
  34886. represents this value
  34887. @see proportionOfLengthToValue
  34888. */
  34889. virtual double valueToProportionOfLength (double value);
  34890. /** Returns the X or Y coordinate of a value along the slider's length.
  34891. If the slider is horizontal, this will be the X coordinate of the given
  34892. value, relative to the left of the slider. If it's vertical, then this will
  34893. be the Y coordinate, relative to the top of the slider.
  34894. If the slider is rotary, this will throw an assertion and return 0. If the
  34895. value is out-of-range, it will be constrained to the length of the slider.
  34896. */
  34897. float getPositionOfValue (double value);
  34898. /** This can be overridden to allow the slider to snap to user-definable values.
  34899. If overridden, it will be called when the user tries to move the slider to
  34900. a given position, and allows a subclass to sanity-check this value, possibly
  34901. returning a different value to use instead.
  34902. @param attemptedValue the value the user is trying to enter
  34903. @param userIsDragging true if the user is dragging with the mouse; false if
  34904. they are entering the value using the text box
  34905. @returns the value to use instead
  34906. */
  34907. virtual double snapValue (double attemptedValue, bool userIsDragging);
  34908. /** This can be called to force the text box to update its contents.
  34909. (Not normally needed, as this is done automatically).
  34910. */
  34911. void updateText();
  34912. /** True if the slider moves horizontally. */
  34913. bool isHorizontal() const;
  34914. /** True if the slider moves vertically. */
  34915. bool isVertical() const;
  34916. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34917. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34918. methods.
  34919. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34920. */
  34921. enum ColourIds
  34922. {
  34923. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34924. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34925. and feel class how this is used. */
  34926. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34927. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34928. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34929. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34930. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34931. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34932. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34933. };
  34934. juce_UseDebuggingNewOperator
  34935. protected:
  34936. /** @internal */
  34937. void labelTextChanged (Label*);
  34938. /** @internal */
  34939. void paint (Graphics& g);
  34940. /** @internal */
  34941. void resized();
  34942. /** @internal */
  34943. void mouseDown (const MouseEvent& e);
  34944. /** @internal */
  34945. void mouseUp (const MouseEvent& e);
  34946. /** @internal */
  34947. void mouseDrag (const MouseEvent& e);
  34948. /** @internal */
  34949. void mouseDoubleClick (const MouseEvent& e);
  34950. /** @internal */
  34951. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34952. /** @internal */
  34953. void modifierKeysChanged (const ModifierKeys& modifiers);
  34954. /** @internal */
  34955. void buttonClicked (Button* button);
  34956. /** @internal */
  34957. void lookAndFeelChanged();
  34958. /** @internal */
  34959. void enablementChanged();
  34960. /** @internal */
  34961. void focusOfChildComponentChanged (FocusChangeType cause);
  34962. /** @internal */
  34963. void handleAsyncUpdate();
  34964. /** @internal */
  34965. void colourChanged();
  34966. /** @internal */
  34967. void valueChanged (Value& value);
  34968. /** Returns the best number of decimal places to use when displaying numbers.
  34969. This is calculated from the slider's interval setting.
  34970. */
  34971. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  34972. private:
  34973. ListenerList <SliderListener> listeners;
  34974. Value currentValue, valueMin, valueMax;
  34975. double lastCurrentValue, lastValueMin, lastValueMax;
  34976. double minimum, maximum, interval, doubleClickReturnValue;
  34977. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34978. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34979. int velocityModeThreshold;
  34980. float rotaryStart, rotaryEnd;
  34981. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34982. int mouseDragStartX, mouseDragStartY;
  34983. int sliderRegionStart, sliderRegionSize;
  34984. int sliderBeingDragged;
  34985. int pixelsForFullDragExtent;
  34986. Rectangle<int> sliderRect;
  34987. String textSuffix;
  34988. SliderStyle style;
  34989. TextEntryBoxPosition textBoxPos;
  34990. int textBoxWidth, textBoxHeight;
  34991. IncDecButtonMode incDecButtonMode;
  34992. bool editableText : 1, doubleClickToValue : 1;
  34993. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34994. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34995. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34996. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34997. Label* valueBox;
  34998. Button* incButton;
  34999. Button* decButton;
  35000. ScopedPointer <Component> popupDisplay;
  35001. Component* parentForPopupDisplay;
  35002. float getLinearSliderPos (double value);
  35003. void restoreMouseIfHidden();
  35004. void sendDragStart();
  35005. void sendDragEnd();
  35006. double constrainedValue (double value) const;
  35007. void triggerChangeMessage (bool synchronous);
  35008. bool incDecDragDirectionIsHorizontal() const;
  35009. Slider (const Slider&);
  35010. Slider& operator= (const Slider&);
  35011. };
  35012. #endif // __JUCE_SLIDER_JUCEHEADER__
  35013. /*** End of inlined file: juce_Slider.h ***/
  35014. #endif
  35015. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  35016. #endif
  35017. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35018. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  35019. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35020. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35021. class TableHeaderComponent;
  35022. /**
  35023. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  35024. You can register one of these objects for table events using TableHeaderComponent::addListener()
  35025. and TableHeaderComponent::removeListener().
  35026. @see TableHeaderComponent
  35027. */
  35028. class JUCE_API TableHeaderListener
  35029. {
  35030. public:
  35031. TableHeaderListener() {}
  35032. /** Destructor. */
  35033. virtual ~TableHeaderListener() {}
  35034. /** This is called when some of the table's columns are added, removed, hidden,
  35035. or rearranged.
  35036. */
  35037. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  35038. /** This is called when one or more of the table's columns are resized.
  35039. */
  35040. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  35041. /** This is called when the column by which the table should be sorted is changed.
  35042. */
  35043. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  35044. /** This is called when the user begins or ends dragging one of the columns around.
  35045. When the user starts dragging a column, this is called with the ID of that
  35046. column. When they finish dragging, it is called again with 0 as the ID.
  35047. */
  35048. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  35049. int columnIdNowBeingDragged);
  35050. };
  35051. /**
  35052. A component that displays a strip of column headings for a table, and allows these
  35053. to be resized, dragged around, etc.
  35054. This is just the component that goes at the top of a table. You can use it
  35055. directly for custom components, or to create a simple table, use the
  35056. TableListBox class.
  35057. To use one of these, create it and use addColumn() to add all the columns that you need.
  35058. Each column must be given a unique ID number that's used to refer to it.
  35059. @see TableListBox, TableHeaderListener
  35060. */
  35061. class JUCE_API TableHeaderComponent : public Component,
  35062. private AsyncUpdater
  35063. {
  35064. public:
  35065. /** Creates an empty table header.
  35066. */
  35067. TableHeaderComponent();
  35068. /** Destructor. */
  35069. ~TableHeaderComponent();
  35070. /** A combination of these flags are passed into the addColumn() method to specify
  35071. the properties of a column.
  35072. */
  35073. enum ColumnPropertyFlags
  35074. {
  35075. 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. */
  35076. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  35077. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  35078. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  35079. 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. */
  35080. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  35081. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  35082. /** This set of default flags is used as the default parameter value in addColumn(). */
  35083. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  35084. /** A quick way of combining flags for a column that's not resizable. */
  35085. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  35086. /** A quick way of combining flags for a column that's not resizable or sortable. */
  35087. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  35088. /** A quick way of combining flags for a column that's not sortable. */
  35089. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  35090. };
  35091. /** Adds a column to the table.
  35092. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  35093. registered listeners.
  35094. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  35095. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  35096. a unique ID. This is used to identify the column later on, after the user may have
  35097. changed the order that they appear in
  35098. @param width the initial width of the column, in pixels
  35099. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  35100. if the 'resizable' flag is specified for this column
  35101. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  35102. if the 'resizable' flag is specified for this column
  35103. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  35104. properties of this column
  35105. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  35106. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  35107. all columns, not just the index amongst those that are currently visible
  35108. */
  35109. void addColumn (const String& columnName,
  35110. int columnId,
  35111. int width,
  35112. int minimumWidth = 30,
  35113. int maximumWidth = -1,
  35114. int propertyFlags = defaultFlags,
  35115. int insertIndex = -1);
  35116. /** Removes a column with the given ID.
  35117. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  35118. registered listeners.
  35119. */
  35120. void removeColumn (int columnIdToRemove);
  35121. /** Deletes all columns from the table.
  35122. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  35123. registered listeners.
  35124. */
  35125. void removeAllColumns();
  35126. /** Returns the number of columns in the table.
  35127. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  35128. return the total number of columns, including hidden ones.
  35129. @see isColumnVisible
  35130. */
  35131. int getNumColumns (bool onlyCountVisibleColumns) const;
  35132. /** Returns the name for a column.
  35133. @see setColumnName
  35134. */
  35135. const String getColumnName (int columnId) const;
  35136. /** Changes the name of a column. */
  35137. void setColumnName (int columnId, const String& newName);
  35138. /** Moves a column to a different index in the table.
  35139. @param columnId the column to move
  35140. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  35141. */
  35142. void moveColumn (int columnId, int newVisibleIndex);
  35143. /** Returns the width of one of the columns.
  35144. */
  35145. int getColumnWidth (int columnId) const;
  35146. /** Changes the width of a column.
  35147. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  35148. */
  35149. void setColumnWidth (int columnId, int newWidth);
  35150. /** Shows or hides a column.
  35151. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  35152. @see isColumnVisible
  35153. */
  35154. void setColumnVisible (int columnId, bool shouldBeVisible);
  35155. /** Returns true if this column is currently visible.
  35156. @see setColumnVisible
  35157. */
  35158. bool isColumnVisible (int columnId) const;
  35159. /** Changes the column which is the sort column.
  35160. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  35161. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  35162. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  35163. @see getSortColumnId, isSortedForwards, reSortTable
  35164. */
  35165. void setSortColumnId (int columnId, bool sortForwards);
  35166. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  35167. @see setSortColumnId, isSortedForwards
  35168. */
  35169. int getSortColumnId() const;
  35170. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  35171. @see setSortColumnId
  35172. */
  35173. bool isSortedForwards() const;
  35174. /** Triggers a re-sort of the table according to the current sort-column.
  35175. If you modifiy the table's contents, you can call this to signal that the table needs
  35176. to be re-sorted.
  35177. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  35178. tableSortOrderChanged() method of any listeners).
  35179. */
  35180. void reSortTable();
  35181. /** Returns the total width of all the visible columns in the table.
  35182. */
  35183. int getTotalWidth() const;
  35184. /** Returns the index of a given column.
  35185. If there's no such column ID, this will return -1.
  35186. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  35187. otherwise it'll return the index amongst all the columns, including any hidden ones.
  35188. */
  35189. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  35190. /** Returns the ID of the column at a given index.
  35191. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  35192. otherwise it'll count it amongst all the columns, including any hidden ones.
  35193. If the index is out-of-range, it'll return 0.
  35194. */
  35195. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  35196. /** Returns the rectangle containing of one of the columns.
  35197. The index is an index from 0 to the number of columns that are currently visible (hidden
  35198. ones are not counted). It returns a rectangle showing the position of the column relative
  35199. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  35200. */
  35201. const Rectangle<int> getColumnPosition (int index) const;
  35202. /** Finds the column ID at a given x-position in the component.
  35203. If there is a column at this point this returns its ID, or if not, it will return 0.
  35204. */
  35205. int getColumnIdAtX (int xToFind) const;
  35206. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  35207. entire width of the component.
  35208. By default this is disabled. Turning it on also means that when resizing a column, those
  35209. on the right will be squashed to fit.
  35210. */
  35211. void setStretchToFitActive (bool shouldStretchToFit);
  35212. /** Returns true if stretch-to-fit has been enabled.
  35213. @see setStretchToFitActive
  35214. */
  35215. bool isStretchToFitActive() const;
  35216. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  35217. specified width, keeping their relative proportions the same.
  35218. If the minimum widths of the columns are too wide to fit into this space, it may
  35219. actually end up wider.
  35220. */
  35221. void resizeAllColumnsToFit (int targetTotalWidth);
  35222. /** Enables or disables the pop-up menu.
  35223. The default menu allows the user to show or hide columns. You can add custom
  35224. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  35225. By default the menu is enabled.
  35226. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  35227. */
  35228. void setPopupMenuActive (bool hasMenu);
  35229. /** Returns true if the pop-up menu is enabled.
  35230. @see setPopupMenuActive
  35231. */
  35232. bool isPopupMenuActive() const;
  35233. /** Returns a string that encapsulates the table's current layout.
  35234. This can be restored later using restoreFromString(). It saves the order of
  35235. the columns, the currently-sorted column, and the widths.
  35236. @see restoreFromString
  35237. */
  35238. const String toString() const;
  35239. /** Restores the state of the table, based on a string previously created with
  35240. toString().
  35241. @see toString
  35242. */
  35243. void restoreFromString (const String& storedVersion);
  35244. /** Adds a listener to be informed about things that happen to the header. */
  35245. void addListener (TableHeaderListener* newListener);
  35246. /** Removes a previously-registered listener. */
  35247. void removeListener (TableHeaderListener* listenerToRemove);
  35248. /** This can be overridden to handle a mouse-click on one of the column headers.
  35249. The default implementation will use this click to call getSortColumnId() and
  35250. change the sort order.
  35251. */
  35252. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  35253. /** This can be overridden to add custom items to the pop-up menu.
  35254. If you override this, you should call the superclass's method to add its
  35255. column show/hide items, if you want them on the menu as well.
  35256. Then to handle the result, override reactToMenuItem().
  35257. @see reactToMenuItem
  35258. */
  35259. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  35260. /** Override this to handle any custom items that you have added to the
  35261. pop-up menu with an addMenuItems() override.
  35262. If the menuReturnId isn't one of your own custom menu items, you'll need to
  35263. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  35264. handle the items that it had added.
  35265. @see addMenuItems
  35266. */
  35267. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  35268. /** @internal */
  35269. void paint (Graphics& g);
  35270. /** @internal */
  35271. void resized();
  35272. /** @internal */
  35273. void mouseMove (const MouseEvent&);
  35274. /** @internal */
  35275. void mouseEnter (const MouseEvent&);
  35276. /** @internal */
  35277. void mouseExit (const MouseEvent&);
  35278. /** @internal */
  35279. void mouseDown (const MouseEvent&);
  35280. /** @internal */
  35281. void mouseDrag (const MouseEvent&);
  35282. /** @internal */
  35283. void mouseUp (const MouseEvent&);
  35284. /** @internal */
  35285. const MouseCursor getMouseCursor();
  35286. /** Can be overridden for more control over the pop-up menu behaviour. */
  35287. virtual void showColumnChooserMenu (int columnIdClicked);
  35288. juce_UseDebuggingNewOperator
  35289. private:
  35290. struct ColumnInfo
  35291. {
  35292. String name;
  35293. int id, propertyFlags, width, minimumWidth, maximumWidth;
  35294. double lastDeliberateWidth;
  35295. bool isVisible() const;
  35296. };
  35297. OwnedArray <ColumnInfo> columns;
  35298. Array <TableHeaderListener*> listeners;
  35299. ScopedPointer <Component> dragOverlayComp;
  35300. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  35301. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  35302. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  35303. ColumnInfo* getInfoForId (int columnId) const;
  35304. int visibleIndexToTotalIndex (int visibleIndex) const;
  35305. void sendColumnsChanged();
  35306. void handleAsyncUpdate();
  35307. void beginDrag (const MouseEvent&);
  35308. void endDrag (int finalIndex);
  35309. int getResizeDraggerAt (int mouseX) const;
  35310. void updateColumnUnderMouse (int x, int y);
  35311. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  35312. TableHeaderComponent (const TableHeaderComponent&);
  35313. TableHeaderComponent operator= (const TableHeaderComponent&);
  35314. };
  35315. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35316. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  35317. #endif
  35318. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35319. /*** Start of inlined file: juce_TableListBox.h ***/
  35320. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35321. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  35322. /**
  35323. One of these is used by a TableListBox as the data model for the table's contents.
  35324. The virtual methods that you override in this class take care of drawing the
  35325. table cells, and reacting to events.
  35326. @see TableListBox
  35327. */
  35328. class JUCE_API TableListBoxModel
  35329. {
  35330. public:
  35331. TableListBoxModel() {}
  35332. /** Destructor. */
  35333. virtual ~TableListBoxModel() {}
  35334. /** This must return the number of rows currently in the table.
  35335. If the number of rows changes, you must call TableListBox::updateContent() to
  35336. cause it to refresh the list.
  35337. */
  35338. virtual int getNumRows() = 0;
  35339. /** This must draw the background behind one of the rows in the table.
  35340. The graphics context has its origin at the row's top-left, and your method
  35341. should fill the area specified by the width and height parameters.
  35342. */
  35343. virtual void paintRowBackground (Graphics& g,
  35344. int rowNumber,
  35345. int width, int height,
  35346. bool rowIsSelected) = 0;
  35347. /** This must draw one of the cells.
  35348. The graphics context's origin will already be set to the top-left of the cell,
  35349. whose size is specified by (width, height).
  35350. */
  35351. virtual void paintCell (Graphics& g,
  35352. int rowNumber,
  35353. int columnId,
  35354. int width, int height,
  35355. bool rowIsSelected) = 0;
  35356. /** This is used to create or update a custom component to go in a cell.
  35357. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  35358. and handle mouse clicks with cellClicked().
  35359. This method will be called whenever a custom component might need to be updated - e.g.
  35360. when the table is changed, or TableListBox::updateContent() is called.
  35361. If you don't need a custom component for the specified cell, then return 0.
  35362. If you do want a custom component, and the existingComponentToUpdate is null, then
  35363. this method must create a new component suitable for the cell, and return it.
  35364. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35365. by this method. In this case, the method must either update it to make sure it's correctly representing
  35366. the given cell (which may be different from the one that the component was created for), or it can
  35367. delete this component and return a new one.
  35368. */
  35369. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  35370. Component* existingComponentToUpdate);
  35371. /** This callback is made when the user clicks on one of the cells in the table.
  35372. The mouse event's coordinates will be relative to the entire table row.
  35373. @see cellDoubleClicked, backgroundClicked
  35374. */
  35375. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  35376. /** This callback is made when the user clicks on one of the cells in the table.
  35377. The mouse event's coordinates will be relative to the entire table row.
  35378. @see cellClicked, backgroundClicked
  35379. */
  35380. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  35381. /** This can be overridden to react to the user double-clicking on a part of the list where
  35382. there are no rows.
  35383. @see cellClicked
  35384. */
  35385. virtual void backgroundClicked();
  35386. /** This callback is made when the table's sort order is changed.
  35387. This could be because the user has clicked a column header, or because the
  35388. TableHeaderComponent::setSortColumnId() method was called.
  35389. If you implement this, your method should re-sort the table using the given
  35390. column as the key.
  35391. */
  35392. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  35393. /** Returns the best width for one of the columns.
  35394. If you implement this method, you should measure the width of all the items
  35395. in this column, and return the best size.
  35396. Returning 0 means that the column shouldn't be changed.
  35397. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  35398. */
  35399. virtual int getColumnAutoSizeWidth (int columnId);
  35400. /** Returns a tooltip for a particular cell in the table.
  35401. */
  35402. virtual const String getCellTooltip (int rowNumber, int columnId);
  35403. /** Override this to be informed when rows are selected or deselected.
  35404. @see ListBox::selectedRowsChanged()
  35405. */
  35406. virtual void selectedRowsChanged (int lastRowSelected);
  35407. /** Override this to be informed when the delete key is pressed.
  35408. @see ListBox::deleteKeyPressed()
  35409. */
  35410. virtual void deleteKeyPressed (int lastRowSelected);
  35411. /** Override this to be informed when the return key is pressed.
  35412. @see ListBox::returnKeyPressed()
  35413. */
  35414. virtual void returnKeyPressed (int lastRowSelected);
  35415. /** Override this to be informed when the list is scrolled.
  35416. This might be caused by the user moving the scrollbar, or by programmatic changes
  35417. to the list position.
  35418. */
  35419. virtual void listWasScrolled();
  35420. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  35421. If this returns a non-empty name then when the user drags a row, the table will try to
  35422. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  35423. drag-and-drop operation, using this string as the source description, and the listbox
  35424. itself as the source component.
  35425. @see DragAndDropContainer::startDragging
  35426. */
  35427. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35428. };
  35429. /**
  35430. A table of cells, using a TableHeaderComponent as its header.
  35431. This component makes it easy to create a table by providing a TableListBoxModel as
  35432. the data source.
  35433. @see TableListBoxModel, TableHeaderComponent
  35434. */
  35435. class JUCE_API TableListBox : public ListBox,
  35436. private ListBoxModel,
  35437. private TableHeaderListener
  35438. {
  35439. public:
  35440. /** Creates a TableListBox.
  35441. The model pointer passed-in can be null, in which case you can set it later
  35442. with setModel().
  35443. */
  35444. TableListBox (const String& componentName,
  35445. TableListBoxModel* model);
  35446. /** Destructor. */
  35447. ~TableListBox();
  35448. /** Changes the TableListBoxModel that is being used for this table.
  35449. */
  35450. void setModel (TableListBoxModel* newModel);
  35451. /** Returns the model currently in use. */
  35452. TableListBoxModel* getModel() const { return model; }
  35453. /** Returns the header component being used in this table. */
  35454. TableHeaderComponent* getHeader() const { return header; }
  35455. /** Changes the height of the table header component.
  35456. @see getHeaderHeight
  35457. */
  35458. void setHeaderHeight (int newHeight);
  35459. /** Returns the height of the table header.
  35460. @see setHeaderHeight
  35461. */
  35462. int getHeaderHeight() const;
  35463. /** Resizes a column to fit its contents.
  35464. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  35465. and applies that to the column.
  35466. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  35467. */
  35468. void autoSizeColumn (int columnId);
  35469. /** Calls autoSizeColumn() for all columns in the table. */
  35470. void autoSizeAllColumns();
  35471. /** Enables or disables the auto size options on the popup menu.
  35472. By default, these are enabled.
  35473. */
  35474. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  35475. /** True if the auto-size options should be shown on the menu.
  35476. @see setAutoSizeMenuOptionsShown
  35477. */
  35478. bool isAutoSizeMenuOptionShown() const;
  35479. /** Returns the position of one of the cells in the table.
  35480. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  35481. the table component's top-left. The row number isn't checked to see if it's
  35482. in-range, but the column ID must exist or this will return an empty rectangle.
  35483. If relativeToComponentTopLeft is false, the co-ords are relative to the
  35484. top-left of the table's top-left cell.
  35485. */
  35486. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  35487. bool relativeToComponentTopLeft) const;
  35488. /** Returns the component that currently represents a given cell.
  35489. If the component for this cell is off-screen or if the position is out-of-range,
  35490. this may return 0.
  35491. @see getCellPosition
  35492. */
  35493. Component* getCellComponent (int columnId, int rowNumber) const;
  35494. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  35495. @see ListBox::scrollToEnsureRowIsOnscreen
  35496. */
  35497. void scrollToEnsureColumnIsOnscreen (int columnId);
  35498. /** @internal */
  35499. int getNumRows();
  35500. /** @internal */
  35501. void paintListBoxItem (int, Graphics&, int, int, bool);
  35502. /** @internal */
  35503. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35504. /** @internal */
  35505. void selectedRowsChanged (int lastRowSelected);
  35506. /** @internal */
  35507. void deleteKeyPressed (int currentSelectedRow);
  35508. /** @internal */
  35509. void returnKeyPressed (int currentSelectedRow);
  35510. /** @internal */
  35511. void backgroundClicked();
  35512. /** @internal */
  35513. void listWasScrolled();
  35514. /** @internal */
  35515. void tableColumnsChanged (TableHeaderComponent*);
  35516. /** @internal */
  35517. void tableColumnsResized (TableHeaderComponent*);
  35518. /** @internal */
  35519. void tableSortOrderChanged (TableHeaderComponent*);
  35520. /** @internal */
  35521. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  35522. /** @internal */
  35523. void resized();
  35524. juce_UseDebuggingNewOperator
  35525. private:
  35526. TableHeaderComponent* header;
  35527. TableListBoxModel* model;
  35528. int columnIdNowBeingDragged;
  35529. bool autoSizeOptionsShown;
  35530. void updateColumnComponents() const;
  35531. TableListBox (const TableListBox&);
  35532. TableListBox& operator= (const TableListBox&);
  35533. };
  35534. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  35535. /*** End of inlined file: juce_TableListBox.h ***/
  35536. #endif
  35537. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  35538. #endif
  35539. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35540. #endif
  35541. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35542. #endif
  35543. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35544. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  35545. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35546. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35547. /**
  35548. A factory object which can create ToolbarItemComponent objects.
  35549. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  35550. that it can create.
  35551. Each type of item is identified by a unique ID, and multiple instances of an
  35552. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  35553. bars).
  35554. @see Toolbar, ToolbarItemComponent, ToolbarButton
  35555. */
  35556. class JUCE_API ToolbarItemFactory
  35557. {
  35558. public:
  35559. ToolbarItemFactory();
  35560. /** Destructor. */
  35561. virtual ~ToolbarItemFactory();
  35562. /** A set of reserved item ID values, used for the built-in item types.
  35563. */
  35564. enum SpecialItemIds
  35565. {
  35566. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  35567. can be placed between sets of items to break them into groups. */
  35568. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  35569. items.*/
  35570. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  35571. either side of it, filling any available space. */
  35572. };
  35573. /** Must return a list of the IDs for all the item types that this factory can create.
  35574. The ids should be added to the array that is passed-in.
  35575. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  35576. and the predefined IDs in the SpecialItemIds enum.
  35577. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  35578. to this list if you want your toolbar to be able to contain those items.
  35579. The list returned here is used by the ToolbarItemPalette class to obtain its list
  35580. of available items, and their order on the palette will reflect the order in which
  35581. they appear on this list.
  35582. @see ToolbarItemPalette
  35583. */
  35584. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  35585. /** Must return the set of items that should be added to a toolbar as its default set.
  35586. This method is used by Toolbar::addDefaultItems() to determine which items to
  35587. create.
  35588. The items that your method adds to the array that is passed-in will be added to the
  35589. toolbar in the same order. Items can appear in the list more than once.
  35590. */
  35591. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  35592. /** Must create an instance of one of the items that the factory lists in its
  35593. getAllToolbarItemIds() method.
  35594. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  35595. method, except for the built-in item types from the SpecialItemIds enum, which
  35596. are created internally by the toolbar code.
  35597. Try not to keep a pointer to the object that is returned, as it will be deleted
  35598. automatically by the toolbar, and remember that multiple instances of the same
  35599. item type are likely to exist at the same time.
  35600. */
  35601. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  35602. };
  35603. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35604. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  35605. #endif
  35606. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35607. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  35608. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35609. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35610. /**
  35611. A component containing a list of toolbar items, which the user can drag onto
  35612. a toolbar to add them.
  35613. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  35614. which automatically shows one of these in a dialog box with lots of extra controls.
  35615. @see Toolbar
  35616. */
  35617. class JUCE_API ToolbarItemPalette : public Component,
  35618. public DragAndDropContainer
  35619. {
  35620. public:
  35621. /** Creates a palette of items for a given factory, with the aim of adding them
  35622. to the specified toolbar.
  35623. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  35624. set of items that are shown in this palette.
  35625. The toolbar and factory must not be deleted while this object exists.
  35626. */
  35627. ToolbarItemPalette (ToolbarItemFactory& factory,
  35628. Toolbar* toolbar);
  35629. /** Destructor. */
  35630. ~ToolbarItemPalette();
  35631. /** @internal */
  35632. void resized();
  35633. juce_UseDebuggingNewOperator
  35634. private:
  35635. ToolbarItemFactory& factory;
  35636. Toolbar* toolbar;
  35637. Viewport* viewport;
  35638. friend class Toolbar;
  35639. void replaceComponent (ToolbarItemComponent* comp);
  35640. ToolbarItemPalette (const ToolbarItemPalette&);
  35641. ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  35642. };
  35643. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35644. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  35645. #endif
  35646. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35647. /*** Start of inlined file: juce_TreeView.h ***/
  35648. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35649. #define __JUCE_TREEVIEW_JUCEHEADER__
  35650. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  35651. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35652. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35653. /**
  35654. Components derived from this class can have files dropped onto them by an external application.
  35655. @see DragAndDropContainer
  35656. */
  35657. class JUCE_API FileDragAndDropTarget
  35658. {
  35659. public:
  35660. /** Destructor. */
  35661. virtual ~FileDragAndDropTarget() {}
  35662. /** Callback to check whether this target is interested in the set of files being offered.
  35663. Note that this will be called repeatedly when the user is dragging the mouse around over your
  35664. component, so don't do anything time-consuming in here, like opening the files to have a look
  35665. inside them!
  35666. @param files the set of (absolute) pathnames of the files that the user is dragging
  35667. @returns true if this component wants to receive the other callbacks regarging this
  35668. type of object; if it returns false, no other callbacks will be made.
  35669. */
  35670. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  35671. /** Callback to indicate that some files are being dragged over this component.
  35672. This gets called when the user moves the mouse into this component while dragging.
  35673. Use this callback as a trigger to make your component repaint itself to give the
  35674. user feedback about whether the files can be dropped here or not.
  35675. @param files the set of (absolute) pathnames of the files that the user is dragging
  35676. @param x the mouse x position, relative to this component
  35677. @param y the mouse y position, relative to this component
  35678. */
  35679. virtual void fileDragEnter (const StringArray& files, int x, int y);
  35680. /** Callback to indicate that the user is dragging some files over this component.
  35681. This gets called when the user moves the mouse over this component while dragging.
  35682. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  35683. this lets you know what happens in-between.
  35684. @param files the set of (absolute) pathnames of the files that the user is dragging
  35685. @param x the mouse x position, relative to this component
  35686. @param y the mouse y position, relative to this component
  35687. */
  35688. virtual void fileDragMove (const StringArray& files, int x, int y);
  35689. /** Callback to indicate that the mouse has moved away from this component.
  35690. This gets called when the user moves the mouse out of this component while dragging
  35691. the files.
  35692. If you've used fileDragEnter() to repaint your component and give feedback, use this
  35693. as a signal to repaint it in its normal state.
  35694. @param files the set of (absolute) pathnames of the files that the user is dragging
  35695. */
  35696. virtual void fileDragExit (const StringArray& files);
  35697. /** Callback to indicate that the user has dropped the files onto this component.
  35698. When the user drops the files, this get called, and you can use the files in whatever
  35699. way is appropriate.
  35700. Note that after this is called, the fileDragExit method may not be called, so you should
  35701. clean up in here if there's anything you need to do when the drag finishes.
  35702. @param files the set of (absolute) pathnames of the files that the user is dragging
  35703. @param x the mouse x position, relative to this component
  35704. @param y the mouse y position, relative to this component
  35705. */
  35706. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  35707. };
  35708. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35709. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  35710. class TreeView;
  35711. /**
  35712. An item in a treeview.
  35713. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  35714. own sub-items.
  35715. To implement an item that contains sub-items, override the itemOpennessChanged()
  35716. method so that when it is opened, it adds the new sub-items to itself using the
  35717. addSubItem method. Depending on the nature of the item it might choose to only
  35718. do this the first time it's opened, or it might want to refresh itself each time.
  35719. It also has the option of deleting its sub-items when it is closed, or leaving them
  35720. in place.
  35721. */
  35722. class JUCE_API TreeViewItem
  35723. {
  35724. public:
  35725. /** Constructor. */
  35726. TreeViewItem();
  35727. /** Destructor. */
  35728. virtual ~TreeViewItem();
  35729. /** Returns the number of sub-items that have been added to this item.
  35730. Note that this doesn't mean much if the node isn't open.
  35731. @see getSubItem, mightContainSubItems, addSubItem
  35732. */
  35733. int getNumSubItems() const throw();
  35734. /** Returns one of the item's sub-items.
  35735. Remember that the object returned might get deleted at any time when its parent
  35736. item is closed or refreshed, depending on the nature of the items you're using.
  35737. @see getNumSubItems
  35738. */
  35739. TreeViewItem* getSubItem (int index) const throw();
  35740. /** Removes any sub-items. */
  35741. void clearSubItems();
  35742. /** Adds a sub-item.
  35743. @param newItem the object to add to the item's sub-item list. Once added, these can be
  35744. found using getSubItem(). When the items are later removed with
  35745. removeSubItem() (or when this item is deleted), they will be deleted.
  35746. @param insertPosition the index which the new item should have when it's added. If this
  35747. value is less than 0, the item will be added to the end of the list.
  35748. */
  35749. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  35750. /** Removes one of the sub-items.
  35751. @param index the item to remove
  35752. @param deleteItem if true, the item that is removed will also be deleted.
  35753. */
  35754. void removeSubItem (int index, bool deleteItem = true);
  35755. /** Returns the TreeView to which this item belongs. */
  35756. TreeView* getOwnerView() const throw() { return ownerView; }
  35757. /** Returns the item within which this item is contained. */
  35758. TreeViewItem* getParentItem() const throw() { return parentItem; }
  35759. /** True if this item is currently open in the treeview. */
  35760. bool isOpen() const throw();
  35761. /** Opens or closes the item.
  35762. When opened or closed, the item's itemOpennessChanged() method will be called,
  35763. and a subclass should use this callback to create and add any sub-items that
  35764. it needs to.
  35765. @see itemOpennessChanged, mightContainSubItems
  35766. */
  35767. void setOpen (bool shouldBeOpen);
  35768. /** True if this item is currently selected.
  35769. Use this when painting the node, to decide whether to draw it as selected or not.
  35770. */
  35771. bool isSelected() const throw();
  35772. /** Selects or deselects the item.
  35773. This will cause a callback to itemSelectionChanged()
  35774. */
  35775. void setSelected (bool shouldBeSelected,
  35776. bool deselectOtherItemsFirst);
  35777. /** Returns the rectangle that this item occupies.
  35778. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  35779. top-left of the TreeView comp, so this will depend on the scroll-position of
  35780. the tree. If false, it is relative to the top-left of the topmost item in the
  35781. tree (so this would be unaffected by scrolling the view).
  35782. */
  35783. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  35784. /** Sends a signal to the treeview to make it refresh itself.
  35785. Call this if your items have changed and you want the tree to update to reflect
  35786. this.
  35787. */
  35788. void treeHasChanged() const throw();
  35789. /** Sends a repaint message to redraw just this item.
  35790. Note that you should only call this if you want to repaint a superficial change. If
  35791. you're altering the tree's nodes, you should instead call treeHasChanged().
  35792. */
  35793. void repaintItem() const;
  35794. /** Returns the row number of this item in the tree.
  35795. The row number of an item will change according to which items are open.
  35796. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  35797. */
  35798. int getRowNumberInTree() const throw();
  35799. /** Returns true if all the item's parent nodes are open.
  35800. This is useful to check whether the item might actually be visible or not.
  35801. */
  35802. bool areAllParentsOpen() const throw();
  35803. /** Changes whether lines are drawn to connect any sub-items to this item.
  35804. By default, line-drawing is turned on.
  35805. */
  35806. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  35807. /** Tells the tree whether this item can potentially be opened.
  35808. If your item could contain sub-items, this should return true; if it returns
  35809. false then the tree will not try to open the item. This determines whether or
  35810. not the item will be drawn with a 'plus' button next to it.
  35811. */
  35812. virtual bool mightContainSubItems() = 0;
  35813. /** Returns a string to uniquely identify this item.
  35814. If you're planning on using the TreeView::getOpennessState() method, then
  35815. these strings will be used to identify which nodes are open. The string
  35816. should be unique amongst the item's sibling items, but it's ok for there
  35817. to be duplicates at other levels of the tree.
  35818. If you're not going to store the state, then it's ok not to bother implementing
  35819. this method.
  35820. */
  35821. virtual const String getUniqueName() const;
  35822. /** Called when an item is opened or closed.
  35823. When setOpen() is called and the item has specified that it might
  35824. have sub-items with the mightContainSubItems() method, this method
  35825. is called to let the item create or manage its sub-items.
  35826. So when this is called with isNowOpen set to true (i.e. when the item is being
  35827. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  35828. refresh its sub-item list.
  35829. When this is called with isNowOpen set to false, the subclass might want
  35830. to use clearSubItems() to save on space, or it might choose to leave them,
  35831. depending on the nature of the tree.
  35832. You could also use this callback as a trigger to start a background process
  35833. which asynchronously creates sub-items and adds them, if that's more
  35834. appropriate for the task in hand.
  35835. @see mightContainSubItems
  35836. */
  35837. virtual void itemOpennessChanged (bool isNowOpen);
  35838. /** Must return the width required by this item.
  35839. If your item needs to have a particular width in pixels, return that value; if
  35840. you'd rather have it just fill whatever space is available in the treeview,
  35841. return -1.
  35842. If all your items return -1, no horizontal scrollbar will be shown, but if any
  35843. items have fixed widths and extend beyond the width of the treeview, a
  35844. scrollbar will appear.
  35845. Each item can be a different width, but if they change width, you should call
  35846. treeHasChanged() to update the tree.
  35847. */
  35848. virtual int getItemWidth() const { return -1; }
  35849. /** Must return the height required by this item.
  35850. This is the height in pixels that the item will take up. Items in the tree
  35851. can be different heights, but if they change height, you should call
  35852. treeHasChanged() to update the tree.
  35853. */
  35854. virtual int getItemHeight() const { return 20; }
  35855. /** You can override this method to return false if you don't want to allow the
  35856. user to select this item.
  35857. */
  35858. virtual bool canBeSelected() const { return true; }
  35859. /** Creates a component that will be used to represent this item.
  35860. You don't have to implement this method - if it returns 0 then no component
  35861. will be used for the item, and you can just draw it using the paintItem()
  35862. callback. But if you do return a component, it will be positioned in the
  35863. treeview so that it can be used to represent this item.
  35864. The component returned will be managed by the treeview, so always return
  35865. a new component, and don't keep a reference to it, as the treeview will
  35866. delete it later when it goes off the screen or is no longer needed. Also
  35867. bear in mind that if the component keeps a reference to the item that
  35868. created it, that item could be deleted before the component. Its position
  35869. and size will be completely managed by the tree, so don't attempt to move it
  35870. around.
  35871. Something you may want to do with your component is to give it a pointer to
  35872. the TreeView that created it. This is perfectly safe, and there's no danger
  35873. of it becoming a dangling pointer because the TreeView will always delete
  35874. the component before it is itself deleted.
  35875. As long as you stick to these rules you can return whatever kind of
  35876. component you like. It's most useful if you're doing things like drag-and-drop
  35877. of items, or want to use a Label component to edit item names, etc.
  35878. */
  35879. virtual Component* createItemComponent() { return 0; }
  35880. /** Draws the item's contents.
  35881. You can choose to either implement this method and draw each item, or you
  35882. can use createItemComponent() to create a component that will represent the
  35883. item.
  35884. If all you need in your tree is to be able to draw the items and detect when
  35885. the user selects or double-clicks one of them, it's probably enough to
  35886. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  35887. complicated interactions, you may need to use createItemComponent() instead.
  35888. @param g the graphics context to draw into
  35889. @param width the width of the area available for drawing
  35890. @param height the height of the area available for drawing
  35891. */
  35892. virtual void paintItem (Graphics& g, int width, int height);
  35893. /** Draws the item's open/close button.
  35894. If you don't implement this method, the default behaviour is to
  35895. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  35896. it for custom effects.
  35897. */
  35898. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  35899. /** Called when the user clicks on this item.
  35900. If you're using createItemComponent() to create a custom component for the
  35901. item, the mouse-clicks might not make it through to the treeview, but this
  35902. is how you find out about clicks when just drawing each item individually.
  35903. The associated mouse-event details are passed in, so you can find out about
  35904. which button, where it was, etc.
  35905. @see itemDoubleClicked
  35906. */
  35907. virtual void itemClicked (const MouseEvent& e);
  35908. /** Called when the user double-clicks on this item.
  35909. If you're using createItemComponent() to create a custom component for the
  35910. item, the mouse-clicks might not make it through to the treeview, but this
  35911. is how you find out about clicks when just drawing each item individually.
  35912. The associated mouse-event details are passed in, so you can find out about
  35913. which button, where it was, etc.
  35914. If not overridden, the base class method here will open or close the item as
  35915. if the 'plus' button had been clicked.
  35916. @see itemClicked
  35917. */
  35918. virtual void itemDoubleClicked (const MouseEvent& e);
  35919. /** Called when the item is selected or deselected.
  35920. Use this if you want to do something special when the item's selectedness
  35921. changes. By default it'll get repainted when this happens.
  35922. */
  35923. virtual void itemSelectionChanged (bool isNowSelected);
  35924. /** The item can return a tool tip string here if it wants to.
  35925. @see TooltipClient
  35926. */
  35927. virtual const String getTooltip();
  35928. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  35929. If this returns a non-empty name then when the user drags an item, the treeview will
  35930. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  35931. a drag-and-drop operation, using this string as the source description, with the treeview
  35932. itself as the source component.
  35933. If you need more complex drag-and-drop behaviour, you can use custom components for
  35934. the items, and use those to trigger the drag.
  35935. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  35936. isInterestedInFileDrag(), etc.
  35937. @see DragAndDropContainer::startDragging
  35938. */
  35939. virtual const String getDragSourceDescription();
  35940. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  35941. method and return true.
  35942. If you return true and allow some files to be dropped, you'll also need to implement the
  35943. filesDropped() method to do something with them.
  35944. Note that this will be called often, so make your implementation very quick! There's
  35945. certainly no time to try opening the files and having a think about what's inside them!
  35946. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  35947. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  35948. */
  35949. virtual bool isInterestedInFileDrag (const StringArray& files);
  35950. /** When files are dropped into this item, this callback is invoked.
  35951. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  35952. The insertIndex value indicates where in the list of sub-items the files were dropped.
  35953. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  35954. */
  35955. virtual void filesDropped (const StringArray& files, int insertIndex);
  35956. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  35957. If you implement this method, you'll also need to implement itemDropped() in order to handle
  35958. the items when they are dropped.
  35959. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  35960. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  35961. */
  35962. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  35963. /** When a things are dropped into this item, this callback is invoked.
  35964. For this to work, you need to have also implemented isInterestedInDragSource().
  35965. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  35966. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  35967. */
  35968. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  35969. /** Sets a flag to indicate that the item wants to be allowed
  35970. to draw all the way across to the left edge of the treeview.
  35971. By default this is false, which means that when the paintItem()
  35972. method is called, its graphics context is clipped to only allow
  35973. drawing within the item's rectangle. If this flag is set to true,
  35974. then the graphics context isn't clipped on its left side, so it
  35975. can draw all the way across to the left margin. Note that the
  35976. context will still have its origin in the same place though, so
  35977. the coordinates of anything to its left will be negative. It's
  35978. mostly useful if you want to draw a wider bar behind the
  35979. highlighted item.
  35980. */
  35981. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  35982. /** Saves the current state of open/closed nodes so it can be restored later.
  35983. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  35984. and records it as XML. To identify node objects it uses the
  35985. TreeViewItem::getUniqueName() method to create named paths. This
  35986. means that the same state of open/closed nodes can be restored to a
  35987. completely different instance of the tree, as long as it contains nodes
  35988. whose unique names are the same.
  35989. You'd normally want to use TreeView::getOpennessState() rather than call it
  35990. for a specific item, but this can be handy if you need to briefly save the state
  35991. for a section of the tree.
  35992. The caller is responsible for deleting the object that is returned.
  35993. @see TreeView::getOpennessState, restoreOpennessState
  35994. */
  35995. XmlElement* getOpennessState() const throw();
  35996. /** Restores the openness of this item and all its sub-items from a saved state.
  35997. See TreeView::restoreOpennessState for more details.
  35998. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  35999. for a specific item, but this can be handy if you need to briefly save the state
  36000. for a section of the tree.
  36001. @see TreeView::restoreOpennessState, getOpennessState
  36002. */
  36003. void restoreOpennessState (const XmlElement& xml) throw();
  36004. /** Returns the index of this item in its parent's sub-items. */
  36005. int getIndexInParent() const throw();
  36006. /** Returns true if this item is the last of its parent's sub-itens. */
  36007. bool isLastOfSiblings() const throw();
  36008. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  36009. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  36010. The string takes the form of a path, constructed from the getUniqueName() of this
  36011. item and all its parents, so these must all be correctly implemented for it to work.
  36012. @see TreeView::findItemFromIdentifierString, getUniqueName
  36013. */
  36014. const String getItemIdentifierString() const;
  36015. juce_UseDebuggingNewOperator
  36016. private:
  36017. TreeView* ownerView;
  36018. TreeViewItem* parentItem;
  36019. OwnedArray <TreeViewItem> subItems;
  36020. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  36021. int uid;
  36022. bool selected : 1;
  36023. bool redrawNeeded : 1;
  36024. bool drawLinesInside : 1;
  36025. bool drawsInLeftMargin : 1;
  36026. unsigned int openness : 2;
  36027. friend class TreeView;
  36028. friend class TreeViewContentComponent;
  36029. void updatePositions (int newY);
  36030. int getIndentX() const throw();
  36031. void setOwnerView (TreeView* newOwner) throw();
  36032. void paintRecursively (Graphics& g, int width);
  36033. TreeViewItem* getTopLevelItem() throw();
  36034. TreeViewItem* findItemRecursively (int y) throw();
  36035. TreeViewItem* getDeepestOpenParentItem() throw();
  36036. int getNumRows() const throw();
  36037. TreeViewItem* getItemOnRow (int index) throw();
  36038. void deselectAllRecursively();
  36039. int countSelectedItemsRecursively() const throw();
  36040. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  36041. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  36042. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  36043. TreeViewItem (const TreeViewItem&);
  36044. TreeViewItem& operator= (const TreeViewItem&);
  36045. };
  36046. /**
  36047. A tree-view component.
  36048. Use one of these to hold and display a structure of TreeViewItem objects.
  36049. */
  36050. class JUCE_API TreeView : public Component,
  36051. public SettableTooltipClient,
  36052. public FileDragAndDropTarget,
  36053. public DragAndDropTarget,
  36054. private AsyncUpdater
  36055. {
  36056. public:
  36057. /** Creates an empty treeview.
  36058. Once you've got a treeview component, you'll need to give it something to
  36059. display, using the setRootItem() method.
  36060. */
  36061. TreeView (const String& componentName = String::empty);
  36062. /** Destructor. */
  36063. ~TreeView();
  36064. /** Sets the item that is displayed in the treeview.
  36065. A tree has a single root item which contains as many sub-items as it needs. If
  36066. you want the tree to contain a number of root items, you should still use a single
  36067. root item above these, but hide it using setRootItemVisible().
  36068. You can pass in 0 to this method to clear the tree and remove its current root item.
  36069. The object passed in will not be deleted by the treeview, it's up to the caller
  36070. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  36071. this item until you've removed it from the tree, either by calling setRootItem (0),
  36072. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  36073. to delete it.
  36074. */
  36075. void setRootItem (TreeViewItem* newRootItem);
  36076. /** Returns the tree's root item.
  36077. This will be the last object passed to setRootItem(), or 0 if none has been set.
  36078. */
  36079. TreeViewItem* getRootItem() const throw() { return rootItem; }
  36080. /** This will remove and delete the current root item.
  36081. It's a convenient way of deleting the item and calling setRootItem (0).
  36082. */
  36083. void deleteRootItem();
  36084. /** Changes whether the tree's root item is shown or not.
  36085. If the root item is hidden, only its sub-items will be shown in the treeview - this
  36086. lets you make the tree look as if it's got many root items. If it's hidden, this call
  36087. will also make sure the root item is open (otherwise the treeview would look empty).
  36088. */
  36089. void setRootItemVisible (bool shouldBeVisible);
  36090. /** Returns true if the root item is visible.
  36091. @see setRootItemVisible
  36092. */
  36093. bool isRootItemVisible() const throw() { return rootItemVisible; }
  36094. /** Sets whether items are open or closed by default.
  36095. Normally, items are closed until the user opens them, but you can use this
  36096. to make them default to being open until explicitly closed.
  36097. @see areItemsOpenByDefault
  36098. */
  36099. void setDefaultOpenness (bool isOpenByDefault);
  36100. /** Returns true if the tree's items default to being open.
  36101. @see setDefaultOpenness
  36102. */
  36103. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  36104. /** This sets a flag to indicate that the tree can be used for multi-selection.
  36105. You can always select multiple items internally by calling the
  36106. TreeViewItem::setSelected() method, but this flag indicates whether the user
  36107. is allowed to multi-select by clicking on the tree.
  36108. By default it is disabled.
  36109. @see isMultiSelectEnabled
  36110. */
  36111. void setMultiSelectEnabled (bool canMultiSelect);
  36112. /** Returns whether multi-select has been enabled for the tree.
  36113. @see setMultiSelectEnabled
  36114. */
  36115. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  36116. /** Sets a flag to indicate whether to hide the open/close buttons.
  36117. @see areOpenCloseButtonsVisible
  36118. */
  36119. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  36120. /** Returns whether open/close buttons are shown.
  36121. @see setOpenCloseButtonsVisible
  36122. */
  36123. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  36124. /** Deselects any items that are currently selected. */
  36125. void clearSelectedItems();
  36126. /** Returns the number of items that are currently selected.
  36127. @see getSelectedItem, clearSelectedItems
  36128. */
  36129. int getNumSelectedItems() const throw();
  36130. /** Returns one of the selected items in the tree.
  36131. @param index the index, 0 to (getNumSelectedItems() - 1)
  36132. */
  36133. TreeViewItem* getSelectedItem (int index) const throw();
  36134. /** Returns the number of rows the tree is using.
  36135. This will depend on which items are open.
  36136. @see TreeViewItem::getRowNumberInTree()
  36137. */
  36138. int getNumRowsInTree() const;
  36139. /** Returns the item on a particular row of the tree.
  36140. If the index is out of range, this will return 0.
  36141. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  36142. */
  36143. TreeViewItem* getItemOnRow (int index) const;
  36144. /** Returns the item that contains a given y position.
  36145. The y is relative to the top of the TreeView component.
  36146. */
  36147. TreeViewItem* getItemAt (int yPosition) const throw();
  36148. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  36149. void scrollToKeepItemVisible (TreeViewItem* item);
  36150. /** Returns the treeview's Viewport object. */
  36151. Viewport* getViewport() const throw();
  36152. /** Returns the number of pixels by which each nested level of the tree is indented.
  36153. @see setIndentSize
  36154. */
  36155. int getIndentSize() const throw() { return indentSize; }
  36156. /** Changes the distance by which each nested level of the tree is indented.
  36157. @see getIndentSize
  36158. */
  36159. void setIndentSize (int newIndentSize);
  36160. /** Searches the tree for an item with the specified identifier.
  36161. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  36162. If no such item exists, this will return false. If the item is found, all of its items
  36163. will be automatically opened.
  36164. */
  36165. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  36166. /** Saves the current state of open/closed nodes so it can be restored later.
  36167. This takes a snapshot of which nodes have been explicitly opened or closed,
  36168. and records it as XML. To identify node objects it uses the
  36169. TreeViewItem::getUniqueName() method to create named paths. This
  36170. means that the same state of open/closed nodes can be restored to a
  36171. completely different instance of the tree, as long as it contains nodes
  36172. whose unique names are the same.
  36173. The caller is responsible for deleting the object that is returned.
  36174. @param alsoIncludeScrollPosition if this is true, the state will also
  36175. include information about where the
  36176. tree has been scrolled to vertically,
  36177. so this can also be restored
  36178. @see restoreOpennessState
  36179. */
  36180. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  36181. /** Restores a previously saved arrangement of open/closed nodes.
  36182. This will try to restore a snapshot of the tree's state that was created by
  36183. the getOpennessState() method. If any of the nodes named in the original
  36184. XML aren't present in this tree, they will be ignored.
  36185. @see getOpennessState
  36186. */
  36187. void restoreOpennessState (const XmlElement& newState);
  36188. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  36189. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36190. methods.
  36191. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36192. */
  36193. enum ColourIds
  36194. {
  36195. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  36196. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  36197. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  36198. };
  36199. /** @internal */
  36200. void paint (Graphics& g);
  36201. /** @internal */
  36202. void resized();
  36203. /** @internal */
  36204. bool keyPressed (const KeyPress& key);
  36205. /** @internal */
  36206. void colourChanged();
  36207. /** @internal */
  36208. void enablementChanged();
  36209. /** @internal */
  36210. bool isInterestedInFileDrag (const StringArray& files);
  36211. /** @internal */
  36212. void fileDragEnter (const StringArray& files, int x, int y);
  36213. /** @internal */
  36214. void fileDragMove (const StringArray& files, int x, int y);
  36215. /** @internal */
  36216. void fileDragExit (const StringArray& files);
  36217. /** @internal */
  36218. void filesDropped (const StringArray& files, int x, int y);
  36219. /** @internal */
  36220. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  36221. /** @internal */
  36222. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36223. /** @internal */
  36224. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36225. /** @internal */
  36226. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  36227. /** @internal */
  36228. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36229. juce_UseDebuggingNewOperator
  36230. private:
  36231. friend class TreeViewItem;
  36232. friend class TreeViewContentComponent;
  36233. class TreeViewport;
  36234. class InsertPointHighlight;
  36235. class TargetGroupHighlight;
  36236. friend class ScopedPointer<TreeViewport>;
  36237. friend class ScopedPointer<InsertPointHighlight>;
  36238. friend class ScopedPointer<TargetGroupHighlight>;
  36239. ScopedPointer<TreeViewport> viewport;
  36240. CriticalSection nodeAlterationLock;
  36241. TreeViewItem* rootItem;
  36242. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  36243. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  36244. int indentSize;
  36245. bool defaultOpenness : 1;
  36246. bool needsRecalculating : 1;
  36247. bool rootItemVisible : 1;
  36248. bool multiSelectEnabled : 1;
  36249. bool openCloseButtonsVisible : 1;
  36250. void itemsChanged() throw();
  36251. void handleAsyncUpdate();
  36252. void moveSelectedRow (int delta);
  36253. void updateButtonUnderMouse (const MouseEvent& e);
  36254. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  36255. void hideDragHighlight() throw();
  36256. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  36257. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  36258. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  36259. const StringArray& files, const String& sourceDescription,
  36260. Component* sourceComponent) const throw();
  36261. TreeView (const TreeView&);
  36262. TreeView& operator= (const TreeView&);
  36263. };
  36264. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  36265. /*** End of inlined file: juce_TreeView.h ***/
  36266. #endif
  36267. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36268. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  36269. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36270. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36271. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  36272. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36273. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36274. /*** Start of inlined file: juce_FileFilter.h ***/
  36275. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36276. #define __JUCE_FILEFILTER_JUCEHEADER__
  36277. /**
  36278. Interface for deciding which files are suitable for something.
  36279. For example, this is used by DirectoryContentsList to select which files
  36280. go into the list.
  36281. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36282. */
  36283. class JUCE_API FileFilter
  36284. {
  36285. public:
  36286. /** Creates a filter with the given description.
  36287. The description can be returned later with the getDescription() method.
  36288. */
  36289. FileFilter (const String& filterDescription);
  36290. /** Destructor. */
  36291. virtual ~FileFilter();
  36292. /** Returns the description that the filter was created with. */
  36293. const String& getDescription() const throw();
  36294. /** Should return true if this file is suitable for inclusion in whatever context
  36295. the object is being used.
  36296. */
  36297. virtual bool isFileSuitable (const File& file) const = 0;
  36298. /** Should return true if this directory is suitable for inclusion in whatever context
  36299. the object is being used.
  36300. */
  36301. virtual bool isDirectorySuitable (const File& file) const = 0;
  36302. protected:
  36303. String description;
  36304. };
  36305. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36306. /*** End of inlined file: juce_FileFilter.h ***/
  36307. /**
  36308. A class to asynchronously scan for details about the files in a directory.
  36309. This keeps a list of files and some information about them, using a background
  36310. thread to scan for more files. As files are found, it broadcasts change messages
  36311. to tell any listeners.
  36312. @see FileListComponent, FileBrowserComponent
  36313. */
  36314. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36315. public TimeSliceClient
  36316. {
  36317. public:
  36318. /** Creates a directory list.
  36319. To set the directory it should point to, use setDirectory(), which will
  36320. also start it scanning for files on the background thread.
  36321. When the background thread finds and adds new files to this list, the
  36322. ChangeBroadcaster class will send a change message, so you can register
  36323. listeners and update them when the list changes.
  36324. @param fileFilter an optional filter to select which files are
  36325. included in the list. If this is 0, then all files
  36326. and directories are included. Make sure that the
  36327. filter doesn't get deleted during the lifetime of this
  36328. object
  36329. @param threadToUse a thread object that this list can use
  36330. to scan for files as a background task. Make sure
  36331. that the thread you give it has been started, or you
  36332. won't get any files!
  36333. */
  36334. DirectoryContentsList (const FileFilter* fileFilter,
  36335. TimeSliceThread& threadToUse);
  36336. /** Destructor. */
  36337. ~DirectoryContentsList();
  36338. /** Sets the directory to look in for files.
  36339. If the directory that's passed in is different to the current one, this will
  36340. also start the background thread scanning it for files.
  36341. */
  36342. void setDirectory (const File& directory,
  36343. bool includeDirectories,
  36344. bool includeFiles);
  36345. /** Returns the directory that's currently being used. */
  36346. const File& getDirectory() const;
  36347. /** Clears the list, and stops the thread scanning for files. */
  36348. void clear();
  36349. /** Clears the list and restarts scanning the directory for files. */
  36350. void refresh();
  36351. /** True if the background thread hasn't yet finished scanning for files. */
  36352. bool isStillLoading() const;
  36353. /** Tells the list whether or not to ignore hidden files.
  36354. By default these are ignored.
  36355. */
  36356. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  36357. /** Returns true if hidden files are ignored.
  36358. @see setIgnoresHiddenFiles
  36359. */
  36360. bool ignoresHiddenFiles() const;
  36361. /** Contains cached information about one of the files in a DirectoryContentsList.
  36362. */
  36363. struct FileInfo
  36364. {
  36365. /** The filename.
  36366. This isn't a full pathname, it's just the last part of the path, same as you'd
  36367. get from File::getFileName().
  36368. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36369. */
  36370. String filename;
  36371. /** File size in bytes. */
  36372. int64 fileSize;
  36373. /** File modification time.
  36374. As supplied by File::getLastModificationTime().
  36375. */
  36376. Time modificationTime;
  36377. /** File creation time.
  36378. As supplied by File::getCreationTime().
  36379. */
  36380. Time creationTime;
  36381. /** True if the file is a directory. */
  36382. bool isDirectory;
  36383. /** True if the file is read-only. */
  36384. bool isReadOnly;
  36385. };
  36386. /** Returns the number of files currently available in the list.
  36387. The info about one of these files can be retrieved with getFileInfo() or
  36388. getFile().
  36389. Obviously as the background thread runs and scans the directory for files, this
  36390. number will change.
  36391. @see getFileInfo, getFile
  36392. */
  36393. int getNumFiles() const;
  36394. /** Returns the cached information about one of the files in the list.
  36395. If the index is in-range, this will return true and will copy the file's details
  36396. to the structure that is passed-in.
  36397. If it returns false, then the index wasn't in range, and the structure won't
  36398. be affected.
  36399. @see getNumFiles, getFile
  36400. */
  36401. bool getFileInfo (int index, FileInfo& resultInfo) const;
  36402. /** Returns one of the files in the list.
  36403. @param index should be less than getNumFiles(). If this is out-of-range, the
  36404. return value will be File::nonexistent
  36405. @see getNumFiles, getFileInfo
  36406. */
  36407. const File getFile (int index) const;
  36408. /** Returns the file filter being used.
  36409. The filter is specified in the constructor.
  36410. */
  36411. const FileFilter* getFilter() const { return fileFilter; }
  36412. /** @internal */
  36413. bool useTimeSlice();
  36414. /** @internal */
  36415. TimeSliceThread& getTimeSliceThread() { return thread; }
  36416. /** @internal */
  36417. static int compareElements (const DirectoryContentsList::FileInfo* first,
  36418. const DirectoryContentsList::FileInfo* second);
  36419. juce_UseDebuggingNewOperator
  36420. private:
  36421. File root;
  36422. const FileFilter* fileFilter;
  36423. TimeSliceThread& thread;
  36424. int fileTypeFlags;
  36425. CriticalSection fileListLock;
  36426. OwnedArray <FileInfo> files;
  36427. ScopedPointer <DirectoryIterator> fileFindHandle;
  36428. bool volatile shouldStop;
  36429. void changed();
  36430. bool checkNextFile (bool& hasChanged);
  36431. bool addFile (const File& file, bool isDir,
  36432. const int64 fileSize, const Time& modTime,
  36433. const Time& creationTime, bool isReadOnly);
  36434. void setTypeFlags (int newFlags);
  36435. DirectoryContentsList (const DirectoryContentsList&);
  36436. DirectoryContentsList& operator= (const DirectoryContentsList&);
  36437. };
  36438. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36439. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  36440. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  36441. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36442. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36443. /**
  36444. A listener for user selection events in a file browser.
  36445. This is used by a FileBrowserComponent or FileListComponent.
  36446. */
  36447. class JUCE_API FileBrowserListener
  36448. {
  36449. public:
  36450. /** Destructor. */
  36451. virtual ~FileBrowserListener();
  36452. /** Callback when the user selects a different file in the browser. */
  36453. virtual void selectionChanged() = 0;
  36454. /** Callback when the user clicks on a file in the browser. */
  36455. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36456. /** Callback when the user double-clicks on a file in the browser. */
  36457. virtual void fileDoubleClicked (const File& file) = 0;
  36458. };
  36459. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36460. /*** End of inlined file: juce_FileBrowserListener.h ***/
  36461. /**
  36462. A base class for components that display a list of the files in a directory.
  36463. @see DirectoryContentsList
  36464. */
  36465. class JUCE_API DirectoryContentsDisplayComponent
  36466. {
  36467. public:
  36468. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  36469. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36470. /** Destructor. */
  36471. virtual ~DirectoryContentsDisplayComponent();
  36472. /** Returns the number of files the user has got selected.
  36473. @see getSelectedFile
  36474. */
  36475. virtual int getNumSelectedFiles() const = 0;
  36476. /** Returns one of the files that the user has currently selected.
  36477. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  36478. @see getNumSelectedFiles
  36479. */
  36480. virtual const File getSelectedFile (int index) const = 0;
  36481. /** Deselects any selected files. */
  36482. virtual void deselectAllFiles() = 0;
  36483. /** Scrolls this view to the top. */
  36484. virtual void scrollToTop() = 0;
  36485. /** Adds a listener to be told when files are selected or clicked.
  36486. @see removeListener
  36487. */
  36488. void addListener (FileBrowserListener* listener);
  36489. /** Removes a listener.
  36490. @see addListener
  36491. */
  36492. void removeListener (FileBrowserListener* listener);
  36493. /** A set of colour IDs to use to change the colour of various aspects of the list.
  36494. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36495. methods.
  36496. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36497. */
  36498. enum ColourIds
  36499. {
  36500. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36501. textColourId = 0x1000541, /**< The colour for the text. */
  36502. };
  36503. /** @internal */
  36504. void sendSelectionChangeMessage();
  36505. /** @internal */
  36506. void sendDoubleClickMessage (const File& file);
  36507. /** @internal */
  36508. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36509. juce_UseDebuggingNewOperator
  36510. protected:
  36511. DirectoryContentsList& fileList;
  36512. ListenerList <FileBrowserListener> listeners;
  36513. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36514. DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36515. };
  36516. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36517. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  36518. #endif
  36519. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36520. #endif
  36521. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36522. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  36523. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36524. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36525. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  36526. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36527. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36528. /**
  36529. Base class for components that live inside a file chooser dialog box and
  36530. show previews of the files that get selected.
  36531. One of these allows special extra information to be displayed for files
  36532. in a dialog box as the user selects them. Each time the current file or
  36533. directory is changed, the selectedFileChanged() method will be called
  36534. to allow it to update itself appropriately.
  36535. @see FileChooser, ImagePreviewComponent
  36536. */
  36537. class JUCE_API FilePreviewComponent : public Component
  36538. {
  36539. public:
  36540. /** Creates a FilePreviewComponent. */
  36541. FilePreviewComponent();
  36542. /** Destructor. */
  36543. ~FilePreviewComponent();
  36544. /** Called to indicate that the user's currently selected file has changed.
  36545. @param newSelectedFile the newly selected file or directory, which may be
  36546. File::nonexistent if none is selected.
  36547. */
  36548. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36549. juce_UseDebuggingNewOperator
  36550. private:
  36551. FilePreviewComponent (const FilePreviewComponent&);
  36552. FilePreviewComponent& operator= (const FilePreviewComponent&);
  36553. };
  36554. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36555. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  36556. /**
  36557. A component for browsing and selecting a file or directory to open or save.
  36558. This contains a FileListComponent and adds various boxes and controls for
  36559. navigating and selecting a file. It can work in different modes so that it can
  36560. be used for loading or saving a file, or for choosing a directory.
  36561. @see FileChooserDialogBox, FileChooser, FileListComponent
  36562. */
  36563. class JUCE_API FileBrowserComponent : public Component,
  36564. public ChangeBroadcaster,
  36565. private FileBrowserListener,
  36566. private TextEditorListener,
  36567. private ButtonListener,
  36568. private ComboBoxListener,
  36569. private FileFilter
  36570. {
  36571. public:
  36572. /** Various options for the browser.
  36573. A combination of these is passed into the FileBrowserComponent constructor.
  36574. */
  36575. enum FileChooserFlags
  36576. {
  36577. openMode = 1, /**< specifies that the component should allow the user to
  36578. choose an existing file with the intention of opening it. */
  36579. saveMode = 2, /**< specifies that the component should allow the user to specify
  36580. the name of a file that will be used to save something. */
  36581. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  36582. conjunction with canSelectDirectories). */
  36583. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  36584. conjuction with canSelectFiles). */
  36585. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  36586. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  36587. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  36588. };
  36589. /** Creates a FileBrowserComponent.
  36590. @param flags A combination of flags from the FileChooserFlags enumeration,
  36591. used to specify the component's behaviour. The flags must contain
  36592. either openMode or saveMode, and canSelectFiles and/or
  36593. canSelectDirectories.
  36594. @param initialFileOrDirectory The file or directory that should be selected when
  36595. the component begins. If this is File::nonexistent,
  36596. a default directory will be chosen.
  36597. @param fileFilter an optional filter to use to determine which files
  36598. are shown. If this is 0 then all files are displayed. Note
  36599. that a pointer is kept internally to this object, so
  36600. make sure that it is not deleted before the browser object
  36601. is deleted.
  36602. @param previewComp an optional preview component that will be used to
  36603. show previews of files that the user selects
  36604. */
  36605. FileBrowserComponent (int flags,
  36606. const File& initialFileOrDirectory,
  36607. const FileFilter* fileFilter,
  36608. FilePreviewComponent* previewComp);
  36609. /** Destructor. */
  36610. ~FileBrowserComponent();
  36611. /** Returns the number of files that the user has got selected.
  36612. If multiple select isn't active, this will only be 0 or 1. To get the complete
  36613. list of files they've chosen, pass an index to getCurrentFile().
  36614. */
  36615. int getNumSelectedFiles() const throw();
  36616. /** Returns one of the files that the user has chosen.
  36617. If the box has multi-select enabled, the index lets you specify which of the files
  36618. to get - see getNumSelectedFiles() to find out how many files were chosen.
  36619. @see getHighlightedFile
  36620. */
  36621. const File getSelectedFile (int index) const throw();
  36622. /** Deselects any files that are currently selected.
  36623. */
  36624. void deselectAllFiles();
  36625. /** Returns true if the currently selected file(s) are usable.
  36626. This can be used to decide whether the user can press "ok" for the
  36627. current file. What it does depends on the mode, so for example in an "open"
  36628. mode, this only returns true if a file has been selected and if it exists.
  36629. In a "save" mode, a non-existent file would also be valid.
  36630. */
  36631. bool currentFileIsValid() const;
  36632. /** This returns the last item in the view that the user has highlighted.
  36633. This may be different from getCurrentFile(), which returns the value
  36634. that is shown in the filename box, and if there are multiple selections,
  36635. this will only return one of them.
  36636. @see getSelectedFile
  36637. */
  36638. const File getHighlightedFile() const throw();
  36639. /** Returns the directory whose contents are currently being shown in the listbox. */
  36640. const File getRoot() const;
  36641. /** Changes the directory that's being shown in the listbox. */
  36642. void setRoot (const File& newRootDirectory);
  36643. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36644. void goUp();
  36645. /** Refreshes the directory that's currently being listed. */
  36646. void refresh();
  36647. /** Returns a verb to describe what should happen when the file is accepted.
  36648. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36649. mode, it'll be "Save", etc.
  36650. */
  36651. virtual const String getActionVerb() const;
  36652. /** Returns true if the saveMode flag was set when this component was created.
  36653. */
  36654. bool isSaveMode() const throw();
  36655. /** Adds a listener to be told when the user selects and clicks on files.
  36656. @see removeListener
  36657. */
  36658. void addListener (FileBrowserListener* listener);
  36659. /** Removes a listener.
  36660. @see addListener
  36661. */
  36662. void removeListener (FileBrowserListener* listener);
  36663. /** @internal */
  36664. void resized();
  36665. /** @internal */
  36666. void buttonClicked (Button* b);
  36667. /** @internal */
  36668. void comboBoxChanged (ComboBox*);
  36669. /** @internal */
  36670. void textEditorTextChanged (TextEditor& editor);
  36671. /** @internal */
  36672. void textEditorReturnKeyPressed (TextEditor& editor);
  36673. /** @internal */
  36674. void textEditorEscapeKeyPressed (TextEditor& editor);
  36675. /** @internal */
  36676. void textEditorFocusLost (TextEditor& editor);
  36677. /** @internal */
  36678. bool keyPressed (const KeyPress& key);
  36679. /** @internal */
  36680. void selectionChanged();
  36681. /** @internal */
  36682. void fileClicked (const File& f, const MouseEvent& e);
  36683. /** @internal */
  36684. void fileDoubleClicked (const File& f);
  36685. /** @internal */
  36686. bool isFileSuitable (const File& file) const;
  36687. /** @internal */
  36688. bool isDirectorySuitable (const File&) const;
  36689. /** @internal */
  36690. FilePreviewComponent* getPreviewComponent() const throw();
  36691. juce_UseDebuggingNewOperator
  36692. protected:
  36693. virtual const BigInteger getRoots (StringArray& rootNames, StringArray& rootPaths);
  36694. private:
  36695. ScopedPointer <DirectoryContentsList> fileList;
  36696. const FileFilter* fileFilter;
  36697. int flags;
  36698. File currentRoot;
  36699. Array<File> chosenFiles;
  36700. ListenerList <FileBrowserListener> listeners;
  36701. DirectoryContentsDisplayComponent* fileListComponent;
  36702. FilePreviewComponent* previewComp;
  36703. ComboBox* currentPathBox;
  36704. TextEditor* filenameBox;
  36705. Button* goUpButton;
  36706. TimeSliceThread thread;
  36707. void sendListenerChangeMessage();
  36708. bool isFileOrDirSuitable (const File& f) const;
  36709. FileBrowserComponent (const FileBrowserComponent&);
  36710. FileBrowserComponent& operator= (const FileBrowserComponent&);
  36711. };
  36712. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36713. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  36714. #endif
  36715. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36716. #endif
  36717. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36718. /*** Start of inlined file: juce_FileChooser.h ***/
  36719. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36720. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36721. /**
  36722. Creates a dialog box to choose a file or directory to load or save.
  36723. To use a FileChooser:
  36724. - create one (as a local stack variable is the neatest way)
  36725. - call one of its browseFor.. methods
  36726. - if this returns true, the user has selected a file, so you can retrieve it
  36727. with the getResult() method.
  36728. e.g. @code
  36729. void loadMooseFile()
  36730. {
  36731. FileChooser myChooser ("Please select the moose you want to load...",
  36732. File::getSpecialLocation (File::userHomeDirectory),
  36733. "*.moose");
  36734. if (myChooser.browseForFileToOpen())
  36735. {
  36736. File mooseFile (myChooser.getResult());
  36737. loadMoose (mooseFile);
  36738. }
  36739. }
  36740. @endcode
  36741. */
  36742. class JUCE_API FileChooser
  36743. {
  36744. public:
  36745. /** Creates a FileChooser.
  36746. After creating one of these, use one of the browseFor... methods to display it.
  36747. @param dialogBoxTitle a text string to display in the dialog box to
  36748. tell the user what's going on
  36749. @param initialFileOrDirectory the file or directory that should be selected when
  36750. the dialog box opens. If this parameter is set to
  36751. File::nonexistent, a sensible default directory
  36752. will be used instead.
  36753. @param filePatternsAllowed a set of file patterns to specify which files can be
  36754. selected - each pattern should be separated by a
  36755. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36756. empty string means that all files are allowed
  36757. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36758. possible; if false, then a Juce-based browser dialog
  36759. box will always be used
  36760. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36761. */
  36762. FileChooser (const String& dialogBoxTitle,
  36763. const File& initialFileOrDirectory = File::nonexistent,
  36764. const String& filePatternsAllowed = String::empty,
  36765. bool useOSNativeDialogBox = true);
  36766. /** Destructor. */
  36767. ~FileChooser();
  36768. /** Shows a dialog box to choose a file to open.
  36769. This will display the dialog box modally, using an "open file" mode, so that
  36770. it won't allow non-existent files or directories to be chosen.
  36771. @param previewComponent an optional component to display inside the dialog
  36772. box to show special info about the files that the user
  36773. is browsing. The component will not be deleted by this
  36774. object, so the caller must take care of it.
  36775. @returns true if the user selected a file, in which case, use the getResult()
  36776. method to find out what it was. Returns false if they cancelled instead.
  36777. @see browseForFileToSave, browseForDirectory
  36778. */
  36779. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36780. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36781. The files that are returned can be obtained by calling getResults(). See
  36782. browseForFileToOpen() for more info about the behaviour of this method.
  36783. */
  36784. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36785. /** Shows a dialog box to choose a file to save.
  36786. This will display the dialog box modally, using an "save file" mode, so it
  36787. will allow non-existent files to be chosen, but not directories.
  36788. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36789. the user if they're sure they want to overwrite a file that already
  36790. exists
  36791. @returns true if the user chose a file and pressed 'ok', in which case, use
  36792. the getResult() method to find out what the file was. Returns false
  36793. if they cancelled instead.
  36794. @see browseForFileToOpen, browseForDirectory
  36795. */
  36796. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  36797. /** Shows a dialog box to choose a directory.
  36798. This will display the dialog box modally, using an "open directory" mode, so it
  36799. will only allow directories to be returned, not files.
  36800. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36801. the getResult() method to find out what they chose. Returns false
  36802. if they cancelled instead.
  36803. @see browseForFileToOpen, browseForFileToSave
  36804. */
  36805. bool browseForDirectory();
  36806. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  36807. The files that are returned can be obtained by calling getResults(). See
  36808. browseForFileToOpen() for more info about the behaviour of this method.
  36809. */
  36810. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  36811. /** Returns the last file that was chosen by one of the browseFor methods.
  36812. After calling the appropriate browseFor... method, this method lets you
  36813. find out what file or directory they chose.
  36814. Note that the file returned is only valid if the browse method returned true (i.e.
  36815. if the user pressed 'ok' rather than cancelling).
  36816. If you're using a multiple-file select, then use the getResults() method instead,
  36817. to obtain the list of all files chosen.
  36818. @see getResults
  36819. */
  36820. const File getResult() const;
  36821. /** Returns a list of all the files that were chosen during the last call to a
  36822. browse method.
  36823. This array may be empty if no files were chosen, or can contain multiple entries
  36824. if multiple files were chosen.
  36825. @see getResult
  36826. */
  36827. const Array<File>& getResults() const;
  36828. juce_UseDebuggingNewOperator
  36829. private:
  36830. String title, filters;
  36831. File startingFile;
  36832. Array<File> results;
  36833. bool useNativeDialogBox;
  36834. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  36835. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36836. FilePreviewComponent* previewComponent);
  36837. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  36838. const String& filters, bool selectsDirectories, bool selectsFiles,
  36839. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36840. FilePreviewComponent* previewComponent);
  36841. };
  36842. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36843. /*** End of inlined file: juce_FileChooser.h ***/
  36844. #endif
  36845. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36846. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  36847. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36848. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36849. /*** Start of inlined file: juce_ResizableWindow.h ***/
  36850. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36851. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36852. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  36853. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36854. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36855. /*** Start of inlined file: juce_DropShadower.h ***/
  36856. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36857. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36858. /**
  36859. Adds a drop-shadow to a component.
  36860. This object creates and manages a set of components which sit around a
  36861. component, creating a gaussian shadow around it. The components will track
  36862. the position of the component and if it's brought to the front they'll also
  36863. follow this.
  36864. For desktop windows you don't need to use this class directly - just
  36865. set the Component::windowHasDropShadow flag when calling
  36866. Component::addToDesktop(), and the system will create one of these if it's
  36867. needed (which it obviously isn't on the Mac, for example).
  36868. */
  36869. class JUCE_API DropShadower : public ComponentListener
  36870. {
  36871. public:
  36872. /** Creates a DropShadower.
  36873. @param alpha the opacity of the shadows, from 0 to 1.0
  36874. @param xOffset the horizontal displacement of the shadow, in pixels
  36875. @param yOffset the vertical displacement of the shadow, in pixels
  36876. @param blurRadius the radius of the blur to use for creating the shadow
  36877. */
  36878. DropShadower (float alpha = 0.5f,
  36879. int xOffset = 1,
  36880. int yOffset = 5,
  36881. float blurRadius = 10.0f);
  36882. /** Destructor. */
  36883. virtual ~DropShadower();
  36884. /** Attaches the DropShadower to the component you want to shadow. */
  36885. void setOwner (Component* componentToFollow);
  36886. /** @internal */
  36887. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36888. /** @internal */
  36889. void componentBroughtToFront (Component& component);
  36890. /** @internal */
  36891. void componentChildrenChanged (Component& component);
  36892. /** @internal */
  36893. void componentParentHierarchyChanged (Component& component);
  36894. /** @internal */
  36895. void componentVisibilityChanged (Component& component);
  36896. juce_UseDebuggingNewOperator
  36897. private:
  36898. Component* owner;
  36899. int numShadows;
  36900. Component* shadowWindows[4];
  36901. Image shadowImageSections[12];
  36902. const int shadowEdge, xOffset, yOffset;
  36903. const float alpha, blurRadius;
  36904. bool inDestructor, reentrant;
  36905. void updateShadows();
  36906. void setShadowImage (const Image& src,
  36907. const int num,
  36908. const int w, const int h,
  36909. const int sx, const int sy);
  36910. void bringShadowWindowsToFront();
  36911. void deleteShadowWindows();
  36912. DropShadower (const DropShadower&);
  36913. DropShadower& operator= (const DropShadower&);
  36914. };
  36915. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  36916. /*** End of inlined file: juce_DropShadower.h ***/
  36917. /**
  36918. A base class for top-level windows.
  36919. This class is used for components that are considered a major part of your
  36920. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  36921. etc. Things like menus that pop up briefly aren't derived from it.
  36922. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  36923. could itself be the child of another component.
  36924. The class manages a list of all instances of top-level windows that are in use,
  36925. and each one is also given the concept of being "active". The active window is
  36926. one that is actively being used by the user. This isn't quite the same as the
  36927. component with the keyboard focus, because there may be a popup menu or other
  36928. temporary window which gets keyboard focus while the active top level window is
  36929. unchanged.
  36930. A top-level window also has an optional drop-shadow.
  36931. @see ResizableWindow, DocumentWindow, DialogWindow
  36932. */
  36933. class JUCE_API TopLevelWindow : public Component
  36934. {
  36935. public:
  36936. /** Creates a TopLevelWindow.
  36937. @param name the name to give the component
  36938. @param addToDesktop if true, the window will be automatically added to the
  36939. desktop; if false, you can use it as a child component
  36940. */
  36941. TopLevelWindow (const String& name, bool addToDesktop);
  36942. /** Destructor. */
  36943. ~TopLevelWindow();
  36944. /** True if this is currently the TopLevelWindow that is actively being used.
  36945. This isn't quite the same as having keyboard focus, because the focus may be
  36946. on a child component or a temporary pop-up menu, etc, while this window is
  36947. still considered to be active.
  36948. @see activeWindowStatusChanged
  36949. */
  36950. bool isActiveWindow() const throw() { return windowIsActive_; }
  36951. /** This will set the bounds of the window so that it's centred in front of another
  36952. window.
  36953. If your app has a few windows open and want to pop up a dialog box for one of
  36954. them, you can use this to show it in front of the relevent parent window, which
  36955. is a bit neater than just having it appear in the middle of the screen.
  36956. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  36957. be used instead. If no window is focused, it'll just default to the middle of the
  36958. screen.
  36959. */
  36960. void centreAroundComponent (Component* componentToCentreAround,
  36961. int width, int height);
  36962. /** Turns the drop-shadow on and off. */
  36963. void setDropShadowEnabled (bool useShadow);
  36964. /** Sets whether an OS-native title bar will be used, or a Juce one.
  36965. @see isUsingNativeTitleBar
  36966. */
  36967. void setUsingNativeTitleBar (bool useNativeTitleBar);
  36968. /** Returns true if the window is currently using an OS-native title bar.
  36969. @see setUsingNativeTitleBar
  36970. */
  36971. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  36972. /** Returns the number of TopLevelWindow objects currently in use.
  36973. @see getTopLevelWindow
  36974. */
  36975. static int getNumTopLevelWindows() throw();
  36976. /** Returns one of the TopLevelWindow objects currently in use.
  36977. The index is 0 to (getNumTopLevelWindows() - 1).
  36978. */
  36979. static TopLevelWindow* getTopLevelWindow (int index) throw();
  36980. /** Returns the currently-active top level window.
  36981. There might not be one, of course, so this can return 0.
  36982. */
  36983. static TopLevelWindow* getActiveTopLevelWindow() throw();
  36984. juce_UseDebuggingNewOperator
  36985. /** @internal */
  36986. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  36987. protected:
  36988. /** This callback happens when this window becomes active or inactive.
  36989. @see isActiveWindow
  36990. */
  36991. virtual void activeWindowStatusChanged();
  36992. /** @internal */
  36993. void focusOfChildComponentChanged (FocusChangeType cause);
  36994. /** @internal */
  36995. void parentHierarchyChanged();
  36996. /** @internal */
  36997. void visibilityChanged();
  36998. /** @internal */
  36999. virtual int getDesktopWindowStyleFlags() const;
  37000. /** @internal */
  37001. void recreateDesktopWindow();
  37002. private:
  37003. friend class TopLevelWindowManager;
  37004. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  37005. ScopedPointer <DropShadower> shadower;
  37006. void setWindowActive (bool isNowActive);
  37007. TopLevelWindow (const TopLevelWindow&);
  37008. TopLevelWindow& operator= (const TopLevelWindow&);
  37009. };
  37010. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37011. /*** End of inlined file: juce_TopLevelWindow.h ***/
  37012. /*** Start of inlined file: juce_ComponentDragger.h ***/
  37013. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37014. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37015. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  37016. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37017. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37018. /**
  37019. A class that imposes restrictions on a Component's size or position.
  37020. This is used by classes such as ResizableCornerComponent,
  37021. ResizableBorderComponent and ResizableWindow.
  37022. The base class can impose some basic size and position limits, but you can
  37023. also subclass this for custom uses.
  37024. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  37025. */
  37026. class JUCE_API ComponentBoundsConstrainer
  37027. {
  37028. public:
  37029. /** When first created, the object will not impose any restrictions on the components. */
  37030. ComponentBoundsConstrainer() throw();
  37031. /** Destructor. */
  37032. virtual ~ComponentBoundsConstrainer();
  37033. /** Imposes a minimum width limit. */
  37034. void setMinimumWidth (int minimumWidth) throw();
  37035. /** Returns the current minimum width. */
  37036. int getMinimumWidth() const throw() { return minW; }
  37037. /** Imposes a maximum width limit. */
  37038. void setMaximumWidth (int maximumWidth) throw();
  37039. /** Returns the current maximum width. */
  37040. int getMaximumWidth() const throw() { return maxW; }
  37041. /** Imposes a minimum height limit. */
  37042. void setMinimumHeight (int minimumHeight) throw();
  37043. /** Returns the current minimum height. */
  37044. int getMinimumHeight() const throw() { return minH; }
  37045. /** Imposes a maximum height limit. */
  37046. void setMaximumHeight (int maximumHeight) throw();
  37047. /** Returns the current maximum height. */
  37048. int getMaximumHeight() const throw() { return maxH; }
  37049. /** Imposes a minimum width and height limit. */
  37050. void setMinimumSize (int minimumWidth,
  37051. int minimumHeight) throw();
  37052. /** Imposes a maximum width and height limit. */
  37053. void setMaximumSize (int maximumWidth,
  37054. int maximumHeight) throw();
  37055. /** Set all the maximum and minimum dimensions. */
  37056. void setSizeLimits (int minimumWidth,
  37057. int minimumHeight,
  37058. int maximumWidth,
  37059. int maximumHeight) throw();
  37060. /** Sets the amount by which the component is allowed to go off-screen.
  37061. The values indicate how many pixels must remain on-screen when dragged off
  37062. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  37063. when the component goes off the top of the screen, its y-position will be
  37064. clipped so that there are always at least 10 pixels on-screen. In other words,
  37065. the lowest y-position it can take would be (10 - the component's height).
  37066. If you pass 0 or less for one of these amounts, the component is allowed
  37067. to move beyond that edge completely, with no restrictions at all.
  37068. If you pass a very large number (i.e. larger that the dimensions of the
  37069. component itself), then the component won't be allowed to overlap that
  37070. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  37071. the component will bump into the left side of the screen and go no further.
  37072. */
  37073. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  37074. int minimumWhenOffTheLeft,
  37075. int minimumWhenOffTheBottom,
  37076. int minimumWhenOffTheRight) throw();
  37077. /** Specifies a width-to-height ratio that the resizer should always maintain.
  37078. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  37079. will always be maintained as this multiple of the height.
  37080. @see setResizeLimits
  37081. */
  37082. void setFixedAspectRatio (double widthOverHeight) throw();
  37083. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  37084. If no aspect ratio is being enforced, this will return 0.
  37085. */
  37086. double getFixedAspectRatio() const throw();
  37087. /** This callback changes the given co-ordinates to impose whatever the current
  37088. constraints are set to be.
  37089. @param bounds the target position that should be examined and adjusted
  37090. @param previousBounds the component's current size
  37091. @param limits the region in which the component can be positioned
  37092. @param isStretchingTop whether the top edge of the component is being resized
  37093. @param isStretchingLeft whether the left edge of the component is being resized
  37094. @param isStretchingBottom whether the bottom edge of the component is being resized
  37095. @param isStretchingRight whether the right edge of the component is being resized
  37096. */
  37097. virtual void checkBounds (Rectangle<int>& bounds,
  37098. const Rectangle<int>& previousBounds,
  37099. const Rectangle<int>& limits,
  37100. bool isStretchingTop,
  37101. bool isStretchingLeft,
  37102. bool isStretchingBottom,
  37103. bool isStretchingRight);
  37104. /** This callback happens when the resizer is about to start dragging. */
  37105. virtual void resizeStart();
  37106. /** This callback happens when the resizer has finished dragging. */
  37107. virtual void resizeEnd();
  37108. /** Checks the given bounds, and then sets the component to the corrected size. */
  37109. void setBoundsForComponent (Component* const component,
  37110. const Rectangle<int>& bounds,
  37111. bool isStretchingTop,
  37112. bool isStretchingLeft,
  37113. bool isStretchingBottom,
  37114. bool isStretchingRight);
  37115. /** Performs a check on the current size of a component, and moves or resizes
  37116. it if it fails the constraints.
  37117. */
  37118. void checkComponentBounds (Component* component);
  37119. /** Called by setBoundsForComponent() to apply a new constrained size to a
  37120. component.
  37121. By default this just calls setBounds(), but it virtual in case it's needed for
  37122. extremely cunning purposes.
  37123. */
  37124. virtual void applyBoundsToComponent (Component* component,
  37125. const Rectangle<int>& bounds);
  37126. juce_UseDebuggingNewOperator
  37127. private:
  37128. int minW, maxW, minH, maxH;
  37129. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  37130. double aspectRatio;
  37131. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  37132. ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  37133. };
  37134. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37135. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  37136. /**
  37137. An object to take care of the logic for dragging components around with the mouse.
  37138. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  37139. then in your mouseDrag() callback, call dragComponent().
  37140. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  37141. to limit the component's position and keep it on-screen.
  37142. e.g. @code
  37143. class MyDraggableComp
  37144. {
  37145. ComponentDragger myDragger;
  37146. void mouseDown (const MouseEvent& e)
  37147. {
  37148. myDragger.startDraggingComponent (this, 0);
  37149. }
  37150. void mouseDrag (const MouseEvent& e)
  37151. {
  37152. myDragger.dragComponent (this, e);
  37153. }
  37154. };
  37155. @endcode
  37156. */
  37157. class JUCE_API ComponentDragger
  37158. {
  37159. public:
  37160. /** Creates a ComponentDragger. */
  37161. ComponentDragger();
  37162. /** Destructor. */
  37163. virtual ~ComponentDragger();
  37164. /** Call this from your component's mouseDown() method, to prepare for dragging.
  37165. @param componentToDrag the component that you want to drag
  37166. @param constrainer a constrainer object to use to keep the component
  37167. from going offscreen
  37168. @see dragComponent
  37169. */
  37170. void startDraggingComponent (Component* const componentToDrag,
  37171. ComponentBoundsConstrainer* constrainer);
  37172. /** Call this from your mouseDrag() callback to move the component.
  37173. This will move the component, but will first check the validity of the
  37174. component's new position using the checkPosition() method, which you
  37175. can override if you need to enforce special positioning limits on the
  37176. component.
  37177. @param componentToDrag the component that you want to drag
  37178. @param e the current mouse-drag event
  37179. @see dragComponent
  37180. */
  37181. void dragComponent (Component* const componentToDrag,
  37182. const MouseEvent& e);
  37183. juce_UseDebuggingNewOperator
  37184. private:
  37185. ComponentBoundsConstrainer* constrainer;
  37186. Point<int> originalPos;
  37187. ComponentDragger (const ComponentDragger&);
  37188. ComponentDragger& operator= (const ComponentDragger&);
  37189. };
  37190. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37191. /*** End of inlined file: juce_ComponentDragger.h ***/
  37192. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  37193. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37194. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37195. /**
  37196. A component that resizes its parent window when dragged.
  37197. This component forms a frame around the edge of a component, allowing it to
  37198. be dragged by the edges or corners to resize it - like the way windows are
  37199. resized in MSWindows or Linux.
  37200. To use it, just add it to your component, making it fill the entire parent component
  37201. (there's a mouse hit-test that only traps mouse-events which land around the
  37202. edge of the component, so it's even ok to put it on top of any other components
  37203. you're using). Make sure you rescale the resizer component to fill the parent
  37204. each time the parent's size changes.
  37205. @see ResizableCornerComponent
  37206. */
  37207. class JUCE_API ResizableBorderComponent : public Component
  37208. {
  37209. public:
  37210. /** Creates a resizer.
  37211. Pass in the target component which you want to be resized when this one is
  37212. dragged.
  37213. The target component will usually be a parent of the resizer component, but this
  37214. isn't mandatory.
  37215. Remember that when the target component is resized, it'll need to move and
  37216. resize this component to keep it in place, as this won't happen automatically.
  37217. If the constrainer parameter is non-zero, then this object will be used to enforce
  37218. limits on the size and position that the component can be stretched to. Make sure
  37219. that the constrainer isn't deleted while still in use by this object.
  37220. @see ComponentBoundsConstrainer
  37221. */
  37222. ResizableBorderComponent (Component* componentToResize,
  37223. ComponentBoundsConstrainer* constrainer);
  37224. /** Destructor. */
  37225. ~ResizableBorderComponent();
  37226. /** Specifies how many pixels wide the draggable edges of this component are.
  37227. @see getBorderThickness
  37228. */
  37229. void setBorderThickness (const BorderSize& newBorderSize);
  37230. /** Returns the number of pixels wide that the draggable edges of this component are.
  37231. @see setBorderThickness
  37232. */
  37233. const BorderSize getBorderThickness() const;
  37234. /** Represents the different sections of a resizable border, which allow it to
  37235. resized in different ways.
  37236. */
  37237. class Zone
  37238. {
  37239. public:
  37240. enum Zones
  37241. {
  37242. centre = 0,
  37243. left = 1,
  37244. top = 2,
  37245. right = 4,
  37246. bottom = 8
  37247. };
  37248. /** Creates a Zone from a combination of the flags in \enum Zones. */
  37249. explicit Zone (int zoneFlags = 0) throw();
  37250. Zone (const Zone& other) throw();
  37251. Zone& operator= (const Zone& other) throw();
  37252. bool operator== (const Zone& other) const throw();
  37253. bool operator!= (const Zone& other) const throw();
  37254. /** Given a point within a rectangle with a resizable border, this returns the
  37255. zone that the point lies within.
  37256. */
  37257. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  37258. const BorderSize& border,
  37259. const Point<int>& position);
  37260. /** Returns an appropriate mouse-cursor for this resize zone. */
  37261. const MouseCursor getMouseCursor() const throw();
  37262. /** Returns true if dragging this zone will move the enire object without resizing it. */
  37263. bool isDraggingWholeObject() const throw() { return zone == centre; }
  37264. /** Returns true if dragging this zone will move the object's left edge. */
  37265. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  37266. /** Returns true if dragging this zone will move the object's right edge. */
  37267. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  37268. /** Returns true if dragging this zone will move the object's top edge. */
  37269. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  37270. /** Returns true if dragging this zone will move the object's bottom edge. */
  37271. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  37272. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  37273. applies to.
  37274. */
  37275. const Rectangle<int> resizeRectangleBy (Rectangle<int> original,
  37276. const Point<int>& distance) const throw();
  37277. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  37278. applies to.
  37279. */
  37280. const Rectangle<float> resizeRectangleBy (Rectangle<float> original,
  37281. const Point<float>& distance) const throw();
  37282. /** Returns the raw flags for this zone. */
  37283. int getZoneFlags() const throw() { return zone; }
  37284. private:
  37285. int zone;
  37286. };
  37287. juce_UseDebuggingNewOperator
  37288. protected:
  37289. /** @internal */
  37290. void paint (Graphics& g);
  37291. /** @internal */
  37292. void mouseEnter (const MouseEvent& e);
  37293. /** @internal */
  37294. void mouseMove (const MouseEvent& e);
  37295. /** @internal */
  37296. void mouseDown (const MouseEvent& e);
  37297. /** @internal */
  37298. void mouseDrag (const MouseEvent& e);
  37299. /** @internal */
  37300. void mouseUp (const MouseEvent& e);
  37301. /** @internal */
  37302. bool hitTest (int x, int y);
  37303. private:
  37304. Component::SafePointer<Component> component;
  37305. ComponentBoundsConstrainer* constrainer;
  37306. BorderSize borderSize;
  37307. Rectangle<int> originalBounds;
  37308. Zone mouseZone;
  37309. void updateMouseZone (const MouseEvent& e);
  37310. ResizableBorderComponent (const ResizableBorderComponent&);
  37311. ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  37312. };
  37313. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37314. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  37315. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  37316. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37317. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37318. /** A component that resizes a parent window when dragged.
  37319. This is the small triangular stripey resizer component you get in the bottom-right
  37320. of windows (more commonly on the Mac than Windows). Put one in the corner of
  37321. a larger component and it will automatically resize its parent when it gets dragged
  37322. around.
  37323. @see ResizableFrameComponent
  37324. */
  37325. class JUCE_API ResizableCornerComponent : public Component
  37326. {
  37327. public:
  37328. /** Creates a resizer.
  37329. Pass in the target component which you want to be resized when this one is
  37330. dragged.
  37331. The target component will usually be a parent of the resizer component, but this
  37332. isn't mandatory.
  37333. Remember that when the target component is resized, it'll need to move and
  37334. resize this component to keep it in place, as this won't happen automatically.
  37335. If the constrainer parameter is non-zero, then this object will be used to enforce
  37336. limits on the size and position that the component can be stretched to. Make sure
  37337. that the constrainer isn't deleted while still in use by this object. If you
  37338. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  37339. @see ComponentBoundsConstrainer
  37340. */
  37341. ResizableCornerComponent (Component* componentToResize,
  37342. ComponentBoundsConstrainer* constrainer);
  37343. /** Destructor. */
  37344. ~ResizableCornerComponent();
  37345. juce_UseDebuggingNewOperator
  37346. protected:
  37347. /** @internal */
  37348. void paint (Graphics& g);
  37349. /** @internal */
  37350. void mouseDown (const MouseEvent& e);
  37351. /** @internal */
  37352. void mouseDrag (const MouseEvent& e);
  37353. /** @internal */
  37354. void mouseUp (const MouseEvent& e);
  37355. /** @internal */
  37356. bool hitTest (int x, int y);
  37357. private:
  37358. Component::SafePointer<Component> component;
  37359. ComponentBoundsConstrainer* constrainer;
  37360. Rectangle<int> originalBounds;
  37361. ResizableCornerComponent (const ResizableCornerComponent&);
  37362. ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  37363. };
  37364. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37365. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  37366. /**
  37367. A base class for top-level windows that can be dragged around and resized.
  37368. To add content to the window, use its setContentComponent() method to
  37369. give it a component that will remain positioned inside it (leaving a gap around
  37370. the edges for a border).
  37371. It's not advisable to add child components directly to a ResizableWindow: put them
  37372. inside your content component instead. And overriding methods like resized(), moved(), etc
  37373. is also not recommended - instead override these methods for your content component.
  37374. (If for some obscure reason you do need to override these methods, always remember to
  37375. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37376. decorations correctly).
  37377. By default resizing isn't enabled - use the setResizable() method to enable it and
  37378. to choose the style of resizing to use.
  37379. @see TopLevelWindow
  37380. */
  37381. class JUCE_API ResizableWindow : public TopLevelWindow
  37382. {
  37383. public:
  37384. /** Creates a ResizableWindow.
  37385. This constructor doesn't specify a background colour, so the LookAndFeel's default
  37386. background colour will be used.
  37387. @param name the name to give the component
  37388. @param addToDesktop if true, the window will be automatically added to the
  37389. desktop; if false, you can use it as a child component
  37390. */
  37391. ResizableWindow (const String& name,
  37392. bool addToDesktop);
  37393. /** Creates a ResizableWindow.
  37394. @param name the name to give the component
  37395. @param backgroundColour the colour to use for filling the window's background.
  37396. @param addToDesktop if true, the window will be automatically added to the
  37397. desktop; if false, you can use it as a child component
  37398. */
  37399. ResizableWindow (const String& name,
  37400. const Colour& backgroundColour,
  37401. bool addToDesktop);
  37402. /** Destructor.
  37403. If a content component has been set with setContentComponent(), it
  37404. will be deleted.
  37405. */
  37406. ~ResizableWindow();
  37407. /** Returns the colour currently being used for the window's background.
  37408. As a convenience the window will fill itself with this colour, but you
  37409. can override the paint() method if you need more customised behaviour.
  37410. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  37411. @see setBackgroundColour
  37412. */
  37413. const Colour getBackgroundColour() const throw();
  37414. /** Changes the colour currently being used for the window's background.
  37415. As a convenience the window will fill itself with this colour, but you
  37416. can override the paint() method if you need more customised behaviour.
  37417. Note that the opaque state of this window is altered by this call to reflect
  37418. the opacity of the colour passed-in. On window systems which can't support
  37419. semi-transparent windows this might cause problems, (though it's unlikely you'll
  37420. be using this class as a base for a semi-transparent component anyway).
  37421. You can also use the ResizableWindow::backgroundColourId colour id to set
  37422. this colour.
  37423. @see getBackgroundColour
  37424. */
  37425. void setBackgroundColour (const Colour& newColour);
  37426. /** Make the window resizable or fixed.
  37427. @param shouldBeResizable whether it's resizable at all
  37428. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  37429. bottom-right; if false, it'll use a ResizableBorderComponent
  37430. around the edge
  37431. @see setResizeLimits, isResizable
  37432. */
  37433. void setResizable (bool shouldBeResizable,
  37434. bool useBottomRightCornerResizer);
  37435. /** True if resizing is enabled.
  37436. @see setResizable
  37437. */
  37438. bool isResizable() const throw();
  37439. /** This sets the maximum and minimum sizes for the window.
  37440. If the window's current size is outside these limits, it will be resized to
  37441. make sure it's within them.
  37442. Calling setBounds() on the component will bypass any size checking - it's only when
  37443. the window is being resized by the user that these values are enforced.
  37444. @see setResizable, setFixedAspectRatio
  37445. */
  37446. void setResizeLimits (int newMinimumWidth,
  37447. int newMinimumHeight,
  37448. int newMaximumWidth,
  37449. int newMaximumHeight) throw();
  37450. /** Returns the bounds constrainer object that this window is using.
  37451. You can access this to change its properties.
  37452. */
  37453. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  37454. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  37455. A pointer to the object you pass in will be kept, but it won't be deleted
  37456. by this object, so it's the caller's responsiblity to manage it.
  37457. If you pass 0, then no contraints will be placed on the positioning of the window.
  37458. */
  37459. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  37460. /** Calls the window's setBounds method, after first checking these bounds
  37461. with the current constrainer.
  37462. @see setConstrainer
  37463. */
  37464. void setBoundsConstrained (const Rectangle<int>& bounds);
  37465. /** Returns true if the window is currently in full-screen mode.
  37466. @see setFullScreen
  37467. */
  37468. bool isFullScreen() const;
  37469. /** Puts the window into full-screen mode, or restores it to its normal size.
  37470. If true, the window will become full-screen; if false, it will return to the
  37471. last size it was before being made full-screen.
  37472. @see isFullScreen
  37473. */
  37474. void setFullScreen (bool shouldBeFullScreen);
  37475. /** Returns true if the window is currently minimised.
  37476. @see setMinimised
  37477. */
  37478. bool isMinimised() const;
  37479. /** Minimises the window, or restores it to its previous position and size.
  37480. When being un-minimised, it'll return to the last position and size it
  37481. was in before being minimised.
  37482. @see isMinimised
  37483. */
  37484. void setMinimised (bool shouldMinimise);
  37485. /** Returns a string which encodes the window's current size and position.
  37486. This string will encapsulate the window's size, position, and whether it's
  37487. in full-screen mode. It's intended for letting your application save and
  37488. restore a window's position.
  37489. Use the restoreWindowStateFromString() to restore from a saved state.
  37490. @see restoreWindowStateFromString
  37491. */
  37492. const String getWindowStateAsString();
  37493. /** Restores the window to a previously-saved size and position.
  37494. This restores the window's size, positon and full-screen status from an
  37495. string that was previously created with the getWindowStateAsString()
  37496. method.
  37497. @returns false if the string wasn't a valid window state
  37498. @see getWindowStateAsString
  37499. */
  37500. bool restoreWindowStateFromString (const String& previousState);
  37501. /** Returns the current content component.
  37502. This will be the component set by setContentComponent(), or 0 if none
  37503. has yet been specified.
  37504. @see setContentComponent
  37505. */
  37506. Component* getContentComponent() const throw() { return contentComponent; }
  37507. /** Changes the current content component.
  37508. This sets a component that will be placed in the centre of the ResizableWindow,
  37509. (leaving a space around the edge for the border).
  37510. You should never add components directly to a ResizableWindow (or any of its subclasses)
  37511. with addChildComponent(). Instead, add them to the content component.
  37512. @param newContentComponent the new component to use (or null to not use one) - this
  37513. component will be deleted either when replaced by another call
  37514. to this method, or when the ResizableWindow is deleted.
  37515. To remove a content component without deleting it, use
  37516. setContentComponent (0, false).
  37517. @param deleteOldOne if true, the previous content component will be deleted; if
  37518. false, the previous component will just be removed without
  37519. deleting it.
  37520. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  37521. it always fits around the size of the content component. If false, the
  37522. new content will be resized to fit the current space available.
  37523. */
  37524. void setContentComponent (Component* newContentComponent,
  37525. bool deleteOldOne = true,
  37526. bool resizeToFit = false);
  37527. /** Changes the window so that the content component ends up with the specified size.
  37528. This is basically a setSize call on the window, but which adds on the borders,
  37529. so you can specify the content component's target size.
  37530. */
  37531. void setContentComponentSize (int width, int height);
  37532. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37533. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37534. methods.
  37535. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37536. */
  37537. enum ColourIds
  37538. {
  37539. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  37540. };
  37541. juce_UseDebuggingNewOperator
  37542. protected:
  37543. /** @internal */
  37544. void paint (Graphics& g);
  37545. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37546. void moved();
  37547. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37548. void resized();
  37549. /** @internal */
  37550. void mouseDown (const MouseEvent& e);
  37551. /** @internal */
  37552. void mouseDrag (const MouseEvent& e);
  37553. /** @internal */
  37554. void lookAndFeelChanged();
  37555. /** @internal */
  37556. void childBoundsChanged (Component* child);
  37557. /** @internal */
  37558. void parentSizeChanged();
  37559. /** @internal */
  37560. void visibilityChanged();
  37561. /** @internal */
  37562. void activeWindowStatusChanged();
  37563. /** @internal */
  37564. int getDesktopWindowStyleFlags() const;
  37565. /** Returns the width of the border to use around the window.
  37566. @see getContentComponentBorder
  37567. */
  37568. virtual const BorderSize getBorderThickness();
  37569. /** Returns the insets to use when positioning the content component.
  37570. @see getBorderThickness
  37571. */
  37572. virtual const BorderSize getContentComponentBorder();
  37573. #if JUCE_DEBUG
  37574. /** Overridden to warn people about adding components directly to this component
  37575. instead of using setContentComponent().
  37576. If you know what you're doing and are sure you really want to add a component, specify
  37577. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37578. */
  37579. void addChildComponent (Component* child, int zOrder = -1);
  37580. /** Overridden to warn people about adding components directly to this component
  37581. instead of using setContentComponent().
  37582. If you know what you're doing and are sure you really want to add a component, specify
  37583. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37584. */
  37585. void addAndMakeVisible (Component* child, int zOrder = -1);
  37586. #endif
  37587. ScopedPointer <ResizableCornerComponent> resizableCorner;
  37588. ScopedPointer <ResizableBorderComponent> resizableBorder;
  37589. private:
  37590. Component::SafePointer <Component> contentComponent;
  37591. bool resizeToFitContent, fullscreen;
  37592. ComponentDragger dragger;
  37593. Rectangle<int> lastNonFullScreenPos;
  37594. ComponentBoundsConstrainer defaultConstrainer;
  37595. ComponentBoundsConstrainer* constrainer;
  37596. #if JUCE_DEBUG
  37597. bool hasBeenResized;
  37598. #endif
  37599. void updateLastPos();
  37600. ResizableWindow (const ResizableWindow&);
  37601. ResizableWindow& operator= (const ResizableWindow&);
  37602. // (xxx remove these eventually)
  37603. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37604. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  37605. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37606. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  37607. };
  37608. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37609. /*** End of inlined file: juce_ResizableWindow.h ***/
  37610. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  37611. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37612. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37613. /**
  37614. A glyph from a particular font, with a particular size, style,
  37615. typeface and position.
  37616. @see GlyphArrangement, Font
  37617. */
  37618. class JUCE_API PositionedGlyph
  37619. {
  37620. public:
  37621. PositionedGlyph (const PositionedGlyph& other);
  37622. /** Returns the character the glyph represents. */
  37623. juce_wchar getCharacter() const { return character; }
  37624. /** Checks whether the glyph is actually empty. */
  37625. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  37626. /** Returns the position of the glyph's left-hand edge. */
  37627. float getLeft() const { return x; }
  37628. /** Returns the position of the glyph's right-hand edge. */
  37629. float getRight() const { return x + w; }
  37630. /** Returns the y position of the glyph's baseline. */
  37631. float getBaselineY() const { return y; }
  37632. /** Returns the y position of the top of the glyph. */
  37633. float getTop() const { return y - font.getAscent(); }
  37634. /** Returns the y position of the bottom of the glyph. */
  37635. float getBottom() const { return y + font.getDescent(); }
  37636. /** Returns the bounds of the glyph. */
  37637. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  37638. /** Shifts the glyph's position by a relative amount. */
  37639. void moveBy (float deltaX, float deltaY);
  37640. /** Draws the glyph into a graphics context. */
  37641. void draw (const Graphics& g) const;
  37642. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  37643. void draw (const Graphics& g, const AffineTransform& transform) const;
  37644. /** Returns the path for this glyph.
  37645. @param path the glyph's outline will be appended to this path
  37646. */
  37647. void createPath (Path& path) const;
  37648. /** Checks to see if a point lies within this glyph. */
  37649. bool hitTest (float x, float y) const;
  37650. juce_UseDebuggingNewOperator
  37651. private:
  37652. friend class GlyphArrangement;
  37653. float x, y, w;
  37654. Font font;
  37655. juce_wchar character;
  37656. int glyph;
  37657. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  37658. };
  37659. /**
  37660. A set of glyphs, each with a position.
  37661. You can create a GlyphArrangement, text to it and then draw it onto a
  37662. graphics context. It's used internally by the text methods in the
  37663. Graphics class, but can be used directly if more control is needed.
  37664. @see Font, PositionedGlyph
  37665. */
  37666. class JUCE_API GlyphArrangement
  37667. {
  37668. public:
  37669. /** Creates an empty arrangement. */
  37670. GlyphArrangement();
  37671. /** Takes a copy of another arrangement. */
  37672. GlyphArrangement (const GlyphArrangement& other);
  37673. /** Copies another arrangement onto this one.
  37674. To add another arrangement without clearing this one, use addGlyphArrangement().
  37675. */
  37676. GlyphArrangement& operator= (const GlyphArrangement& other);
  37677. /** Destructor. */
  37678. ~GlyphArrangement();
  37679. /** Returns the total number of glyphs in the arrangement. */
  37680. int getNumGlyphs() const throw() { return glyphs.size(); }
  37681. /** Returns one of the glyphs from the arrangement.
  37682. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  37683. careful not to pass an out-of-range index here, as it
  37684. doesn't do any bounds-checking.
  37685. */
  37686. PositionedGlyph& getGlyph (int index) const;
  37687. /** Clears all text from the arrangement and resets it.
  37688. */
  37689. void clear();
  37690. /** Appends a line of text to the arrangement.
  37691. This will add the text as a single line, where x is the left-hand edge of the
  37692. first character, and y is the position for the text's baseline.
  37693. If the text contains new-lines or carriage-returns, this will ignore them - use
  37694. addJustifiedText() to add multi-line arrangements.
  37695. */
  37696. void addLineOfText (const Font& font,
  37697. const String& text,
  37698. float x, float y);
  37699. /** Adds a line of text, truncating it if it's wider than a specified size.
  37700. This is the same as addLineOfText(), but if the line's width exceeds the value
  37701. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  37702. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  37703. */
  37704. void addCurtailedLineOfText (const Font& font,
  37705. const String& text,
  37706. float x, float y,
  37707. float maxWidthPixels,
  37708. bool useEllipsis);
  37709. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  37710. This will add text to the arrangement, breaking it into new lines either where there
  37711. is a new-line or carriage-return character in the text, or where a line's width
  37712. exceeds the value set in maxLineWidth.
  37713. Each line that is added will be laid out using the flags set in horizontalLayout, so
  37714. the lines can be left- or right-justified, or centred horizontally in the space
  37715. between x and (x + maxLineWidth).
  37716. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  37717. lines will be placed below it, separated by a distance of font.getHeight().
  37718. */
  37719. void addJustifiedText (const Font& font,
  37720. const String& text,
  37721. float x, float y,
  37722. float maxLineWidth,
  37723. const Justification& horizontalLayout);
  37724. /** Tries to fit some text withing a given space.
  37725. This does its best to make the given text readable within the specified rectangle,
  37726. so it useful for labelling things.
  37727. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  37728. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  37729. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  37730. it's been truncated.
  37731. A Justification parameter lets you specify how the text is laid out within the rectangle,
  37732. both horizontally and vertically.
  37733. @see Graphics::drawFittedText
  37734. */
  37735. void addFittedText (const Font& font,
  37736. const String& text,
  37737. float x, float y, float width, float height,
  37738. const Justification& layout,
  37739. int maximumLinesToUse,
  37740. float minimumHorizontalScale = 0.7f);
  37741. /** Appends another glyph arrangement to this one. */
  37742. void addGlyphArrangement (const GlyphArrangement& other);
  37743. /** Draws this glyph arrangement to a graphics context.
  37744. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  37745. method, which renders the glyphs as filled vectors.
  37746. */
  37747. void draw (const Graphics& g) const;
  37748. /** Draws this glyph arrangement to a graphics context.
  37749. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  37750. method for non-transformed arrangements.
  37751. */
  37752. void draw (const Graphics& g, const AffineTransform& transform) const;
  37753. /** Converts the set of glyphs into a path.
  37754. @param path the glyphs' outlines will be appended to this path
  37755. */
  37756. void createPath (Path& path) const;
  37757. /** Looks for a glyph that contains the given co-ordinate.
  37758. @returns the index of the glyph, or -1 if none were found.
  37759. */
  37760. int findGlyphIndexAt (float x, float y) const;
  37761. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  37762. @param startIndex the first glyph to test
  37763. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  37764. startIndex will be included
  37765. @param includeWhitespace if true, the extent of any whitespace characters will also
  37766. be taken into account
  37767. */
  37768. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  37769. /** Shifts a set of glyphs by a given amount.
  37770. @param startIndex the first glyph to transform
  37771. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  37772. startIndex will be used
  37773. @param deltaX the amount to add to their x-positions
  37774. @param deltaY the amount to add to their y-positions
  37775. */
  37776. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  37777. float deltaX, float deltaY);
  37778. /** Removes a set of glyphs from the arrangement.
  37779. @param startIndex the first glyph to remove
  37780. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  37781. startIndex will be deleted
  37782. */
  37783. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  37784. /** Expands or compresses a set of glyphs horizontally.
  37785. @param startIndex the first glyph to transform
  37786. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  37787. startIndex will be used
  37788. @param horizontalScaleFactor how much to scale their horizontal width by
  37789. */
  37790. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  37791. float horizontalScaleFactor);
  37792. /** Justifies a set of glyphs within a given space.
  37793. This moves the glyphs as a block so that the whole thing is located within the
  37794. given rectangle with the specified layout.
  37795. If the Justification::horizontallyJustified flag is specified, each line will
  37796. be stretched out to fill the specified width.
  37797. */
  37798. void justifyGlyphs (int startIndex, int numGlyphs,
  37799. float x, float y, float width, float height,
  37800. const Justification& justification);
  37801. juce_UseDebuggingNewOperator
  37802. private:
  37803. OwnedArray <PositionedGlyph> glyphs;
  37804. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  37805. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  37806. const Justification& justification, float minimumHorizontalScale);
  37807. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  37808. };
  37809. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37810. /*** End of inlined file: juce_GlyphArrangement.h ***/
  37811. /**
  37812. A file open/save dialog box.
  37813. This is a Juce-based file dialog box; to use a native file chooser, see the
  37814. FileChooser class.
  37815. To use one of these, create it and call its show() method. e.g.
  37816. @code
  37817. {
  37818. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  37819. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37820. File::nonexistent,
  37821. &wildcardFilter,
  37822. 0);
  37823. FileChooserDialogBox dialogBox ("Open some kind of file",
  37824. "Please choose some kind of file that you want to open...",
  37825. browser,
  37826. getLookAndFeel().alertWindowBackground);
  37827. if (dialogBox.show())
  37828. {
  37829. File selectedFile = browser.getCurrentFile();
  37830. ...
  37831. }
  37832. }
  37833. @endcode
  37834. @see FileChooser
  37835. */
  37836. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37837. public ButtonListener,
  37838. public FileBrowserListener
  37839. {
  37840. public:
  37841. /** Creates a file chooser box.
  37842. @param title the main title to show at the top of the box
  37843. @param instructions an optional longer piece of text to show below the title in
  37844. a smaller font, describing in more detail what's required.
  37845. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37846. box. Make sure you delete this after (but not before!) the
  37847. dialog box has been deleted.
  37848. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37849. if they try to select a file that already exists. (This
  37850. flag is only used when saving files)
  37851. @param backgroundColour the background colour for the top level window
  37852. @see FileBrowserComponent, FilePreviewComponent
  37853. */
  37854. FileChooserDialogBox (const String& title,
  37855. const String& instructions,
  37856. FileBrowserComponent& browserComponent,
  37857. bool warnAboutOverwritingExistingFiles,
  37858. const Colour& backgroundColour);
  37859. /** Destructor. */
  37860. ~FileChooserDialogBox();
  37861. /** Displays and runs the dialog box modally.
  37862. This will show the box with the specified size, returning true if the user
  37863. pressed 'ok', or false if they cancelled.
  37864. Leave the width or height as 0 to use the default size
  37865. */
  37866. bool show (int width = 0, int height = 0);
  37867. /** Displays and runs the dialog box modally.
  37868. This will show the box with the specified size at the specified location,
  37869. returning true if the user pressed 'ok', or false if they cancelled.
  37870. Leave the width or height as 0 to use the default size.
  37871. */
  37872. bool showAt (int x, int y, int width, int height);
  37873. /** A set of colour IDs to use to change the colour of various aspects of the box.
  37874. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37875. methods.
  37876. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37877. */
  37878. enum ColourIds
  37879. {
  37880. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  37881. };
  37882. /** @internal */
  37883. void buttonClicked (Button* button);
  37884. /** @internal */
  37885. void closeButtonPressed();
  37886. /** @internal */
  37887. void selectionChanged();
  37888. /** @internal */
  37889. void fileClicked (const File& file, const MouseEvent& e);
  37890. /** @internal */
  37891. void fileDoubleClicked (const File& file);
  37892. juce_UseDebuggingNewOperator
  37893. private:
  37894. class ContentComponent : public Component
  37895. {
  37896. public:
  37897. ContentComponent();
  37898. ~ContentComponent();
  37899. void paint (Graphics& g);
  37900. void resized();
  37901. String instructions;
  37902. GlyphArrangement text;
  37903. FileBrowserComponent* chooserComponent;
  37904. FilePreviewComponent* previewComponent;
  37905. TextButton* okButton;
  37906. TextButton* cancelButton;
  37907. };
  37908. ContentComponent* content;
  37909. const bool warnAboutOverwritingExistingFiles;
  37910. FileChooserDialogBox (const FileChooserDialogBox&);
  37911. FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37912. };
  37913. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37914. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  37915. #endif
  37916. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37917. #endif
  37918. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37919. /*** Start of inlined file: juce_FileListComponent.h ***/
  37920. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37921. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37922. /**
  37923. A component that displays the files in a directory as a listbox.
  37924. This implements the DirectoryContentsDisplayComponent base class so that
  37925. it can be used in a FileBrowserComponent.
  37926. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37927. class and the FileBrowserListener class.
  37928. @see DirectoryContentsList, FileTreeComponent
  37929. */
  37930. class JUCE_API FileListComponent : public ListBox,
  37931. public DirectoryContentsDisplayComponent,
  37932. private ListBoxModel,
  37933. private ChangeListener
  37934. {
  37935. public:
  37936. /** Creates a listbox to show the contents of a specified directory.
  37937. */
  37938. FileListComponent (DirectoryContentsList& listToShow);
  37939. /** Destructor. */
  37940. ~FileListComponent();
  37941. /** Returns the number of files the user has got selected.
  37942. @see getSelectedFile
  37943. */
  37944. int getNumSelectedFiles() const;
  37945. /** Returns one of the files that the user has currently selected.
  37946. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  37947. @see getNumSelectedFiles
  37948. */
  37949. const File getSelectedFile (int index = 0) const;
  37950. /** Deselects any files that are currently selected. */
  37951. void deselectAllFiles();
  37952. /** Scrolls to the top of the list. */
  37953. void scrollToTop();
  37954. /** @internal */
  37955. void changeListenerCallback (void*);
  37956. /** @internal */
  37957. int getNumRows();
  37958. /** @internal */
  37959. void paintListBoxItem (int, Graphics&, int, int, bool);
  37960. /** @internal */
  37961. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37962. /** @internal */
  37963. void selectedRowsChanged (int lastRowSelected);
  37964. /** @internal */
  37965. void deleteKeyPressed (int currentSelectedRow);
  37966. /** @internal */
  37967. void returnKeyPressed (int currentSelectedRow);
  37968. juce_UseDebuggingNewOperator
  37969. private:
  37970. FileListComponent (const FileListComponent&);
  37971. FileListComponent& operator= (const FileListComponent&);
  37972. File lastDirectory;
  37973. };
  37974. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37975. /*** End of inlined file: juce_FileListComponent.h ***/
  37976. #endif
  37977. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37978. /*** Start of inlined file: juce_FilenameComponent.h ***/
  37979. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37980. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37981. class FilenameComponent;
  37982. /**
  37983. Listens for events happening to a FilenameComponent.
  37984. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  37985. register one of these objects for event callbacks when the filename is changed.
  37986. @see FilenameComponent
  37987. */
  37988. class JUCE_API FilenameComponentListener
  37989. {
  37990. public:
  37991. /** Destructor. */
  37992. virtual ~FilenameComponentListener() {}
  37993. /** This method is called after the FilenameComponent's file has been changed. */
  37994. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  37995. };
  37996. /**
  37997. Shows a filename as an editable text box, with a 'browse' button and a
  37998. drop-down list for recently selected files.
  37999. A handy component for dialogue boxes where you want the user to be able to
  38000. select a file or directory.
  38001. Attach an FilenameComponentListener using the addListener() method, and it will
  38002. get called each time the user changes the filename, either by browsing for a file
  38003. and clicking 'ok', or by typing a new filename into the box and pressing return.
  38004. @see FileChooser, ComboBox
  38005. */
  38006. class JUCE_API FilenameComponent : public Component,
  38007. public SettableTooltipClient,
  38008. public FileDragAndDropTarget,
  38009. private AsyncUpdater,
  38010. private ButtonListener,
  38011. private ComboBoxListener
  38012. {
  38013. public:
  38014. /** Creates a FilenameComponent.
  38015. @param name the name for this component.
  38016. @param currentFile the file to initially show in the box
  38017. @param canEditFilename if true, the user can manually edit the filename; if false,
  38018. they can only change it by browsing for a new file
  38019. @param isDirectory if true, the file will be treated as a directory, and
  38020. an appropriate directory browser used
  38021. @param isForSaving if true, the file browser will allow non-existent files to
  38022. be picked, as the file is assumed to be used for saving rather
  38023. than loading
  38024. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  38025. If an empty string is passed in, then the pattern is assumed to be "*"
  38026. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  38027. to any filenames that are entered or chosen
  38028. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  38029. will only appear if the initial file isn't valid)
  38030. */
  38031. FilenameComponent (const String& name,
  38032. const File& currentFile,
  38033. bool canEditFilename,
  38034. bool isDirectory,
  38035. bool isForSaving,
  38036. const String& fileBrowserWildcard,
  38037. const String& enforcedSuffix,
  38038. const String& textWhenNothingSelected);
  38039. /** Destructor. */
  38040. ~FilenameComponent();
  38041. /** Returns the currently displayed filename. */
  38042. const File getCurrentFile() const;
  38043. /** Changes the current filename.
  38044. If addToRecentlyUsedList is true, the filename will also be added to the
  38045. drop-down list of recent files.
  38046. If sendChangeNotification is false, then the listeners won't be told of the
  38047. change.
  38048. */
  38049. void setCurrentFile (File newFile,
  38050. bool addToRecentlyUsedList,
  38051. bool sendChangeNotification = true);
  38052. /** Changes whether the use can type into the filename box.
  38053. */
  38054. void setFilenameIsEditable (bool shouldBeEditable);
  38055. /** Sets a file or directory to be the default starting point for the browser to show.
  38056. This is only used if the current file hasn't been set.
  38057. */
  38058. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  38059. /** Returns all the entries on the recent files list.
  38060. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  38061. state of this list.
  38062. @see setRecentlyUsedFilenames
  38063. */
  38064. const StringArray getRecentlyUsedFilenames() const;
  38065. /** Sets all the entries on the recent files list.
  38066. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  38067. state of this list.
  38068. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  38069. */
  38070. void setRecentlyUsedFilenames (const StringArray& filenames);
  38071. /** Adds an entry to the recently-used files dropdown list.
  38072. If the file is already in the list, it will be moved to the top. A limit
  38073. is also placed on the number of items that are kept in the list.
  38074. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  38075. */
  38076. void addRecentlyUsedFile (const File& file);
  38077. /** Changes the limit for the number of files that will be stored in the recent-file list.
  38078. */
  38079. void setMaxNumberOfRecentFiles (int newMaximum);
  38080. /** Changes the text shown on the 'browse' button.
  38081. By default this button just says "..." but you can change it. The button itself
  38082. can be changed using the look-and-feel classes, so it might not actually have any
  38083. text on it.
  38084. */
  38085. void setBrowseButtonText (const String& browseButtonText);
  38086. /** Adds a listener that will be called when the selected file is changed. */
  38087. void addListener (FilenameComponentListener* listener);
  38088. /** Removes a previously-registered listener. */
  38089. void removeListener (FilenameComponentListener* listener);
  38090. /** Gives the component a tooltip. */
  38091. void setTooltip (const String& newTooltip);
  38092. /** @internal */
  38093. void paintOverChildren (Graphics& g);
  38094. /** @internal */
  38095. void resized();
  38096. /** @internal */
  38097. void lookAndFeelChanged();
  38098. /** @internal */
  38099. bool isInterestedInFileDrag (const StringArray& files);
  38100. /** @internal */
  38101. void filesDropped (const StringArray& files, int, int);
  38102. /** @internal */
  38103. void fileDragEnter (const StringArray& files, int, int);
  38104. /** @internal */
  38105. void fileDragExit (const StringArray& files);
  38106. juce_UseDebuggingNewOperator
  38107. private:
  38108. ComboBox filenameBox;
  38109. String lastFilename;
  38110. ScopedPointer<Button> browseButton;
  38111. int maxRecentFiles;
  38112. bool isDir, isSaving, isFileDragOver;
  38113. String wildcard, enforcedSuffix, browseButtonText;
  38114. ListenerList <FilenameComponentListener> listeners;
  38115. File defaultBrowseFile;
  38116. void comboBoxChanged (ComboBox*);
  38117. void buttonClicked (Button* button);
  38118. void handleAsyncUpdate();
  38119. FilenameComponent (const FilenameComponent&);
  38120. FilenameComponent& operator= (const FilenameComponent&);
  38121. };
  38122. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38123. /*** End of inlined file: juce_FilenameComponent.h ***/
  38124. #endif
  38125. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38126. #endif
  38127. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38128. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  38129. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38130. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38131. /**
  38132. Shows a set of file paths in a list, allowing them to be added, removed or
  38133. re-ordered.
  38134. @see FileSearchPath
  38135. */
  38136. class JUCE_API FileSearchPathListComponent : public Component,
  38137. public SettableTooltipClient,
  38138. public FileDragAndDropTarget,
  38139. private ButtonListener,
  38140. private ListBoxModel
  38141. {
  38142. public:
  38143. /** Creates an empty FileSearchPathListComponent.
  38144. */
  38145. FileSearchPathListComponent();
  38146. /** Destructor. */
  38147. ~FileSearchPathListComponent();
  38148. /** Returns the path as it is currently shown. */
  38149. const FileSearchPath& getPath() const throw() { return path; }
  38150. /** Changes the current path. */
  38151. void setPath (const FileSearchPath& newPath);
  38152. /** Sets a file or directory to be the default starting point for the browser to show.
  38153. This is only used if the current file hasn't been set.
  38154. */
  38155. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  38156. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38157. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38158. methods.
  38159. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38160. */
  38161. enum ColourIds
  38162. {
  38163. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  38164. Make this transparent if you don't want the background to be filled. */
  38165. };
  38166. /** @internal */
  38167. int getNumRows();
  38168. /** @internal */
  38169. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  38170. /** @internal */
  38171. void deleteKeyPressed (int lastRowSelected);
  38172. /** @internal */
  38173. void returnKeyPressed (int lastRowSelected);
  38174. /** @internal */
  38175. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  38176. /** @internal */
  38177. void selectedRowsChanged (int lastRowSelected);
  38178. /** @internal */
  38179. void resized();
  38180. /** @internal */
  38181. void paint (Graphics& g);
  38182. /** @internal */
  38183. bool isInterestedInFileDrag (const StringArray& files);
  38184. /** @internal */
  38185. void filesDropped (const StringArray& files, int, int);
  38186. /** @internal */
  38187. void buttonClicked (Button* button);
  38188. juce_UseDebuggingNewOperator
  38189. private:
  38190. FileSearchPath path;
  38191. File defaultBrowseTarget;
  38192. ListBox* listBox;
  38193. Button* addButton;
  38194. Button* removeButton;
  38195. TextButton* changeButton;
  38196. DrawableButton* upButton;
  38197. DrawableButton* downButton;
  38198. void changed();
  38199. void updateButtons();
  38200. FileSearchPathListComponent (const FileSearchPathListComponent&);
  38201. FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  38202. };
  38203. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38204. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  38205. #endif
  38206. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38207. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  38208. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38209. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38210. /**
  38211. A component that displays the files in a directory as a treeview.
  38212. This implements the DirectoryContentsDisplayComponent base class so that
  38213. it can be used in a FileBrowserComponent.
  38214. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38215. class and the FileBrowserListener class.
  38216. @see DirectoryContentsList, FileListComponent
  38217. */
  38218. class JUCE_API FileTreeComponent : public TreeView,
  38219. public DirectoryContentsDisplayComponent
  38220. {
  38221. public:
  38222. /** Creates a listbox to show the contents of a specified directory.
  38223. */
  38224. FileTreeComponent (DirectoryContentsList& listToShow);
  38225. /** Destructor. */
  38226. ~FileTreeComponent();
  38227. /** Returns the number of files the user has got selected.
  38228. @see getSelectedFile
  38229. */
  38230. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  38231. /** Returns one of the files that the user has currently selected.
  38232. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  38233. @see getNumSelectedFiles
  38234. */
  38235. const File getSelectedFile (int index = 0) const;
  38236. /** Deselects any files that are currently selected. */
  38237. void deselectAllFiles();
  38238. /** Scrolls the list to the top. */
  38239. void scrollToTop();
  38240. /** Setting a name for this allows tree items to be dragged.
  38241. The string that you pass in here will be returned by the getDragSourceDescription()
  38242. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  38243. */
  38244. void setDragAndDropDescription (const String& description);
  38245. /** Returns the last value that was set by setDragAndDropDescription().
  38246. */
  38247. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  38248. juce_UseDebuggingNewOperator
  38249. private:
  38250. String dragAndDropDescription;
  38251. FileTreeComponent (const FileTreeComponent&);
  38252. FileTreeComponent& operator= (const FileTreeComponent&);
  38253. };
  38254. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38255. /*** End of inlined file: juce_FileTreeComponent.h ***/
  38256. #endif
  38257. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38258. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  38259. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38260. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38261. /**
  38262. A simple preview component that shows thumbnails of image files.
  38263. @see FileChooserDialogBox, FilePreviewComponent
  38264. */
  38265. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  38266. private Timer
  38267. {
  38268. public:
  38269. /** Creates an ImagePreviewComponent. */
  38270. ImagePreviewComponent();
  38271. /** Destructor. */
  38272. ~ImagePreviewComponent();
  38273. /** @internal */
  38274. void selectedFileChanged (const File& newSelectedFile);
  38275. /** @internal */
  38276. void paint (Graphics& g);
  38277. /** @internal */
  38278. void timerCallback();
  38279. juce_UseDebuggingNewOperator
  38280. private:
  38281. File fileToLoad;
  38282. Image currentThumbnail;
  38283. String currentDetails;
  38284. void getThumbSize (int& w, int& h) const;
  38285. ImagePreviewComponent (const ImagePreviewComponent&);
  38286. ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  38287. };
  38288. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38289. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  38290. #endif
  38291. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38292. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  38293. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38294. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38295. /**
  38296. A type of FileFilter that works by wildcard pattern matching.
  38297. This filter only allows files that match one of the specified patterns, but
  38298. allows all directories through.
  38299. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38300. */
  38301. class JUCE_API WildcardFileFilter : public FileFilter
  38302. {
  38303. public:
  38304. /**
  38305. Creates a wildcard filter for one or more patterns.
  38306. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  38307. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  38308. or .aiff.
  38309. The description is a name to show the user in a list of possible patterns, so
  38310. for the wav/aiff example, your description might be "audio files".
  38311. */
  38312. WildcardFileFilter (const String& fileWildcardPatterns,
  38313. const String& directoryWildcardPatterns,
  38314. const String& description);
  38315. /** Destructor. */
  38316. ~WildcardFileFilter();
  38317. /** Returns true if the filename matches one of the patterns specified. */
  38318. bool isFileSuitable (const File& file) const;
  38319. /** This always returns true. */
  38320. bool isDirectorySuitable (const File& file) const;
  38321. juce_UseDebuggingNewOperator
  38322. private:
  38323. StringArray fileWildcards, directoryWildcards;
  38324. static void parse (const String& pattern, StringArray& result);
  38325. static bool match (const File& file, const StringArray& wildcards);
  38326. };
  38327. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38328. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  38329. #endif
  38330. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  38331. #endif
  38332. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  38333. #endif
  38334. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  38335. #endif
  38336. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  38337. #endif
  38338. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  38339. #endif
  38340. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  38341. #endif
  38342. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38343. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  38344. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38345. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38346. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  38347. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38348. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38349. /**
  38350. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  38351. command in a ApplicationCommandManager.
  38352. Normally, you won't actually create a KeyPressMappingSet directly, because
  38353. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  38354. you'd create yourself an ApplicationCommandManager, and call its
  38355. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  38356. KeyPressMappingSet.
  38357. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  38358. to the top-level component for which you want to handle keystrokes. So for example:
  38359. @code
  38360. class MyMainWindow : public Component
  38361. {
  38362. ApplicationCommandManager* myCommandManager;
  38363. public:
  38364. MyMainWindow()
  38365. {
  38366. myCommandManager = new ApplicationCommandManager();
  38367. // first, make sure the command manager has registered all the commands that its
  38368. // targets can perform..
  38369. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  38370. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  38371. // this will use the command manager to initialise the KeyPressMappingSet with
  38372. // the default keypresses that were specified when the targets added their commands
  38373. // to the manager.
  38374. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  38375. // having set up the default key-mappings, you might now want to load the last set
  38376. // of mappings that the user configured.
  38377. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  38378. // Now tell our top-level window to send any keypresses that arrive to the
  38379. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  38380. addKeyListener (myCommandManager->getKeyMappings());
  38381. }
  38382. ...
  38383. }
  38384. @endcode
  38385. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  38386. register to be told when a command or mapping is added, removed, etc.
  38387. There's also a UI component called KeyMappingEditorComponent that can be used
  38388. to easily edit the key mappings.
  38389. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  38390. */
  38391. class JUCE_API KeyPressMappingSet : public KeyListener,
  38392. public ChangeBroadcaster,
  38393. public FocusChangeListener
  38394. {
  38395. public:
  38396. /** Creates a KeyPressMappingSet for a given command manager.
  38397. Normally, you won't actually create a KeyPressMappingSet directly, because
  38398. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  38399. best thing to do is to create your ApplicationCommandManager, and use the
  38400. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  38401. When a suitable keypress happens, the manager's invoke() method will be
  38402. used to invoke the appropriate command.
  38403. @see ApplicationCommandManager
  38404. */
  38405. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  38406. /** Creates an copy of a KeyPressMappingSet. */
  38407. KeyPressMappingSet (const KeyPressMappingSet& other);
  38408. /** Destructor. */
  38409. ~KeyPressMappingSet();
  38410. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  38411. /** Returns a list of keypresses that are assigned to a particular command.
  38412. @param commandID the command's ID
  38413. */
  38414. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  38415. /** Assigns a keypress to a command.
  38416. If the keypress is already assigned to a different command, it will first be
  38417. removed from that command, to avoid it triggering multiple functions.
  38418. @param commandID the ID of the command that you want to add a keypress to. If
  38419. this is 0, the keypress will be removed from anything that it
  38420. was previously assigned to, but not re-assigned
  38421. @param newKeyPress the new key-press
  38422. @param insertIndex if this is less than zero, the key will be appended to the
  38423. end of the list of keypresses; otherwise the new keypress will
  38424. be inserted into the existing list at this index
  38425. */
  38426. void addKeyPress (CommandID commandID,
  38427. const KeyPress& newKeyPress,
  38428. int insertIndex = -1);
  38429. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  38430. @see resetToDefaultMapping
  38431. */
  38432. void resetToDefaultMappings();
  38433. /** Resets all key-mappings to the defaults for a particular command.
  38434. @see resetToDefaultMappings
  38435. */
  38436. void resetToDefaultMapping (CommandID commandID);
  38437. /** Removes all keypresses that are assigned to any commands. */
  38438. void clearAllKeyPresses();
  38439. /** Removes all keypresses that are assigned to a particular command. */
  38440. void clearAllKeyPresses (CommandID commandID);
  38441. /** Removes one of the keypresses that are assigned to a command.
  38442. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  38443. which the keyPressIndex refers.
  38444. */
  38445. void removeKeyPress (CommandID commandID, int keyPressIndex);
  38446. /** Removes a keypress from any command that it may be assigned to.
  38447. */
  38448. void removeKeyPress (const KeyPress& keypress);
  38449. /** Returns true if the given command is linked to this key. */
  38450. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  38451. /** Looks for a command that corresponds to a keypress.
  38452. @returns the UID of the command or 0 if none was found
  38453. */
  38454. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  38455. /** Tries to recreate the mappings from a previously stored state.
  38456. The XML passed in must have been created by the createXml() method.
  38457. If the stored state makes any reference to commands that aren't
  38458. currently available, these will be ignored.
  38459. If the set of mappings being loaded was a set of differences (using createXml (true)),
  38460. then this will call resetToDefaultMappings() and then merge the saved mappings
  38461. on top. If the saved set was created with createXml (false), then this method
  38462. will first clear all existing mappings and load the saved ones as a complete set.
  38463. @returns true if it manages to load the XML correctly
  38464. @see createXml
  38465. */
  38466. bool restoreFromXml (const XmlElement& xmlVersion);
  38467. /** Creates an XML representation of the current mappings.
  38468. This will produce a lump of XML that can be later reloaded using
  38469. restoreFromXml() to recreate the current mapping state.
  38470. The object that is returned must be deleted by the caller.
  38471. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  38472. will be saved into the XML. If it's true, then the XML will
  38473. only store the differences between the current mappings and
  38474. the default mappings you'd get from calling resetToDefaultMappings().
  38475. The advantage of saving a set of differences from the default is that
  38476. if you change the default mappings (in a new version of your app, for
  38477. example), then these will be merged into a user's saved preferences.
  38478. @see restoreFromXml
  38479. */
  38480. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  38481. /** @internal */
  38482. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  38483. /** @internal */
  38484. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  38485. /** @internal */
  38486. void globalFocusChanged (Component* focusedComponent);
  38487. juce_UseDebuggingNewOperator
  38488. private:
  38489. ApplicationCommandManager* commandManager;
  38490. struct CommandMapping
  38491. {
  38492. CommandID commandID;
  38493. Array <KeyPress> keypresses;
  38494. bool wantsKeyUpDownCallbacks;
  38495. };
  38496. OwnedArray <CommandMapping> mappings;
  38497. struct KeyPressTime
  38498. {
  38499. KeyPress key;
  38500. uint32 timeWhenPressed;
  38501. };
  38502. OwnedArray <KeyPressTime> keysDown;
  38503. void handleMessage (const Message& message);
  38504. void invokeCommand (const CommandID commandID,
  38505. const KeyPress& keyPress,
  38506. const bool isKeyDown,
  38507. const int millisecsSinceKeyPressed,
  38508. Component* const originatingComponent) const;
  38509. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  38510. };
  38511. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38512. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  38513. /**
  38514. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  38515. object.
  38516. @see KeyPressMappingSet
  38517. */
  38518. class JUCE_API KeyMappingEditorComponent : public Component,
  38519. public TreeViewItem,
  38520. public ChangeListener,
  38521. private ButtonListener
  38522. {
  38523. public:
  38524. /** Creates a KeyMappingEditorComponent.
  38525. @param mappingSet this is the set of mappings to display and
  38526. edit. Make sure the mappings object is not
  38527. deleted before this component!
  38528. @param showResetToDefaultButton if true, then at the bottom of the
  38529. list, the component will include a 'reset to
  38530. defaults' button.
  38531. */
  38532. KeyMappingEditorComponent (KeyPressMappingSet* mappingSet,
  38533. bool showResetToDefaultButton);
  38534. /** Destructor. */
  38535. virtual ~KeyMappingEditorComponent();
  38536. /** Sets up the colours to use for parts of the component.
  38537. @param mainBackground colour to use for most of the background
  38538. @param textColour colour to use for the text
  38539. */
  38540. void setColours (const Colour& mainBackground,
  38541. const Colour& textColour);
  38542. /** Returns the KeyPressMappingSet that this component is acting upon.
  38543. */
  38544. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  38545. /** Can be overridden if some commands need to be excluded from the list.
  38546. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  38547. method to decide what to return, but you can override it to handle special cases.
  38548. */
  38549. virtual bool shouldCommandBeIncluded (CommandID commandID);
  38550. /** Can be overridden to indicate that some commands are shown as read-only.
  38551. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  38552. method to decide what to return, but you can override it to handle special cases.
  38553. */
  38554. virtual bool isCommandReadOnly (CommandID commandID);
  38555. /** This can be overridden to let you change the format of the string used
  38556. to describe a keypress.
  38557. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  38558. keys that are triggered by something else externally. If you override the
  38559. method, be sure to let the base class's method handle keys you're not
  38560. interested in.
  38561. */
  38562. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  38563. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38564. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38565. methods.
  38566. To change the colours of the menu that pops up
  38567. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38568. */
  38569. enum ColourIds
  38570. {
  38571. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  38572. textColourId = 0x100ad01, /**< The colour for the text. */
  38573. };
  38574. /** @internal */
  38575. void parentHierarchyChanged();
  38576. /** @internal */
  38577. void resized();
  38578. /** @internal */
  38579. void changeListenerCallback (void*);
  38580. /** @internal */
  38581. bool mightContainSubItems();
  38582. /** @internal */
  38583. const String getUniqueName() const;
  38584. /** @internal */
  38585. void buttonClicked (Button* button);
  38586. juce_UseDebuggingNewOperator
  38587. private:
  38588. KeyPressMappingSet* mappings;
  38589. TreeView* tree;
  38590. friend class KeyMappingTreeViewItem;
  38591. friend class KeyCategoryTreeViewItem;
  38592. friend class KeyMappingItemComponent;
  38593. friend class KeyMappingChangeButton;
  38594. TextButton* resetButton;
  38595. void assignNewKey (CommandID commandID, int index);
  38596. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  38597. KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  38598. };
  38599. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38600. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  38601. #endif
  38602. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  38603. #endif
  38604. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38605. #endif
  38606. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  38607. #endif
  38608. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38609. #endif
  38610. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  38611. #endif
  38612. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  38613. #endif
  38614. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38615. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  38616. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38617. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38618. /** An object that watches for any movement of a component or any of its parent components.
  38619. This makes it easy to check when a component is moved relative to its top-level
  38620. peer window. The normal Component::moved() method is only called when a component
  38621. moves relative to its immediate parent, and sometimes you want to know if any of
  38622. components higher up the tree have moved (which of course will affect the overall
  38623. position of all their sub-components).
  38624. It also includes a callback that lets you know when the top-level peer is changed.
  38625. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  38626. because they need to keep their custom windows in the right place and respond to
  38627. changes in the peer.
  38628. */
  38629. class JUCE_API ComponentMovementWatcher : public ComponentListener
  38630. {
  38631. public:
  38632. /** Creates a ComponentMovementWatcher to watch a given target component. */
  38633. ComponentMovementWatcher (Component* component);
  38634. /** Destructor. */
  38635. ~ComponentMovementWatcher();
  38636. /** This callback happens when the component that is being watched is moved
  38637. relative to its top-level peer window, or when it is resized.
  38638. */
  38639. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  38640. /** This callback happens when the component's top-level peer is changed.
  38641. */
  38642. virtual void componentPeerChanged() = 0;
  38643. juce_UseDebuggingNewOperator
  38644. /** @internal */
  38645. void componentParentHierarchyChanged (Component& component);
  38646. /** @internal */
  38647. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  38648. private:
  38649. Component::SafePointer<Component> component;
  38650. ComponentPeer* lastPeer;
  38651. Array <Component*> registeredParentComps;
  38652. bool reentrant;
  38653. Rectangle<int> lastBounds;
  38654. void unregister() throw();
  38655. void registerWithParentComps() throw();
  38656. ComponentMovementWatcher (const ComponentMovementWatcher&);
  38657. ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  38658. };
  38659. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38660. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  38661. #endif
  38662. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38663. /*** Start of inlined file: juce_GroupComponent.h ***/
  38664. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38665. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38666. /**
  38667. A component that draws an outline around itself and has an optional title at
  38668. the top, for drawing an outline around a group of controls.
  38669. */
  38670. class JUCE_API GroupComponent : public Component
  38671. {
  38672. public:
  38673. /** Creates a GroupComponent.
  38674. @param componentName the name to give the component
  38675. @param labelText the text to show at the top of the outline
  38676. */
  38677. GroupComponent (const String& componentName = String::empty,
  38678. const String& labelText = String::empty);
  38679. /** Destructor. */
  38680. ~GroupComponent();
  38681. /** Changes the text that's shown at the top of the component. */
  38682. void setText (const String& newText);
  38683. /** Returns the currently displayed text label. */
  38684. const String getText() const;
  38685. /** Sets the positioning of the text label.
  38686. (The default is Justification::left)
  38687. @see getTextLabelPosition
  38688. */
  38689. void setTextLabelPosition (const Justification& justification);
  38690. /** Returns the current text label position.
  38691. @see setTextLabelPosition
  38692. */
  38693. const Justification getTextLabelPosition() const throw() { return justification; }
  38694. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38695. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38696. methods.
  38697. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38698. */
  38699. enum ColourIds
  38700. {
  38701. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  38702. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  38703. };
  38704. /** @internal */
  38705. void paint (Graphics& g);
  38706. /** @internal */
  38707. void enablementChanged();
  38708. /** @internal */
  38709. void colourChanged();
  38710. private:
  38711. String text;
  38712. Justification justification;
  38713. GroupComponent (const GroupComponent&);
  38714. GroupComponent& operator= (const GroupComponent&);
  38715. };
  38716. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38717. /*** End of inlined file: juce_GroupComponent.h ***/
  38718. #endif
  38719. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38720. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  38721. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38722. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38723. /*** Start of inlined file: juce_TabbedComponent.h ***/
  38724. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38725. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38726. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  38727. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38728. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38729. class TabbedButtonBar;
  38730. /** In a TabbedButtonBar, this component is used for each of the buttons.
  38731. If you want to create a TabbedButtonBar with custom tab components, derive
  38732. your component from this class, and override the TabbedButtonBar::createTabButton()
  38733. method to create it instead of the default one.
  38734. @see TabbedButtonBar
  38735. */
  38736. class JUCE_API TabBarButton : public Button
  38737. {
  38738. public:
  38739. /** Creates the tab button. */
  38740. TabBarButton (const String& name,
  38741. TabbedButtonBar* ownerBar,
  38742. int tabIndex);
  38743. /** Destructor. */
  38744. ~TabBarButton();
  38745. /** Chooses the best length for the tab, given the specified depth.
  38746. If the tab is horizontal, this should return its width, and the depth
  38747. specifies its height. If it's vertical, it should return the height, and
  38748. the depth is actually its width.
  38749. */
  38750. virtual int getBestTabLength (int depth);
  38751. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  38752. void clicked (const ModifierKeys& mods);
  38753. bool hitTest (int x, int y);
  38754. juce_UseDebuggingNewOperator
  38755. protected:
  38756. friend class TabbedButtonBar;
  38757. TabbedButtonBar* const owner;
  38758. int tabIndex, overlapPixels;
  38759. DropShadowEffect shadow;
  38760. /** Returns an area of the component that's safe to draw in.
  38761. This deals with the orientation of the tabs, which affects which side is
  38762. touching the tabbed box's content component.
  38763. */
  38764. void getActiveArea (int& x, int& y, int& w, int& h);
  38765. private:
  38766. TabBarButton (const TabBarButton&);
  38767. TabBarButton& operator= (const TabBarButton&);
  38768. };
  38769. /**
  38770. A vertical or horizontal bar containing tabs that you can select.
  38771. You can use one of these to generate things like a dialog box that has
  38772. tabbed pages you can flip between. Attach a ChangeListener to the
  38773. button bar to be told when the user changes the page.
  38774. An easier method than doing this is to use a TabbedComponent, which
  38775. contains its own TabbedButtonBar and which takes care of the layout
  38776. and other housekeeping.
  38777. @see TabbedComponent
  38778. */
  38779. class JUCE_API TabbedButtonBar : public Component,
  38780. public ChangeBroadcaster,
  38781. public ButtonListener
  38782. {
  38783. public:
  38784. /** The placement of the tab-bar
  38785. @see setOrientation, getOrientation
  38786. */
  38787. enum Orientation
  38788. {
  38789. TabsAtTop,
  38790. TabsAtBottom,
  38791. TabsAtLeft,
  38792. TabsAtRight
  38793. };
  38794. /** Creates a TabbedButtonBar with a given placement.
  38795. You can change the orientation later if you need to.
  38796. */
  38797. TabbedButtonBar (Orientation orientation);
  38798. /** Destructor. */
  38799. ~TabbedButtonBar();
  38800. /** Changes the bar's orientation.
  38801. This won't change the bar's actual size - you'll need to do that yourself,
  38802. but this determines which direction the tabs go in, and which side they're
  38803. stuck to.
  38804. */
  38805. void setOrientation (Orientation orientation);
  38806. /** Returns the current orientation.
  38807. @see setOrientation
  38808. */
  38809. Orientation getOrientation() const throw() { return orientation; }
  38810. /** Deletes all the tabs from the bar.
  38811. @see addTab
  38812. */
  38813. void clearTabs();
  38814. /** Adds a tab to the bar.
  38815. Tabs are added in left-to-right reading order.
  38816. If this is the first tab added, it'll also be automatically selected.
  38817. */
  38818. void addTab (const String& tabName,
  38819. const Colour& tabBackgroundColour,
  38820. int insertIndex = -1);
  38821. /** Changes the name of one of the tabs. */
  38822. void setTabName (int tabIndex,
  38823. const String& newName);
  38824. /** Gets rid of one of the tabs. */
  38825. void removeTab (int tabIndex);
  38826. /** Moves a tab to a new index in the list.
  38827. Pass -1 as the index to move it to the end of the list.
  38828. */
  38829. void moveTab (int currentIndex, int newIndex);
  38830. /** Returns the number of tabs in the bar. */
  38831. int getNumTabs() const;
  38832. /** Returns a list of all the tab names in the bar. */
  38833. const StringArray getTabNames() const;
  38834. /** Changes the currently selected tab.
  38835. This will send a change message and cause a synchronous callback to
  38836. the currentTabChanged() method. (But if the given tab is already selected,
  38837. nothing will be done).
  38838. To deselect all the tabs, use an index of -1.
  38839. */
  38840. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38841. /** Returns the name of the currently selected tab.
  38842. This could be an empty string if none are selected.
  38843. */
  38844. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  38845. /** Returns the index of the currently selected tab.
  38846. This could return -1 if none are selected.
  38847. */
  38848. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  38849. /** Returns the button for a specific tab.
  38850. The button that is returned may be deleted later by this component, so don't hang
  38851. on to the pointer that is returned. A null pointer may be returned if the index is
  38852. out of range.
  38853. */
  38854. TabBarButton* getTabButton (int index) const;
  38855. /** Callback method to indicate the selected tab has been changed.
  38856. @see setCurrentTabIndex
  38857. */
  38858. virtual void currentTabChanged (int newCurrentTabIndex,
  38859. const String& newCurrentTabName);
  38860. /** Callback method to indicate that the user has right-clicked on a tab.
  38861. (Or ctrl-clicked on the Mac)
  38862. */
  38863. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  38864. /** Returns the colour of a tab.
  38865. This is the colour that was specified in addTab().
  38866. */
  38867. const Colour getTabBackgroundColour (int tabIndex);
  38868. /** Changes the background colour of a tab.
  38869. @see addTab, getTabBackgroundColour
  38870. */
  38871. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38872. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38873. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38874. methods.
  38875. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38876. */
  38877. enum ColourIds
  38878. {
  38879. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  38880. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  38881. the look and feel will choose an appropriate colour. */
  38882. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  38883. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  38884. this isn't specified, the look and feel will choose an appropriate
  38885. colour. */
  38886. };
  38887. /** @internal */
  38888. void resized();
  38889. /** @internal */
  38890. void buttonClicked (Button* button);
  38891. /** @internal */
  38892. void lookAndFeelChanged();
  38893. juce_UseDebuggingNewOperator
  38894. protected:
  38895. /** This creates one of the tabs.
  38896. If you need to use custom tab components, you can override this method and
  38897. return your own class instead of the default.
  38898. */
  38899. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  38900. private:
  38901. Orientation orientation;
  38902. StringArray tabs;
  38903. Array <Colour> tabColours;
  38904. int currentTabIndex;
  38905. Component* behindFrontTab;
  38906. ScopedPointer<Button> extraTabsButton;
  38907. TabbedButtonBar (const TabbedButtonBar&);
  38908. TabbedButtonBar& operator= (const TabbedButtonBar&);
  38909. };
  38910. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38911. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  38912. /**
  38913. A component with a TabbedButtonBar along one of its sides.
  38914. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  38915. with addTab(), and this will take care of showing the pages for you when the
  38916. user clicks on a different tab.
  38917. @see TabbedButtonBar
  38918. */
  38919. class JUCE_API TabbedComponent : public Component
  38920. {
  38921. public:
  38922. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  38923. Once created, add some tabs with the addTab() method.
  38924. */
  38925. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  38926. /** Destructor. */
  38927. ~TabbedComponent();
  38928. /** Changes the placement of the tabs.
  38929. This will rearrange the layout to place the tabs along the appropriate
  38930. side of this component, and will shift the content component accordingly.
  38931. @see TabbedButtonBar::setOrientation
  38932. */
  38933. void setOrientation (TabbedButtonBar::Orientation orientation);
  38934. /** Returns the current tab placement.
  38935. @see setOrientation, TabbedButtonBar::getOrientation
  38936. */
  38937. TabbedButtonBar::Orientation getOrientation() const throw();
  38938. /** Specifies how many pixels wide or high the tab-bar should be.
  38939. If the tabs are placed along the top or bottom, this specified the height
  38940. of the bar; if they're along the left or right edges, it'll be the width
  38941. of the bar.
  38942. */
  38943. void setTabBarDepth (int newDepth);
  38944. /** Returns the current thickness of the tab bar.
  38945. @see setTabBarDepth
  38946. */
  38947. int getTabBarDepth() const throw() { return tabDepth; }
  38948. /** Specifies the thickness of an outline that should be drawn around the content component.
  38949. If this thickness is > 0, a line will be drawn around the three sides of the content
  38950. component which don't touch the tab-bar, and the content component will be inset by this amount.
  38951. To set the colour of the line, use setColour (outlineColourId, ...).
  38952. */
  38953. void setOutline (int newThickness);
  38954. /** Specifies a gap to leave around the edge of the content component.
  38955. Each edge of the content component will be indented by the given number of pixels.
  38956. */
  38957. void setIndent (int indentThickness);
  38958. /** Removes all the tabs from the bar.
  38959. @see TabbedButtonBar::clearTabs
  38960. */
  38961. void clearTabs();
  38962. /** Adds a tab to the tab-bar.
  38963. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  38964. is true, it will be deleted when the tab is removed or when this object is
  38965. deleted.
  38966. @see TabbedButtonBar::addTab
  38967. */
  38968. void addTab (const String& tabName,
  38969. const Colour& tabBackgroundColour,
  38970. Component* contentComponent,
  38971. bool deleteComponentWhenNotNeeded,
  38972. int insertIndex = -1);
  38973. /** Changes the name of one of the tabs. */
  38974. void setTabName (int tabIndex, const String& newName);
  38975. /** Gets rid of one of the tabs. */
  38976. void removeTab (int tabIndex);
  38977. /** Returns the number of tabs in the bar. */
  38978. int getNumTabs() const;
  38979. /** Returns a list of all the tab names in the bar. */
  38980. const StringArray getTabNames() const;
  38981. /** Returns the content component that was added for the given index.
  38982. Be sure not to use or delete the components that are returned, as this may interfere
  38983. with the TabbedComponent's use of them.
  38984. */
  38985. Component* getTabContentComponent (int tabIndex) const throw();
  38986. /** Returns the colour of one of the tabs. */
  38987. const Colour getTabBackgroundColour (int tabIndex) const throw();
  38988. /** Changes the background colour of one of the tabs. */
  38989. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38990. /** Changes the currently-selected tab.
  38991. To deselect all the tabs, pass -1 as the index.
  38992. @see TabbedButtonBar::setCurrentTabIndex
  38993. */
  38994. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38995. /** Returns the index of the currently selected tab.
  38996. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  38997. */
  38998. int getCurrentTabIndex() const;
  38999. /** Returns the name of the currently selected tab.
  39000. @see addTab, TabbedButtonBar::getCurrentTabName()
  39001. */
  39002. const String& getCurrentTabName() const;
  39003. /** Returns the current component that's filling the panel.
  39004. This will return 0 if there isn't one.
  39005. */
  39006. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  39007. /** Callback method to indicate the selected tab has been changed.
  39008. @see setCurrentTabIndex
  39009. */
  39010. virtual void currentTabChanged (int newCurrentTabIndex,
  39011. const String& newCurrentTabName);
  39012. /** Callback method to indicate that the user has right-clicked on a tab.
  39013. (Or ctrl-clicked on the Mac)
  39014. */
  39015. virtual void popupMenuClickOnTab (int tabIndex,
  39016. const String& tabName);
  39017. /** Returns the tab button bar component that is being used.
  39018. */
  39019. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  39020. /** A set of colour IDs to use to change the colour of various aspects of the component.
  39021. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39022. methods.
  39023. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39024. */
  39025. enum ColourIds
  39026. {
  39027. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  39028. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  39029. (See setOutline) */
  39030. };
  39031. /** @internal */
  39032. void paint (Graphics& g);
  39033. /** @internal */
  39034. void resized();
  39035. /** @internal */
  39036. void lookAndFeelChanged();
  39037. juce_UseDebuggingNewOperator
  39038. protected:
  39039. TabbedButtonBar* tabs;
  39040. /** This creates one of the tab buttons.
  39041. If you need to use custom tab components, you can override this method and
  39042. return your own class instead of the default.
  39043. */
  39044. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  39045. private:
  39046. Array <Component*> contentComponents;
  39047. Component* panelComponent;
  39048. int tabDepth;
  39049. int outlineThickness, edgeIndent;
  39050. static const Identifier deleteComponentId;
  39051. friend class TabCompButtonBar;
  39052. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  39053. TabbedComponent (const TabbedComponent&);
  39054. TabbedComponent& operator= (const TabbedComponent&);
  39055. };
  39056. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  39057. /*** End of inlined file: juce_TabbedComponent.h ***/
  39058. /*** Start of inlined file: juce_DocumentWindow.h ***/
  39059. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39060. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39061. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  39062. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39063. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39064. /*** Start of inlined file: juce_MenuBarModel.h ***/
  39065. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  39066. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  39067. class MenuBarModel;
  39068. /**
  39069. A class to receive callbacks when a MenuBarModel changes.
  39070. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  39071. */
  39072. class JUCE_API MenuBarModelListener
  39073. {
  39074. public:
  39075. /** Destructor. */
  39076. virtual ~MenuBarModelListener() {}
  39077. /** This callback is made when items are changed in the menu bar model.
  39078. */
  39079. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  39080. /** This callback is made when an application command is invoked that
  39081. is represented by one of the items in the menu bar model.
  39082. */
  39083. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  39084. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  39085. };
  39086. /**
  39087. A class for controlling MenuBar components.
  39088. This class is used to tell a MenuBar what menus to show, and to respond
  39089. to a menu being selected.
  39090. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  39091. */
  39092. class JUCE_API MenuBarModel : private AsyncUpdater,
  39093. private ApplicationCommandManagerListener
  39094. {
  39095. public:
  39096. MenuBarModel() throw();
  39097. /** Destructor. */
  39098. virtual ~MenuBarModel();
  39099. /** Call this when some of your menu items have changed.
  39100. This method will cause a callback to any MenuBarListener objects that
  39101. are registered with this model.
  39102. If this model is displaying items from an ApplicationCommandManager, you
  39103. can use the setApplicationCommandManagerToWatch() method to cause
  39104. change messages to be sent automatically when the ApplicationCommandManager
  39105. is changed.
  39106. @see addListener, removeListener, MenuBarListener
  39107. */
  39108. void menuItemsChanged();
  39109. /** Tells the menu bar to listen to the specified command manager, and to update
  39110. itself when the commands change.
  39111. This will also allow it to flash a menu name when a command from that menu
  39112. is invoked using a keystroke.
  39113. */
  39114. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  39115. /** Registers a listener for callbacks when the menu items in this model change.
  39116. The listener object will get callbacks when this object's menuItemsChanged()
  39117. method is called.
  39118. @see removeListener
  39119. */
  39120. void addListener (MenuBarModelListener* listenerToAdd) throw();
  39121. /** Removes a listener.
  39122. @see addListener
  39123. */
  39124. void removeListener (MenuBarModelListener* listenerToRemove) throw();
  39125. /** This method must return a list of the names of the menus. */
  39126. virtual const StringArray getMenuBarNames() = 0;
  39127. /** This should return the popup menu to display for a given top-level menu.
  39128. @param topLevelMenuIndex the index of the top-level menu to show
  39129. @param menuName the name of the top-level menu item to show
  39130. */
  39131. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  39132. const String& menuName) = 0;
  39133. /** This is called when a menu item has been clicked on.
  39134. @param menuItemID the item ID of the PopupMenu item that was selected
  39135. @param topLevelMenuIndex the index of the top-level menu from which the item was
  39136. chosen (just in case you've used duplicate ID numbers
  39137. on more than one of the popup menus)
  39138. */
  39139. virtual void menuItemSelected (int menuItemID,
  39140. int topLevelMenuIndex) = 0;
  39141. #if JUCE_MAC || DOXYGEN
  39142. /** MAC ONLY - Sets the model that is currently being shown as the main
  39143. menu bar at the top of the screen on the Mac.
  39144. You can pass 0 to stop the current model being displayed. Be careful
  39145. not to delete a model while it is being used.
  39146. An optional extra menu can be specified, containing items to add to the top of
  39147. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  39148. an apple, it's the one next to it, with your application's name at the top
  39149. and the services menu etc on it). When one of these items is selected, the
  39150. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  39151. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  39152. object then newMenuBarModel must be non-null.
  39153. */
  39154. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  39155. const PopupMenu* extraAppleMenuItems = 0);
  39156. /** MAC ONLY - Returns the menu model that is currently being shown as
  39157. the main menu bar.
  39158. */
  39159. static MenuBarModel* getMacMainMenu();
  39160. #endif
  39161. /** @internal */
  39162. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  39163. /** @internal */
  39164. void applicationCommandListChanged();
  39165. /** @internal */
  39166. void handleAsyncUpdate();
  39167. juce_UseDebuggingNewOperator
  39168. private:
  39169. ApplicationCommandManager* manager;
  39170. ListenerList <MenuBarModelListener> listeners;
  39171. MenuBarModel (const MenuBarModel&);
  39172. MenuBarModel& operator= (const MenuBarModel&);
  39173. };
  39174. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  39175. /*** End of inlined file: juce_MenuBarModel.h ***/
  39176. /**
  39177. A menu bar component.
  39178. @see MenuBarModel
  39179. */
  39180. class JUCE_API MenuBarComponent : public Component,
  39181. private MenuBarModelListener,
  39182. private Timer
  39183. {
  39184. public:
  39185. /** Creates a menu bar.
  39186. @param model the model object to use to control this bar. You can
  39187. pass 0 into this if you like, and set the model later
  39188. using the setModel() method
  39189. */
  39190. MenuBarComponent (MenuBarModel* model);
  39191. /** Destructor. */
  39192. ~MenuBarComponent();
  39193. /** Changes the model object to use to control the bar.
  39194. This can be 0, in which case the bar will be empty. Don't delete the object
  39195. that is passed-in while it's still being used by this MenuBar.
  39196. */
  39197. void setModel (MenuBarModel* newModel);
  39198. /** Returns the current menu bar model being used.
  39199. */
  39200. MenuBarModel* getModel() const throw();
  39201. /** Pops up one of the menu items.
  39202. This lets you manually open one of the menus - it could be triggered by a
  39203. key shortcut, for example.
  39204. */
  39205. void showMenu (int menuIndex);
  39206. /** @internal */
  39207. void paint (Graphics& g);
  39208. /** @internal */
  39209. void resized();
  39210. /** @internal */
  39211. void mouseEnter (const MouseEvent& e);
  39212. /** @internal */
  39213. void mouseExit (const MouseEvent& e);
  39214. /** @internal */
  39215. void mouseDown (const MouseEvent& e);
  39216. /** @internal */
  39217. void mouseDrag (const MouseEvent& e);
  39218. /** @internal */
  39219. void mouseUp (const MouseEvent& e);
  39220. /** @internal */
  39221. void mouseMove (const MouseEvent& e);
  39222. /** @internal */
  39223. void handleCommandMessage (int commandId);
  39224. /** @internal */
  39225. bool keyPressed (const KeyPress& key);
  39226. /** @internal */
  39227. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  39228. /** @internal */
  39229. void menuCommandInvoked (MenuBarModel* menuBarModel,
  39230. const ApplicationCommandTarget::InvocationInfo& info);
  39231. juce_UseDebuggingNewOperator
  39232. private:
  39233. class AsyncCallback;
  39234. friend class AsyncCallback;
  39235. MenuBarModel* model;
  39236. StringArray menuNames;
  39237. Array <int> xPositions;
  39238. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  39239. int lastMouseX, lastMouseY;
  39240. int getItemAt (int x, int y);
  39241. void setItemUnderMouse (int index);
  39242. void setOpenItem (int index);
  39243. void updateItemUnderMouse (int x, int y);
  39244. void timerCallback();
  39245. void repaintMenuItem (int index);
  39246. void menuDismissed (int topLevelIndex, int itemId);
  39247. MenuBarComponent (const MenuBarComponent&);
  39248. MenuBarComponent& operator= (const MenuBarComponent&);
  39249. };
  39250. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39251. /*** End of inlined file: juce_MenuBarComponent.h ***/
  39252. /**
  39253. A resizable window with a title bar and maximise, minimise and close buttons.
  39254. This subclass of ResizableWindow creates a fairly standard type of window with
  39255. a title bar and various buttons. The name of the component is shown in the
  39256. title bar, and an icon can optionally be specified with setIcon().
  39257. All the methods available to a ResizableWindow are also available to this,
  39258. so it can easily be made resizable, minimised, maximised, etc.
  39259. It's not advisable to add child components directly to a DocumentWindow: put them
  39260. inside your content component instead. And overriding methods like resized(), moved(), etc
  39261. is also not recommended - instead override these methods for your content component.
  39262. (If for some obscure reason you do need to override these methods, always remember to
  39263. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  39264. decorations correctly).
  39265. You can also automatically add a menu bar to the window, using the setMenuBar()
  39266. method.
  39267. @see ResizableWindow, DialogWindow
  39268. */
  39269. class JUCE_API DocumentWindow : public ResizableWindow
  39270. {
  39271. public:
  39272. /** The set of available button-types that can be put on the title bar.
  39273. @see setTitleBarButtonsRequired
  39274. */
  39275. enum TitleBarButtons
  39276. {
  39277. minimiseButton = 1,
  39278. maximiseButton = 2,
  39279. closeButton = 4,
  39280. /** A combination of all the buttons above. */
  39281. allButtons = 7
  39282. };
  39283. /** Creates a DocumentWindow.
  39284. @param name the name to give the component - this is also
  39285. the title shown at the top of the window. To change
  39286. this later, use setName()
  39287. @param backgroundColour the colour to use for filling the window's background.
  39288. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  39289. should be shown on the title bar. This value is a bitwise
  39290. combination of values from the TitleBarButtons enum. Note
  39291. that it can be "allButtons" to get them all. You
  39292. can change this later with the setTitleBarButtonsRequired()
  39293. method, which can also specify where they are positioned.
  39294. @param addToDesktop if true, the window will be automatically added to the
  39295. desktop; if false, you can use it as a child component
  39296. @see TitleBarButtons
  39297. */
  39298. DocumentWindow (const String& name,
  39299. const Colour& backgroundColour,
  39300. int requiredButtons,
  39301. bool addToDesktop = true);
  39302. /** Destructor.
  39303. If a content component has been set with setContentComponent(), it
  39304. will be deleted.
  39305. */
  39306. ~DocumentWindow();
  39307. /** Changes the component's name.
  39308. (This is overridden from Component::setName() to cause a repaint, as
  39309. the name is what gets drawn across the window's title bar).
  39310. */
  39311. void setName (const String& newName);
  39312. /** Sets an icon to show in the title bar, next to the title.
  39313. A copy is made internally of the image, so the caller can delete the
  39314. image after calling this. If 0 is passed-in, any existing icon will be
  39315. removed.
  39316. */
  39317. void setIcon (const Image& imageToUse);
  39318. /** Changes the height of the title-bar. */
  39319. void setTitleBarHeight (int newHeight);
  39320. /** Returns the current title bar height. */
  39321. int getTitleBarHeight() const;
  39322. /** Changes the set of title-bar buttons being shown.
  39323. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  39324. should be shown on the title bar. This value is a bitwise
  39325. combination of values from the TitleBarButtons enum. Note
  39326. that it can be "allButtons" to get them all.
  39327. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  39328. left side of the bar; if false, they'll be placed at the right
  39329. */
  39330. void setTitleBarButtonsRequired (int requiredButtons,
  39331. bool positionTitleBarButtonsOnLeft);
  39332. /** Sets whether the title should be centred within the window.
  39333. If true, the title text is shown in the middle of the title-bar; if false,
  39334. it'll be shown at the left of the bar.
  39335. */
  39336. void setTitleBarTextCentred (bool textShouldBeCentred);
  39337. /** Creates a menu inside this window.
  39338. @param menuBarModel this specifies a MenuBarModel that should be used to
  39339. generate the contents of a menu bar that will be placed
  39340. just below the title bar, and just above any content
  39341. component. If this value is zero, any existing menu bar
  39342. will be removed from the component; if non-zero, one will
  39343. be added if it's required.
  39344. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  39345. or less to use the look-and-feel's default size.
  39346. */
  39347. void setMenuBar (MenuBarModel* menuBarModel,
  39348. int menuBarHeight = 0);
  39349. /** This method is called when the user tries to close the window.
  39350. This is triggered by the user clicking the close button, or using some other
  39351. OS-specific key shortcut or OS menu for getting rid of a window.
  39352. If the window is just a pop-up, you should override this closeButtonPressed()
  39353. method and make it delete the window in whatever way is appropriate for your
  39354. app. E.g. you might just want to call "delete this".
  39355. If your app is centred around this window such that the whole app should quit when
  39356. the window is closed, then you will probably want to use this method as an opportunity
  39357. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  39358. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  39359. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  39360. or closing it via the taskbar icon on Windows).
  39361. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  39362. redirects it to call this method, so any methods of closing the window that are
  39363. caught by userTriedToCloseWindow() will also end up here).
  39364. */
  39365. virtual void closeButtonPressed();
  39366. /** Callback that is triggered when the minimise button is pressed.
  39367. The default implementation of this calls ResizableWindow::setMinimised(), but
  39368. you can override it to do more customised behaviour.
  39369. */
  39370. virtual void minimiseButtonPressed();
  39371. /** Callback that is triggered when the maximise button is pressed, or when the
  39372. title-bar is double-clicked.
  39373. The default implementation of this calls ResizableWindow::setFullScreen(), but
  39374. you can override it to do more customised behaviour.
  39375. */
  39376. virtual void maximiseButtonPressed();
  39377. /** Returns the close button, (or 0 if there isn't one). */
  39378. Button* getCloseButton() const throw();
  39379. /** Returns the minimise button, (or 0 if there isn't one). */
  39380. Button* getMinimiseButton() const throw();
  39381. /** Returns the maximise button, (or 0 if there isn't one). */
  39382. Button* getMaximiseButton() const throw();
  39383. /** A set of colour IDs to use to change the colour of various aspects of the window.
  39384. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39385. methods.
  39386. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39387. */
  39388. enum ColourIds
  39389. {
  39390. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  39391. and feel class how this is used. */
  39392. };
  39393. /** @internal */
  39394. void paint (Graphics& g);
  39395. /** @internal */
  39396. void resized();
  39397. /** @internal */
  39398. void lookAndFeelChanged();
  39399. /** @internal */
  39400. const BorderSize getBorderThickness();
  39401. /** @internal */
  39402. const BorderSize getContentComponentBorder();
  39403. /** @internal */
  39404. void mouseDoubleClick (const MouseEvent& e);
  39405. /** @internal */
  39406. void userTriedToCloseWindow();
  39407. /** @internal */
  39408. void activeWindowStatusChanged();
  39409. /** @internal */
  39410. int getDesktopWindowStyleFlags() const;
  39411. /** @internal */
  39412. void parentHierarchyChanged();
  39413. /** @internal */
  39414. const Rectangle<int> getTitleBarArea();
  39415. juce_UseDebuggingNewOperator
  39416. private:
  39417. int titleBarHeight, menuBarHeight, requiredButtons;
  39418. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  39419. ScopedPointer <Button> titleBarButtons [3];
  39420. Image titleBarIcon;
  39421. ScopedPointer <MenuBarComponent> menuBar;
  39422. MenuBarModel* menuBarModel;
  39423. class ButtonListenerProxy;
  39424. friend class ScopedPointer <ButtonListenerProxy>;
  39425. ScopedPointer <ButtonListenerProxy> buttonListener;
  39426. void repaintTitleBar();
  39427. DocumentWindow (const DocumentWindow&);
  39428. DocumentWindow& operator= (const DocumentWindow&);
  39429. };
  39430. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39431. /*** End of inlined file: juce_DocumentWindow.h ***/
  39432. class MultiDocumentPanel;
  39433. class MDITabbedComponentInternal;
  39434. /**
  39435. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  39436. component.
  39437. It's like a normal DocumentWindow but has some extra functionality to make sure
  39438. everything works nicely inside a MultiDocumentPanel.
  39439. @see MultiDocumentPanel
  39440. */
  39441. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  39442. {
  39443. public:
  39444. /**
  39445. */
  39446. MultiDocumentPanelWindow (const Colour& backgroundColour);
  39447. /** Destructor. */
  39448. ~MultiDocumentPanelWindow();
  39449. /** @internal */
  39450. void maximiseButtonPressed();
  39451. /** @internal */
  39452. void closeButtonPressed();
  39453. /** @internal */
  39454. void activeWindowStatusChanged();
  39455. /** @internal */
  39456. void broughtToFront();
  39457. juce_UseDebuggingNewOperator
  39458. private:
  39459. void updateOrder();
  39460. MultiDocumentPanel* getOwner() const throw();
  39461. };
  39462. /**
  39463. A component that contains a set of other components either in floating windows
  39464. or tabs.
  39465. This acts as a panel that can be used to hold a set of open document windows, with
  39466. different layout modes.
  39467. Use addDocument() and closeDocument() to add or remove components from the
  39468. panel - never use any of the Component methods to access the panel's child
  39469. components directly, as these are managed internally.
  39470. */
  39471. class JUCE_API MultiDocumentPanel : public Component,
  39472. private ComponentListener
  39473. {
  39474. public:
  39475. /** Creates an empty panel.
  39476. Use addDocument() and closeDocument() to add or remove components from the
  39477. panel - never use any of the Component methods to access the panel's child
  39478. components directly, as these are managed internally.
  39479. */
  39480. MultiDocumentPanel();
  39481. /** Destructor.
  39482. When deleted, this will call closeAllDocuments (false) to make sure all its
  39483. components are deleted. If you need to make sure all documents are saved
  39484. before closing, then you should call closeAllDocuments (true) and check that
  39485. it returns true before deleting the panel.
  39486. */
  39487. ~MultiDocumentPanel();
  39488. /** Tries to close all the documents.
  39489. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39490. be called for each open document, and any of these calls fails, this method
  39491. will stop and return false, leaving some documents still open.
  39492. If checkItsOkToCloseFirst is false, then all documents will be closed
  39493. unconditionally.
  39494. @see closeDocument
  39495. */
  39496. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  39497. /** Adds a document component to the panel.
  39498. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  39499. this will fail and return false. (If it does fail, the component passed-in will not be
  39500. deleted, even if deleteWhenRemoved was set to true).
  39501. The MultiDocumentPanel will deal with creating a window border to go around your component,
  39502. so just pass in the bare content component here, no need to give it a ResizableWindow
  39503. or DocumentWindow.
  39504. @param component the component to add
  39505. @param backgroundColour the background colour to use to fill the component's
  39506. window or tab
  39507. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  39508. or closeAllDocuments(), then it will be deleted. If false, then
  39509. the caller must handle the component's deletion
  39510. */
  39511. bool addDocument (Component* component,
  39512. const Colour& backgroundColour,
  39513. bool deleteWhenRemoved);
  39514. /** Closes one of the documents.
  39515. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39516. be called, and if it fails, this method will return false without closing the
  39517. document.
  39518. If checkItsOkToCloseFirst is false, then the documents will be closed
  39519. unconditionally.
  39520. The component will be deleted if the deleteWhenRemoved parameter was set to
  39521. true when it was added with addDocument.
  39522. @see addDocument, closeAllDocuments
  39523. */
  39524. bool closeDocument (Component* component,
  39525. bool checkItsOkToCloseFirst);
  39526. /** Returns the number of open document windows.
  39527. @see getDocument
  39528. */
  39529. int getNumDocuments() const throw();
  39530. /** Returns one of the open documents.
  39531. The order of the documents in this array may change when they are added, removed
  39532. or moved around.
  39533. @see getNumDocuments
  39534. */
  39535. Component* getDocument (int index) const throw();
  39536. /** Returns the document component that is currently focused or on top.
  39537. If currently using floating windows, then this will be the component in the currently
  39538. active window, or the top component if none are active.
  39539. If it's currently in tabbed mode, then it'll return the component in the active tab.
  39540. @see setActiveDocument
  39541. */
  39542. Component* getActiveDocument() const throw();
  39543. /** Makes one of the components active and brings it to the top.
  39544. @see getActiveDocument
  39545. */
  39546. void setActiveDocument (Component* component);
  39547. /** Callback which gets invoked when the currently-active document changes. */
  39548. virtual void activeDocumentChanged();
  39549. /** Sets a limit on how many windows can be open at once.
  39550. If this is zero or less there's no limit (the default). addDocument() will fail
  39551. if this number is exceeded.
  39552. */
  39553. void setMaximumNumDocuments (int maximumNumDocuments);
  39554. /** Sets an option to make the document fullscreen if there's only one document open.
  39555. If set to true, then if there's only one document, it'll fill the whole of this
  39556. component without tabs or a window border. If false, then tabs or a window
  39557. will always be shown, even if there's only one document. If there's more than
  39558. one document open, then this option makes no difference.
  39559. */
  39560. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  39561. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  39562. */
  39563. bool isFullscreenWhenOneDocument() const throw();
  39564. /** The different layout modes available. */
  39565. enum LayoutMode
  39566. {
  39567. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  39568. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  39569. };
  39570. /** Changes the panel's mode.
  39571. @see LayoutMode, getLayoutMode
  39572. */
  39573. void setLayoutMode (LayoutMode newLayoutMode);
  39574. /** Returns the current layout mode. */
  39575. LayoutMode getLayoutMode() const throw() { return mode; }
  39576. /** Sets the background colour for the whole panel.
  39577. Each document has its own background colour, but this is the one used to fill the areas
  39578. behind them.
  39579. */
  39580. void setBackgroundColour (const Colour& newBackgroundColour);
  39581. /** Returns the current background colour.
  39582. @see setBackgroundColour
  39583. */
  39584. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  39585. /** A subclass must override this to say whether its currently ok for a document
  39586. to be closed.
  39587. This method is called by closeDocument() and closeAllDocuments() to indicate that
  39588. a document should be saved if possible, ready for it to be closed.
  39589. If this method returns true, then it means the document is ok and can be closed.
  39590. If it returns false, then it means that the closeDocument() method should stop
  39591. and not close.
  39592. Normally, you'd use this method to ask the user if they want to save any changes,
  39593. then return true if the save operation went ok. If the user cancelled the save
  39594. operation you could return false here to abort the close operation.
  39595. If your component is based on the FileBasedDocument class, then you'd probably want
  39596. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  39597. FileBasedDocument::savedOk
  39598. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  39599. */
  39600. virtual bool tryToCloseDocument (Component* component) = 0;
  39601. /** Creates a new window to be used for a document.
  39602. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  39603. but you might want to override it to return a custom component.
  39604. */
  39605. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  39606. /** @internal */
  39607. void paint (Graphics& g);
  39608. /** @internal */
  39609. void resized();
  39610. /** @internal */
  39611. void componentNameChanged (Component&);
  39612. juce_UseDebuggingNewOperator
  39613. private:
  39614. LayoutMode mode;
  39615. Array <Component*> components;
  39616. TabbedComponent* tabComponent;
  39617. Colour backgroundColour;
  39618. int maximumNumDocuments, numDocsBeforeTabsUsed;
  39619. friend class MultiDocumentPanelWindow;
  39620. friend class MDITabbedComponentInternal;
  39621. Component* getContainerComp (Component* c) const;
  39622. void updateOrder();
  39623. void addWindow (Component* component);
  39624. };
  39625. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  39626. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  39627. #endif
  39628. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39629. #endif
  39630. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39631. #endif
  39632. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  39633. #endif
  39634. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39635. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  39636. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39637. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39638. /**
  39639. For laying out a set of components, where the components have preferred sizes
  39640. and size limits, but where they are allowed to stretch to fill the available
  39641. space.
  39642. For example, if you have a component containing several other components, and
  39643. each one should be given a share of the total size, you could use one of these
  39644. to resize the child components when the parent component is resized. Then
  39645. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  39646. A StretchableLayoutManager operates only in one dimension, so if you have a set
  39647. of components stacked vertically on top of each other, you'd use one to manage their
  39648. heights. To build up complex arrangements of components, e.g. for applications
  39649. with multiple nested panels, you would use more than one StretchableLayoutManager.
  39650. E.g. by using two (one vertical, one horizontal), you could create a resizable
  39651. spreadsheet-style table.
  39652. E.g.
  39653. @code
  39654. class MyComp : public Component
  39655. {
  39656. StretchableLayoutManager myLayout;
  39657. MyComp()
  39658. {
  39659. myLayout.setItemLayout (0, // for item 0
  39660. 50, 100, // must be between 50 and 100 pixels in size
  39661. -0.6); // and its preferred size is 60% of the total available space
  39662. myLayout.setItemLayout (1, // for item 1
  39663. -0.2, -0.6, // size must be between 20% and 60% of the available space
  39664. 50); // and its preferred size is 50 pixels
  39665. }
  39666. void resized()
  39667. {
  39668. // make a list of two of our child components that we want to reposition
  39669. Component* comps[] = { myComp1, myComp2 };
  39670. // this will position the 2 components, one above the other, to fit
  39671. // vertically into the rectangle provided.
  39672. myLayout.layOutComponents (comps, 2,
  39673. 0, 0, getWidth(), getHeight(),
  39674. true);
  39675. }
  39676. };
  39677. @endcode
  39678. @see StretchableLayoutResizerBar
  39679. */
  39680. class JUCE_API StretchableLayoutManager
  39681. {
  39682. public:
  39683. /** Creates an empty layout.
  39684. You'll need to add some item properties to the layout before it can be used
  39685. to resize things - see setItemLayout().
  39686. */
  39687. StretchableLayoutManager();
  39688. /** Destructor. */
  39689. ~StretchableLayoutManager();
  39690. /** For a numbered item, this sets its size limits and preferred size.
  39691. @param itemIndex the index of the item to change.
  39692. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39693. indicates an absolute size in pixels. A negative number indicates a
  39694. proportion of the available space (e.g -0.5 is 50%)
  39695. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39696. indicates an absolute size in pixels. A negative number indicates a
  39697. proportion of the available space
  39698. @param preferredSize the size that this item would like to be, if there's enough room. A
  39699. positive number indicates an absolute size in pixels. A negative number
  39700. indicates a proportion of the available space
  39701. @see getItemLayout
  39702. */
  39703. void setItemLayout (int itemIndex,
  39704. double minimumSize,
  39705. double maximumSize,
  39706. double preferredSize);
  39707. /** For a numbered item, this returns its size limits and preferred size.
  39708. @param itemIndex the index of the item.
  39709. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39710. indicates an absolute size in pixels. A negative number indicates a
  39711. proportion of the available space (e.g -0.5 is 50%)
  39712. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39713. indicates an absolute size in pixels. A negative number indicates a
  39714. proportion of the available space
  39715. @param preferredSize the size that this item would like to be, if there's enough room. A
  39716. positive number indicates an absolute size in pixels. A negative number
  39717. indicates a proportion of the available space
  39718. @returns false if the item's properties hadn't been set
  39719. @see setItemLayout
  39720. */
  39721. bool getItemLayout (int itemIndex,
  39722. double& minimumSize,
  39723. double& maximumSize,
  39724. double& preferredSize) const;
  39725. /** Clears all the properties that have been set with setItemLayout() and resets
  39726. this object to its initial state.
  39727. */
  39728. void clearAllItems();
  39729. /** Takes a set of components that correspond to the layout's items, and positions
  39730. them to fill a space.
  39731. This will try to give each item its preferred size, whether that's a relative size
  39732. or an absolute one.
  39733. @param components an array of components that correspond to each of the
  39734. numbered items that the StretchableLayoutManager object
  39735. has been told about with setItemLayout()
  39736. @param numComponents the number of components in the array that is passed-in. This
  39737. should be the same as the number of items this object has been
  39738. told about.
  39739. @param x the left of the rectangle in which the components should
  39740. be laid out
  39741. @param y the top of the rectangle in which the components should
  39742. be laid out
  39743. @param width the width of the rectangle in which the components should
  39744. be laid out
  39745. @param height the height of the rectangle in which the components should
  39746. be laid out
  39747. @param vertically if true, the components will be positioned in a vertical stack,
  39748. so that they fill the height of the rectangle. If false, they
  39749. will be placed side-by-side in a horizontal line, filling the
  39750. available width
  39751. @param resizeOtherDimension if true, this means that the components will have their
  39752. other dimension resized to fit the space - i.e. if the 'vertically'
  39753. parameter is true, their x-positions and widths are adjusted to fit
  39754. the x and width parameters; if 'vertically' is false, their y-positions
  39755. and heights are adjusted to fit the y and height parameters.
  39756. */
  39757. void layOutComponents (Component** components,
  39758. int numComponents,
  39759. int x, int y, int width, int height,
  39760. bool vertically,
  39761. bool resizeOtherDimension);
  39762. /** Returns the current position of one of the items.
  39763. This is only a valid call after layOutComponents() has been called, as it
  39764. returns the last position that this item was placed at. If the layout was
  39765. vertical, the value returned will be the y position of the top of the item,
  39766. relative to the top of the rectangle in which the items were placed (so for
  39767. example, item 0 will always have position of 0, even in the rectangle passed
  39768. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  39769. the position returned is the item's left-hand position, again relative to the
  39770. x position of the rectangle used.
  39771. @see getItemCurrentSize, setItemPosition
  39772. */
  39773. int getItemCurrentPosition (int itemIndex) const;
  39774. /** Returns the current size of one of the items.
  39775. This is only meaningful after layOutComponents() has been called, as it
  39776. returns the last size that this item was given. If the layout was done
  39777. vertically, it'll return the item's height in pixels; if it was horizontal,
  39778. it'll return its width.
  39779. @see getItemCurrentRelativeSize
  39780. */
  39781. int getItemCurrentAbsoluteSize (int itemIndex) const;
  39782. /** Returns the current size of one of the items.
  39783. This is only meaningful after layOutComponents() has been called, as it
  39784. returns the last size that this item was given. If the layout was done
  39785. vertically, it'll return a negative value representing the item's height relative
  39786. to the last size used for laying the components out; if the layout was done
  39787. horizontally it'll be the proportion of its width.
  39788. @see getItemCurrentAbsoluteSize
  39789. */
  39790. double getItemCurrentRelativeSize (int itemIndex) const;
  39791. /** Moves one of the items, shifting along any other items as necessary in
  39792. order to get it to the desired position.
  39793. Calling this method will also update the preferred sizes of the items it
  39794. shuffles along, so that they reflect their new positions.
  39795. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  39796. about when it's dragged).
  39797. @param itemIndex the item to move
  39798. @param newPosition the absolute position that you'd like this item to move
  39799. to. The item might not be able to always reach exactly this position,
  39800. because other items may have minimum sizes that constrain how
  39801. far it can go
  39802. */
  39803. void setItemPosition (int itemIndex,
  39804. int newPosition);
  39805. juce_UseDebuggingNewOperator
  39806. private:
  39807. struct ItemLayoutProperties
  39808. {
  39809. int itemIndex;
  39810. int currentSize;
  39811. double minSize, maxSize, preferredSize;
  39812. };
  39813. OwnedArray <ItemLayoutProperties> items;
  39814. int totalSize;
  39815. static int sizeToRealSize (double size, int totalSpace);
  39816. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  39817. void setTotalSize (int newTotalSize);
  39818. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  39819. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  39820. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  39821. void updatePrefSizesToMatchCurrentPositions();
  39822. StretchableLayoutManager (const StretchableLayoutManager&);
  39823. StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  39824. };
  39825. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39826. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  39827. #endif
  39828. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39829. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39830. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39831. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39832. /**
  39833. A component that acts as one of the vertical or horizontal bars you see being
  39834. used to resize panels in a window.
  39835. One of these acts with a StretchableLayoutManager to resize the other components.
  39836. @see StretchableLayoutManager
  39837. */
  39838. class JUCE_API StretchableLayoutResizerBar : public Component
  39839. {
  39840. public:
  39841. /** Creates a resizer bar for use on a specified layout.
  39842. @param layoutToUse the layout that will be affected when this bar
  39843. is dragged
  39844. @param itemIndexInLayout the item index in the layout that corresponds to
  39845. this bar component. You'll need to set up the item
  39846. properties in a suitable way for a divider bar, e.g.
  39847. for an 8-pixel wide bar which, you could call
  39848. myLayout->setItemLayout (barIndex, 8, 8, 8)
  39849. @param isBarVertical true if it's an upright bar that you drag left and
  39850. right; false for a horizontal one that you drag up and
  39851. down
  39852. */
  39853. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  39854. int itemIndexInLayout,
  39855. bool isBarVertical);
  39856. /** Destructor. */
  39857. ~StretchableLayoutResizerBar();
  39858. /** This is called when the bar is dragged.
  39859. This method must update the positions of any components whose position is
  39860. determined by the StretchableLayoutManager, because they might have just
  39861. moved.
  39862. The default implementation calls the resized() method of this component's
  39863. parent component, because that's often where you're likely to apply the
  39864. layout, but it can be overridden for more specific needs.
  39865. */
  39866. virtual void hasBeenMoved();
  39867. /** @internal */
  39868. void paint (Graphics& g);
  39869. /** @internal */
  39870. void mouseDown (const MouseEvent& e);
  39871. /** @internal */
  39872. void mouseDrag (const MouseEvent& e);
  39873. juce_UseDebuggingNewOperator
  39874. private:
  39875. StretchableLayoutManager* layout;
  39876. int itemIndex, mouseDownPos;
  39877. bool isVertical;
  39878. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  39879. StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  39880. };
  39881. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39882. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39883. #endif
  39884. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39885. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  39886. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39887. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39888. /**
  39889. A utility class for fitting a set of objects whose sizes can vary between
  39890. a minimum and maximum size, into a space.
  39891. This is a trickier algorithm than it would first seem, so I've put it in this
  39892. class to allow it to be shared by various bits of code.
  39893. To use it, create one of these objects, call addItem() to add the list of items
  39894. you need, then call resizeToFit(), which will change all their sizes. You can
  39895. then retrieve the new sizes with getItemSize() and getNumItems().
  39896. It's currently used by the TableHeaderComponent for stretching out the table
  39897. headings to fill the table's width.
  39898. */
  39899. class StretchableObjectResizer
  39900. {
  39901. public:
  39902. /** Creates an empty object resizer. */
  39903. StretchableObjectResizer();
  39904. /** Destructor. */
  39905. ~StretchableObjectResizer();
  39906. /** Adds an item to the list.
  39907. The order parameter lets you specify groups of items that are resized first when some
  39908. space needs to be found. Those items with an order of 0 will be the first ones to be
  39909. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  39910. will then try resizing the items with an order of 1, then 2, and so on.
  39911. */
  39912. void addItem (double currentSize,
  39913. double minSize,
  39914. double maxSize,
  39915. int order = 0);
  39916. /** Resizes all the items to fit this amount of space.
  39917. This will attempt to fit them in without exceeding each item's miniumum and
  39918. maximum sizes. In cases where none of the items can be expanded or enlarged any
  39919. further, the final size may be greater or less than the size passed in.
  39920. After calling this method, you can retrieve the new sizes with the getItemSize()
  39921. method.
  39922. */
  39923. void resizeToFit (double targetSize);
  39924. /** Returns the number of items that have been added. */
  39925. int getNumItems() const throw() { return items.size(); }
  39926. /** Returns the size of one of the items. */
  39927. double getItemSize (int index) const throw();
  39928. juce_UseDebuggingNewOperator
  39929. private:
  39930. struct Item
  39931. {
  39932. double size;
  39933. double minSize;
  39934. double maxSize;
  39935. int order;
  39936. };
  39937. OwnedArray <Item> items;
  39938. StretchableObjectResizer (const StretchableObjectResizer&);
  39939. StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  39940. };
  39941. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39942. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  39943. #endif
  39944. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  39945. #endif
  39946. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  39947. #endif
  39948. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  39949. #endif
  39950. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39951. /*** Start of inlined file: juce_LookAndFeel.h ***/
  39952. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39953. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39954. /*** Start of inlined file: juce_AlertWindow.h ***/
  39955. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  39956. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  39957. /*** Start of inlined file: juce_TextLayout.h ***/
  39958. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  39959. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  39960. class Graphics;
  39961. /**
  39962. A laid-out arrangement of text.
  39963. You can add text in different fonts to a TextLayout object, then call its
  39964. layout() method to word-wrap it into lines. The layout can then be drawn
  39965. using a graphics context.
  39966. It's handy if you've got a message to display, because you can format it,
  39967. measure the extent of the layout, and then create a suitably-sized window
  39968. to show it in.
  39969. @see Font, Graphics::drawFittedText, GlyphArrangement
  39970. */
  39971. class JUCE_API TextLayout
  39972. {
  39973. public:
  39974. /** Creates an empty text layout.
  39975. Text can then be appended using the appendText() method.
  39976. */
  39977. TextLayout();
  39978. /** Creates a copy of another layout object. */
  39979. TextLayout (const TextLayout& other);
  39980. /** Creates a text layout from an initial string and font. */
  39981. TextLayout (const String& text, const Font& font);
  39982. /** Destructor. */
  39983. ~TextLayout();
  39984. /** Copies another layout onto this one. */
  39985. TextLayout& operator= (const TextLayout& layoutToCopy);
  39986. /** Clears the layout, removing all its text. */
  39987. void clear();
  39988. /** Adds a string to the end of the arrangement.
  39989. The string will be broken onto new lines wherever it contains
  39990. carriage-returns or linefeeds. After adding it, you can call layout()
  39991. to wrap long lines into a paragraph and justify it.
  39992. */
  39993. void appendText (const String& textToAppend,
  39994. const Font& fontToUse);
  39995. /** Replaces all the text with a new string.
  39996. This is equivalent to calling clear() followed by appendText().
  39997. */
  39998. void setText (const String& newText,
  39999. const Font& fontToUse);
  40000. /** Breaks the text up to form a paragraph with the given width.
  40001. @param maximumWidth any text wider than this will be split
  40002. across multiple lines
  40003. @param justification how the lines are to be laid-out horizontally
  40004. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  40005. width that keeps all the lines of text at a
  40006. similar length - this is good when you're displaying
  40007. a short message and don't want it to get split
  40008. onto two lines with only a couple of words on
  40009. the second line, which looks untidy.
  40010. */
  40011. void layout (int maximumWidth,
  40012. const Justification& justification,
  40013. bool attemptToBalanceLineLengths);
  40014. /** Returns the overall width of the entire text layout. */
  40015. int getWidth() const;
  40016. /** Returns the overall height of the entire text layout. */
  40017. int getHeight() const;
  40018. /** Returns the total number of lines of text. */
  40019. int getNumLines() const { return totalLines; }
  40020. /** Returns the width of a particular line of text.
  40021. @param lineNumber the line, from 0 to (getNumLines() - 1)
  40022. */
  40023. int getLineWidth (int lineNumber) const;
  40024. /** Renders the text at a specified position using a graphics context.
  40025. */
  40026. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  40027. /** Renders the text within a specified rectangle using a graphics context.
  40028. The justification flags dictate how the block of text should be positioned
  40029. within the rectangle.
  40030. */
  40031. void drawWithin (Graphics& g,
  40032. int x, int y, int w, int h,
  40033. const Justification& layoutFlags) const;
  40034. juce_UseDebuggingNewOperator
  40035. private:
  40036. class Token;
  40037. friend class OwnedArray <Token>;
  40038. OwnedArray <Token> tokens;
  40039. int totalLines;
  40040. };
  40041. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  40042. /*** End of inlined file: juce_TextLayout.h ***/
  40043. /** A window that displays a message and has buttons for the user to react to it.
  40044. For simple dialog boxes with just a couple of buttons on them, there are
  40045. some static methods for running these.
  40046. For more complex dialogs, an AlertWindow can be created, then it can have some
  40047. buttons and components added to it, and its runModalLoop() method is then used to
  40048. show it. The value returned by runModalLoop() shows which button the
  40049. user pressed to dismiss the box.
  40050. @see ThreadWithProgressWindow
  40051. */
  40052. class JUCE_API AlertWindow : public TopLevelWindow,
  40053. private ButtonListener
  40054. {
  40055. public:
  40056. /** The type of icon to show in the dialog box. */
  40057. enum AlertIconType
  40058. {
  40059. NoIcon, /**< No icon will be shown on the dialog box. */
  40060. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  40061. user to answer a question. */
  40062. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  40063. warning about something and shouldn't be ignored. */
  40064. InfoIcon /**< An icon that indicates that the dialog box is just
  40065. giving the user some information, which doesn't require
  40066. a response from them. */
  40067. };
  40068. /** Creates an AlertWindow.
  40069. @param title the headline to show at the top of the dialog box
  40070. @param message a longer, more descriptive message to show underneath the
  40071. headline
  40072. @param iconType the type of icon to display
  40073. @param associatedComponent if this is non-zero, it specifies the component that the
  40074. alert window should be associated with. Depending on the look
  40075. and feel, this might be used for positioning of the alert window.
  40076. */
  40077. AlertWindow (const String& title,
  40078. const String& message,
  40079. AlertIconType iconType,
  40080. Component* associatedComponent = 0);
  40081. /** Destroys the AlertWindow */
  40082. ~AlertWindow();
  40083. /** Returns the type of alert icon that was specified when the window
  40084. was created. */
  40085. AlertIconType getAlertType() const throw() { return alertIconType; }
  40086. /** Changes the dialog box's message.
  40087. This will also resize the window to fit the new message if required.
  40088. */
  40089. void setMessage (const String& message);
  40090. /** Adds a button to the window.
  40091. @param name the text to show on the button
  40092. @param returnValue the value that should be returned from runModalLoop()
  40093. if this is the button that the user presses.
  40094. @param shortcutKey1 an optional key that can be pressed to trigger this button
  40095. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  40096. */
  40097. void addButton (const String& name,
  40098. int returnValue,
  40099. const KeyPress& shortcutKey1 = KeyPress(),
  40100. const KeyPress& shortcutKey2 = KeyPress());
  40101. /** Returns the number of buttons that the window currently has. */
  40102. int getNumButtons() const;
  40103. /** Invokes a click of one of the buttons. */
  40104. void triggerButtonClick (const String& buttonName);
  40105. /** Adds a textbox to the window for entering strings.
  40106. @param name an internal name for the text-box. This is the name to pass to
  40107. the getTextEditorContents() method to find out what the
  40108. user typed-in.
  40109. @param initialContents a string to show in the text box when it's first shown
  40110. @param onScreenLabel if this is non-empty, it will be displayed next to the
  40111. text-box to label it.
  40112. @param isPasswordBox if true, the text editor will display asterisks instead of
  40113. the actual text
  40114. @see getTextEditorContents
  40115. */
  40116. void addTextEditor (const String& name,
  40117. const String& initialContents,
  40118. const String& onScreenLabel = String::empty,
  40119. bool isPasswordBox = false);
  40120. /** Returns the contents of a named textbox.
  40121. After showing an AlertWindow that contains a text editor, this can be
  40122. used to find out what the user has typed into it.
  40123. @param nameOfTextEditor the name of the text box that you're interested in
  40124. @see addTextEditor
  40125. */
  40126. const String getTextEditorContents (const String& nameOfTextEditor) const;
  40127. /** Adds a drop-down list of choices to the box.
  40128. After the box has been shown, the getComboBoxComponent() method can
  40129. be used to find out which item the user picked.
  40130. @param name the label to use for the drop-down list
  40131. @param items the list of items to show in it
  40132. @param onScreenLabel if this is non-empty, it will be displayed next to the
  40133. combo-box to label it.
  40134. @see getComboBoxComponent
  40135. */
  40136. void addComboBox (const String& name,
  40137. const StringArray& items,
  40138. const String& onScreenLabel = String::empty);
  40139. /** Returns a drop-down list that was added to the AlertWindow.
  40140. @param nameOfList the name that was passed into the addComboBox() method
  40141. when creating the drop-down
  40142. @returns the ComboBox component, or 0 if none was found for the given name.
  40143. */
  40144. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  40145. /** Adds a block of text.
  40146. This is handy for adding a multi-line note next to a textbox or combo-box,
  40147. to provide more details about what's going on.
  40148. */
  40149. void addTextBlock (const String& text);
  40150. /** Adds a progress-bar to the window.
  40151. @param progressValue a variable that will be repeatedly checked while the
  40152. dialog box is visible, to see how far the process has
  40153. got. The value should be in the range 0 to 1.0
  40154. */
  40155. void addProgressBarComponent (double& progressValue);
  40156. /** Adds a user-defined component to the dialog box.
  40157. @param component the component to add - its size should be set up correctly
  40158. before it is passed in. The caller is responsible for deleting
  40159. the component later on - the AlertWindow won't delete it.
  40160. */
  40161. void addCustomComponent (Component* component);
  40162. /** Returns the number of custom components in the dialog box.
  40163. @see getCustomComponent, addCustomComponent
  40164. */
  40165. int getNumCustomComponents() const;
  40166. /** Returns one of the custom components in the dialog box.
  40167. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  40168. will return 0
  40169. @see getNumCustomComponents, addCustomComponent
  40170. */
  40171. Component* getCustomComponent (int index) const;
  40172. /** Removes one of the custom components in the dialog box.
  40173. Note that this won't delete it, it just removes the component from the window
  40174. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  40175. will return 0
  40176. @returns the component that was removed (or zero)
  40177. @see getNumCustomComponents, addCustomComponent
  40178. */
  40179. Component* removeCustomComponent (int index);
  40180. /** Returns true if the window contains any components other than just buttons.*/
  40181. bool containsAnyExtraComponents() const;
  40182. // easy-to-use message box functions:
  40183. /** Shows a dialog box that just has a message and a single button to get rid of it.
  40184. The box is shown modally, and the method returns after the user
  40185. has clicked the button (or pressed the escape or return keys).
  40186. @param iconType the type of icon to show
  40187. @param title the headline to show at the top of the box
  40188. @param message a longer, more descriptive message to show underneath the
  40189. headline
  40190. @param buttonText the text to show in the button - if this string is empty, the
  40191. default string "ok" (or a localised version) will be used.
  40192. @param associatedComponent if this is non-zero, it specifies the component that the
  40193. alert window should be associated with. Depending on the look
  40194. and feel, this might be used for positioning of the alert window.
  40195. */
  40196. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  40197. const String& title,
  40198. const String& message,
  40199. const String& buttonText = String::empty,
  40200. Component* associatedComponent = 0);
  40201. /** Shows a dialog box with two buttons.
  40202. Ideal for ok/cancel or yes/no choices. The return key can also be used
  40203. to trigger the first button, and the escape key for the second button.
  40204. @param iconType the type of icon to show
  40205. @param title the headline to show at the top of the box
  40206. @param message a longer, more descriptive message to show underneath the
  40207. headline
  40208. @param button1Text the text to show in the first button - if this string is
  40209. empty, the default string "ok" (or a localised version of it)
  40210. will be used.
  40211. @param button2Text the text to show in the second button - if this string is
  40212. empty, the default string "cancel" (or a localised version of it)
  40213. will be used.
  40214. @param associatedComponent if this is non-zero, it specifies the component that the
  40215. alert window should be associated with. Depending on the look
  40216. and feel, this might be used for positioning of the alert window.
  40217. @returns true if button 1 was clicked, false if it was button 2
  40218. */
  40219. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  40220. const String& title,
  40221. const String& message,
  40222. const String& button1Text = String::empty,
  40223. const String& button2Text = String::empty,
  40224. Component* associatedComponent = 0);
  40225. /** Shows a dialog box with three buttons.
  40226. Ideal for yes/no/cancel boxes.
  40227. The escape key can be used to trigger the third button.
  40228. @param iconType the type of icon to show
  40229. @param title the headline to show at the top of the box
  40230. @param message a longer, more descriptive message to show underneath the
  40231. headline
  40232. @param button1Text the text to show in the first button - if an empty string, then
  40233. "yes" will be used (or a localised version of it)
  40234. @param button2Text the text to show in the first button - if an empty string, then
  40235. "no" will be used (or a localised version of it)
  40236. @param button3Text the text to show in the first button - if an empty string, then
  40237. "cancel" will be used (or a localised version of it)
  40238. @param associatedComponent if this is non-zero, it specifies the component that the
  40239. alert window should be associated with. Depending on the look
  40240. and feel, this might be used for positioning of the alert window.
  40241. @returns one of the following values:
  40242. - 0 if the third button was pressed (normally used for 'cancel')
  40243. - 1 if the first button was pressed (normally used for 'yes')
  40244. - 2 if the middle button was pressed (normally used for 'no')
  40245. */
  40246. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  40247. const String& title,
  40248. const String& message,
  40249. const String& button1Text = String::empty,
  40250. const String& button2Text = String::empty,
  40251. const String& button3Text = String::empty,
  40252. Component* associatedComponent = 0);
  40253. /** Shows an operating-system native dialog box.
  40254. @param title the title to use at the top
  40255. @param bodyText the longer message to show
  40256. @param isOkCancel if true, this will show an ok/cancel box, if false,
  40257. it'll show a box with just an ok button
  40258. @returns true if the ok button was pressed, false if they pressed cancel.
  40259. */
  40260. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  40261. const String& bodyText,
  40262. bool isOkCancel);
  40263. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  40264. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40265. methods.
  40266. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40267. */
  40268. enum ColourIds
  40269. {
  40270. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  40271. textColourId = 0x1001810, /**< The colour for the text. */
  40272. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  40273. };
  40274. juce_UseDebuggingNewOperator
  40275. protected:
  40276. /** @internal */
  40277. void paint (Graphics& g);
  40278. /** @internal */
  40279. void mouseDown (const MouseEvent& e);
  40280. /** @internal */
  40281. void mouseDrag (const MouseEvent& e);
  40282. /** @internal */
  40283. bool keyPressed (const KeyPress& key);
  40284. /** @internal */
  40285. void buttonClicked (Button* button);
  40286. /** @internal */
  40287. void lookAndFeelChanged();
  40288. /** @internal */
  40289. void userTriedToCloseWindow();
  40290. /** @internal */
  40291. int getDesktopWindowStyleFlags() const;
  40292. private:
  40293. String text;
  40294. TextLayout textLayout;
  40295. AlertIconType alertIconType;
  40296. ComponentBoundsConstrainer constrainer;
  40297. ComponentDragger dragger;
  40298. Rectangle<int> textArea;
  40299. Array<void*> buttons, textBoxes, comboBoxes;
  40300. Array<void*> progressBars, customComps, textBlocks, allComps;
  40301. StringArray textboxNames, comboBoxNames;
  40302. Font font;
  40303. Component* associatedComponent;
  40304. void updateLayout (bool onlyIncreaseSize);
  40305. // disable copy constructor
  40306. AlertWindow (const AlertWindow&);
  40307. AlertWindow& operator= (const AlertWindow&);
  40308. };
  40309. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  40310. /*** End of inlined file: juce_AlertWindow.h ***/
  40311. class ToggleButton;
  40312. class TextButton;
  40313. class AlertWindow;
  40314. class TextLayout;
  40315. class ScrollBar;
  40316. class BubbleComponent;
  40317. class ComboBox;
  40318. class Button;
  40319. class FilenameComponent;
  40320. class DocumentWindow;
  40321. class ResizableWindow;
  40322. class GroupComponent;
  40323. class MenuBarComponent;
  40324. class DropShadower;
  40325. class GlyphArrangement;
  40326. class PropertyComponent;
  40327. class TableHeaderComponent;
  40328. class Toolbar;
  40329. class ToolbarItemComponent;
  40330. class PopupMenu;
  40331. class ProgressBar;
  40332. class FileBrowserComponent;
  40333. class DirectoryContentsDisplayComponent;
  40334. class FilePreviewComponent;
  40335. class ImageButton;
  40336. class CallOutBox;
  40337. /**
  40338. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  40339. can be used to apply different 'skins' to the application.
  40340. */
  40341. class JUCE_API LookAndFeel
  40342. {
  40343. public:
  40344. /** Creates the default JUCE look and feel. */
  40345. LookAndFeel();
  40346. /** Destructor. */
  40347. virtual ~LookAndFeel();
  40348. /** Returns the current default look-and-feel for a component to use when it
  40349. hasn't got one explicitly set.
  40350. @see setDefaultLookAndFeel
  40351. */
  40352. static LookAndFeel& getDefaultLookAndFeel() throw();
  40353. /** Changes the default look-and-feel.
  40354. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  40355. set to 0, it will revert to using the default one. The
  40356. object passed-in must be deleted by the caller when
  40357. it's no longer needed.
  40358. @see getDefaultLookAndFeel
  40359. */
  40360. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  40361. /** Looks for a colour that has been registered with the given colour ID number.
  40362. If a colour has been set for this ID number using setColour(), then it is
  40363. returned. If none has been set, it will just return Colours::black.
  40364. The colour IDs for various purposes are stored as enums in the components that
  40365. they are relevent to - for an example, see Slider::ColourIds,
  40366. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  40367. If you're looking up a colour for use in drawing a component, it's usually
  40368. best not to call this directly, but to use the Component::findColour() method
  40369. instead. That will first check whether a suitable colour has been registered
  40370. directly with the component, and will fall-back on calling the component's
  40371. LookAndFeel's findColour() method if none is found.
  40372. @see setColour, Component::findColour, Component::setColour
  40373. */
  40374. const Colour findColour (int colourId) const throw();
  40375. /** Registers a colour to be used for a particular purpose.
  40376. For more details, see the comments for findColour().
  40377. @see findColour, Component::findColour, Component::setColour
  40378. */
  40379. void setColour (int colourId, const Colour& colour) throw();
  40380. /** Returns true if the specified colour ID has been explicitly set using the
  40381. setColour() method.
  40382. */
  40383. bool isColourSpecified (int colourId) const throw();
  40384. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  40385. /** Allows you to change the default sans-serif font.
  40386. If you need to supply your own Typeface object for any of the default fonts, rather
  40387. than just supplying the name (e.g. if you want to use an embedded font), then
  40388. you should instead override getTypefaceForFont() to create and return the typeface.
  40389. */
  40390. void setDefaultSansSerifTypefaceName (const String& newName);
  40391. /** Override this to get the chance to swap a component's mouse cursor for a
  40392. customised one.
  40393. */
  40394. virtual const MouseCursor getMouseCursorFor (Component& component);
  40395. /** Draws the lozenge-shaped background for a standard button. */
  40396. virtual void drawButtonBackground (Graphics& g,
  40397. Button& button,
  40398. const Colour& backgroundColour,
  40399. bool isMouseOverButton,
  40400. bool isButtonDown);
  40401. virtual const Font getFontForTextButton (TextButton& button);
  40402. /** Draws the text for a TextButton. */
  40403. virtual void drawButtonText (Graphics& g,
  40404. TextButton& button,
  40405. bool isMouseOverButton,
  40406. bool isButtonDown);
  40407. /** Draws the contents of a standard ToggleButton. */
  40408. virtual void drawToggleButton (Graphics& g,
  40409. ToggleButton& button,
  40410. bool isMouseOverButton,
  40411. bool isButtonDown);
  40412. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  40413. virtual void drawTickBox (Graphics& g,
  40414. Component& component,
  40415. float x, float y, float w, float h,
  40416. bool ticked,
  40417. bool isEnabled,
  40418. bool isMouseOverButton,
  40419. bool isButtonDown);
  40420. /* AlertWindow handling..
  40421. */
  40422. virtual AlertWindow* createAlertWindow (const String& title,
  40423. const String& message,
  40424. const String& button1,
  40425. const String& button2,
  40426. const String& button3,
  40427. AlertWindow::AlertIconType iconType,
  40428. int numButtons,
  40429. Component* associatedComponent);
  40430. virtual void drawAlertBox (Graphics& g,
  40431. AlertWindow& alert,
  40432. const Rectangle<int>& textArea,
  40433. TextLayout& textLayout);
  40434. virtual int getAlertBoxWindowFlags();
  40435. virtual int getAlertWindowButtonHeight();
  40436. virtual const Font getAlertWindowFont();
  40437. /** Draws a progress bar.
  40438. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  40439. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  40440. isn't known). It can use the current time as a basis for playing an animation.
  40441. (Used by progress bars in AlertWindow).
  40442. */
  40443. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40444. int width, int height,
  40445. double progress, const String& textToShow);
  40446. // Draws a small image that spins to indicate that something's happening..
  40447. // This method should use the current time to animate itself, so just keep
  40448. // repainting it every so often.
  40449. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  40450. int x, int y, int w, int h);
  40451. /** Draws one of the buttons on a scrollbar.
  40452. @param g the context to draw into
  40453. @param scrollbar the bar itself
  40454. @param width the width of the button
  40455. @param height the height of the button
  40456. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  40457. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40458. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  40459. @param isButtonDown whether the mouse button's held down
  40460. */
  40461. virtual void drawScrollbarButton (Graphics& g,
  40462. ScrollBar& scrollbar,
  40463. int width, int height,
  40464. int buttonDirection,
  40465. bool isScrollbarVertical,
  40466. bool isMouseOverButton,
  40467. bool isButtonDown);
  40468. /** Draws the thumb area of a scrollbar.
  40469. @param g the context to draw into
  40470. @param scrollbar the bar itself
  40471. @param x the x position of the left edge of the thumb area to draw in
  40472. @param y the y position of the top edge of the thumb area to draw in
  40473. @param width the width of the thumb area to draw in
  40474. @param height the height of the thumb area to draw in
  40475. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40476. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  40477. thumb, or its x position for horizontal bars
  40478. @param thumbSize for vertical bars, the height of the thumb, or its width for
  40479. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  40480. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  40481. currently dragging the thumb
  40482. @param isMouseDown whether the mouse is currently dragging the scrollbar
  40483. */
  40484. virtual void drawScrollbar (Graphics& g,
  40485. ScrollBar& scrollbar,
  40486. int x, int y,
  40487. int width, int height,
  40488. bool isScrollbarVertical,
  40489. int thumbStartPosition,
  40490. int thumbSize,
  40491. bool isMouseOver,
  40492. bool isMouseDown);
  40493. /** Returns the component effect to use for a scrollbar */
  40494. virtual ImageEffectFilter* getScrollbarEffect();
  40495. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  40496. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  40497. /** Returns the default thickness to use for a scrollbar. */
  40498. virtual int getDefaultScrollbarWidth();
  40499. /** Returns the length in pixels to use for a scrollbar button. */
  40500. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  40501. /** Returns a tick shape for use in yes/no boxes, etc. */
  40502. virtual const Path getTickShape (float height);
  40503. /** Returns a cross shape for use in yes/no boxes, etc. */
  40504. virtual const Path getCrossShape (float height);
  40505. /** Draws the + or - box in a treeview. */
  40506. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  40507. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  40508. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  40509. // these return an image from the ImageCache, so use ImageCache::release() to free it
  40510. virtual const Image getDefaultFolderImage();
  40511. virtual const Image getDefaultDocumentFileImage();
  40512. virtual void createFileChooserHeaderText (const String& title,
  40513. const String& instructions,
  40514. GlyphArrangement& destArrangement,
  40515. int width);
  40516. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  40517. const String& filename, Image* icon,
  40518. const String& fileSizeDescription,
  40519. const String& fileTimeDescription,
  40520. bool isDirectory,
  40521. bool isItemSelected,
  40522. int itemIndex);
  40523. virtual Button* createFileBrowserGoUpButton();
  40524. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  40525. DirectoryContentsDisplayComponent* fileListComponent,
  40526. FilePreviewComponent* previewComp,
  40527. ComboBox* currentPathBox,
  40528. TextEditor* filenameBox,
  40529. Button* goUpButton);
  40530. virtual void drawBubble (Graphics& g,
  40531. float tipX, float tipY,
  40532. float boxX, float boxY, float boxW, float boxH);
  40533. /** Fills the background of a popup menu component. */
  40534. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40535. /** Draws one of the items in a popup menu. */
  40536. virtual void drawPopupMenuItem (Graphics& g,
  40537. int width, int height,
  40538. bool isSeparator,
  40539. bool isActive,
  40540. bool isHighlighted,
  40541. bool isTicked,
  40542. bool hasSubMenu,
  40543. const String& text,
  40544. const String& shortcutKeyText,
  40545. Image* image,
  40546. const Colour* const textColour);
  40547. /** Returns the size and style of font to use in popup menus. */
  40548. virtual const Font getPopupMenuFont();
  40549. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40550. int width, int height,
  40551. bool isScrollUpArrow);
  40552. /** Finds the best size for an item in a popup menu. */
  40553. virtual void getIdealPopupMenuItemSize (const String& text,
  40554. bool isSeparator,
  40555. int standardMenuItemHeight,
  40556. int& idealWidth,
  40557. int& idealHeight);
  40558. virtual int getMenuWindowFlags();
  40559. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40560. bool isMouseOverBar,
  40561. MenuBarComponent& menuBar);
  40562. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40563. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40564. virtual void drawMenuBarItem (Graphics& g,
  40565. int width, int height,
  40566. int itemIndex,
  40567. const String& itemText,
  40568. bool isMouseOverItem,
  40569. bool isMenuOpen,
  40570. bool isMouseOverBar,
  40571. MenuBarComponent& menuBar);
  40572. virtual void drawComboBox (Graphics& g, int width, int height,
  40573. bool isButtonDown,
  40574. int buttonX, int buttonY,
  40575. int buttonW, int buttonH,
  40576. ComboBox& box);
  40577. virtual const Font getComboBoxFont (ComboBox& box);
  40578. virtual Label* createComboBoxTextBox (ComboBox& box);
  40579. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40580. virtual void drawLabel (Graphics& g, Label& label);
  40581. virtual void drawLinearSlider (Graphics& g,
  40582. int x, int y,
  40583. int width, int height,
  40584. float sliderPos,
  40585. float minSliderPos,
  40586. float maxSliderPos,
  40587. const Slider::SliderStyle style,
  40588. Slider& slider);
  40589. virtual void drawLinearSliderBackground (Graphics& g,
  40590. int x, int y,
  40591. int width, int height,
  40592. float sliderPos,
  40593. float minSliderPos,
  40594. float maxSliderPos,
  40595. const Slider::SliderStyle style,
  40596. Slider& slider);
  40597. virtual void drawLinearSliderThumb (Graphics& g,
  40598. int x, int y,
  40599. int width, int height,
  40600. float sliderPos,
  40601. float minSliderPos,
  40602. float maxSliderPos,
  40603. const Slider::SliderStyle style,
  40604. Slider& slider);
  40605. virtual int getSliderThumbRadius (Slider& slider);
  40606. virtual void drawRotarySlider (Graphics& g,
  40607. int x, int y,
  40608. int width, int height,
  40609. float sliderPosProportional,
  40610. float rotaryStartAngle,
  40611. float rotaryEndAngle,
  40612. Slider& slider);
  40613. virtual Button* createSliderButton (bool isIncrement);
  40614. virtual Label* createSliderTextBox (Slider& slider);
  40615. virtual ImageEffectFilter* getSliderEffect();
  40616. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40617. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40618. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40619. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40620. ComboBox* filenameBox, Button* browseButton);
  40621. virtual void drawCornerResizer (Graphics& g,
  40622. int w, int h,
  40623. bool isMouseOver,
  40624. bool isMouseDragging);
  40625. virtual void drawResizableFrame (Graphics& g,
  40626. int w, int h,
  40627. const BorderSize& borders);
  40628. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  40629. const BorderSize& border,
  40630. ResizableWindow& window);
  40631. virtual void drawResizableWindowBorder (Graphics& g,
  40632. int w, int h,
  40633. const BorderSize& border,
  40634. ResizableWindow& window);
  40635. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40636. Graphics& g, int w, int h,
  40637. int titleSpaceX, int titleSpaceW,
  40638. const Image* icon,
  40639. bool drawTitleTextOnLeft);
  40640. virtual Button* createDocumentWindowButton (int buttonType);
  40641. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40642. int titleBarX, int titleBarY,
  40643. int titleBarW, int titleBarH,
  40644. Button* minimiseButton,
  40645. Button* maximiseButton,
  40646. Button* closeButton,
  40647. bool positionTitleBarButtonsOnLeft);
  40648. virtual int getDefaultMenuBarHeight();
  40649. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40650. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40651. int w, int h,
  40652. bool isVerticalBar,
  40653. bool isMouseOver,
  40654. bool isMouseDragging);
  40655. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40656. const String& text,
  40657. const Justification& position,
  40658. GroupComponent& group);
  40659. virtual void createTabButtonShape (Path& p,
  40660. int width, int height,
  40661. int tabIndex,
  40662. const String& text,
  40663. Button& button,
  40664. TabbedButtonBar::Orientation orientation,
  40665. bool isMouseOver,
  40666. bool isMouseDown,
  40667. bool isFrontTab);
  40668. virtual void fillTabButtonShape (Graphics& g,
  40669. const Path& path,
  40670. const Colour& preferredBackgroundColour,
  40671. int tabIndex,
  40672. const String& text,
  40673. Button& button,
  40674. TabbedButtonBar::Orientation orientation,
  40675. bool isMouseOver,
  40676. bool isMouseDown,
  40677. bool isFrontTab);
  40678. virtual void drawTabButtonText (Graphics& g,
  40679. int x, int y, int w, int h,
  40680. const Colour& preferredBackgroundColour,
  40681. int tabIndex,
  40682. const String& text,
  40683. Button& button,
  40684. TabbedButtonBar::Orientation orientation,
  40685. bool isMouseOver,
  40686. bool isMouseDown,
  40687. bool isFrontTab);
  40688. virtual int getTabButtonOverlap (int tabDepth);
  40689. virtual int getTabButtonSpaceAroundImage();
  40690. virtual int getTabButtonBestWidth (int tabIndex,
  40691. const String& text,
  40692. int tabDepth,
  40693. Button& button);
  40694. virtual void drawTabButton (Graphics& g,
  40695. int w, int h,
  40696. const Colour& preferredColour,
  40697. int tabIndex,
  40698. const String& text,
  40699. Button& button,
  40700. TabbedButtonBar::Orientation orientation,
  40701. bool isMouseOver,
  40702. bool isMouseDown,
  40703. bool isFrontTab);
  40704. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40705. int w, int h,
  40706. TabbedButtonBar& tabBar,
  40707. TabbedButtonBar::Orientation orientation);
  40708. virtual Button* createTabBarExtrasButton();
  40709. virtual void drawImageButton (Graphics& g, Image* image,
  40710. int imageX, int imageY, int imageW, int imageH,
  40711. const Colour& overlayColour,
  40712. float imageOpacity,
  40713. ImageButton& button);
  40714. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40715. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40716. int width, int height,
  40717. bool isMouseOver, bool isMouseDown,
  40718. int columnFlags);
  40719. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40720. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40721. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40722. bool isMouseOver, bool isMouseDown,
  40723. ToolbarItemComponent& component);
  40724. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40725. const String& text, ToolbarItemComponent& component);
  40726. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40727. bool isOpen, int width, int height);
  40728. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40729. PropertyComponent& component);
  40730. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40731. PropertyComponent& component);
  40732. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  40733. void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  40734. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40735. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  40736. /**
  40737. */
  40738. virtual void playAlertSound();
  40739. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40740. static void drawGlassSphere (Graphics& g,
  40741. float x, float y,
  40742. float diameter,
  40743. const Colour& colour,
  40744. float outlineThickness) throw();
  40745. static void drawGlassPointer (Graphics& g,
  40746. float x, float y,
  40747. float diameter,
  40748. const Colour& colour, float outlineThickness,
  40749. int direction) throw();
  40750. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40751. static void drawGlassLozenge (Graphics& g,
  40752. float x, float y,
  40753. float width, float height,
  40754. const Colour& colour,
  40755. float outlineThickness,
  40756. float cornerSize,
  40757. bool flatOnLeft, bool flatOnRight,
  40758. bool flatOnTop, bool flatOnBottom) throw();
  40759. juce_UseDebuggingNewOperator
  40760. private:
  40761. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40762. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40763. Array <int> colourIds;
  40764. Array <Colour> colours;
  40765. // default typeface names
  40766. String defaultSans, defaultSerif, defaultFixed;
  40767. void drawShinyButtonShape (Graphics& g,
  40768. float x, float y, float w, float h, float maxCornerSize,
  40769. const Colour& baseColour,
  40770. float strokeWidth,
  40771. bool flatOnLeft,
  40772. bool flatOnRight,
  40773. bool flatOnTop,
  40774. bool flatOnBottom) throw();
  40775. LookAndFeel (const LookAndFeel&);
  40776. LookAndFeel& operator= (const LookAndFeel&);
  40777. };
  40778. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40779. /*** End of inlined file: juce_LookAndFeel.h ***/
  40780. #endif
  40781. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40782. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40783. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40784. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40785. /**
  40786. The original Juce look-and-feel.
  40787. */
  40788. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40789. {
  40790. public:
  40791. /** Creates the default JUCE look and feel. */
  40792. OldSchoolLookAndFeel();
  40793. /** Destructor. */
  40794. virtual ~OldSchoolLookAndFeel();
  40795. /** Draws the lozenge-shaped background for a standard button. */
  40796. virtual void drawButtonBackground (Graphics& g,
  40797. Button& button,
  40798. const Colour& backgroundColour,
  40799. bool isMouseOverButton,
  40800. bool isButtonDown);
  40801. /** Draws the contents of a standard ToggleButton. */
  40802. virtual void drawToggleButton (Graphics& g,
  40803. ToggleButton& button,
  40804. bool isMouseOverButton,
  40805. bool isButtonDown);
  40806. virtual void drawTickBox (Graphics& g,
  40807. Component& component,
  40808. float x, float y, float w, float h,
  40809. bool ticked,
  40810. bool isEnabled,
  40811. bool isMouseOverButton,
  40812. bool isButtonDown);
  40813. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40814. int width, int height,
  40815. double progress, const String& textToShow);
  40816. virtual void drawScrollbarButton (Graphics& g,
  40817. ScrollBar& scrollbar,
  40818. int width, int height,
  40819. int buttonDirection,
  40820. bool isScrollbarVertical,
  40821. bool isMouseOverButton,
  40822. bool isButtonDown);
  40823. virtual void drawScrollbar (Graphics& g,
  40824. ScrollBar& scrollbar,
  40825. int x, int y,
  40826. int width, int height,
  40827. bool isScrollbarVertical,
  40828. int thumbStartPosition,
  40829. int thumbSize,
  40830. bool isMouseOver,
  40831. bool isMouseDown);
  40832. virtual ImageEffectFilter* getScrollbarEffect();
  40833. virtual void drawTextEditorOutline (Graphics& g,
  40834. int width, int height,
  40835. TextEditor& textEditor);
  40836. /** Fills the background of a popup menu component. */
  40837. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40838. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40839. bool isMouseOverBar,
  40840. MenuBarComponent& menuBar);
  40841. virtual void drawComboBox (Graphics& g, int width, int height,
  40842. bool isButtonDown,
  40843. int buttonX, int buttonY,
  40844. int buttonW, int buttonH,
  40845. ComboBox& box);
  40846. virtual const Font getComboBoxFont (ComboBox& box);
  40847. virtual void drawLinearSlider (Graphics& g,
  40848. int x, int y,
  40849. int width, int height,
  40850. float sliderPos,
  40851. float minSliderPos,
  40852. float maxSliderPos,
  40853. const Slider::SliderStyle style,
  40854. Slider& slider);
  40855. virtual int getSliderThumbRadius (Slider& slider);
  40856. virtual Button* createSliderButton (bool isIncrement);
  40857. virtual ImageEffectFilter* getSliderEffect();
  40858. virtual void drawCornerResizer (Graphics& g,
  40859. int w, int h,
  40860. bool isMouseOver,
  40861. bool isMouseDragging);
  40862. virtual Button* createDocumentWindowButton (int buttonType);
  40863. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40864. int titleBarX, int titleBarY,
  40865. int titleBarW, int titleBarH,
  40866. Button* minimiseButton,
  40867. Button* maximiseButton,
  40868. Button* closeButton,
  40869. bool positionTitleBarButtonsOnLeft);
  40870. juce_UseDebuggingNewOperator
  40871. private:
  40872. DropShadowEffect scrollbarShadow;
  40873. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40874. OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40875. };
  40876. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40877. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40878. #endif
  40879. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  40880. #endif
  40881. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  40882. #endif
  40883. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  40884. #endif
  40885. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40886. /*** Start of inlined file: juce_PopupMenuCustomComponent.h ***/
  40887. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40888. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40889. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  40890. @see PopupMenu::addCustomItem
  40891. */
  40892. class JUCE_API PopupMenuCustomComponent : public Component,
  40893. public ReferenceCountedObject
  40894. {
  40895. public:
  40896. /** Destructor. */
  40897. ~PopupMenuCustomComponent();
  40898. /** Chooses the size that this component would like to have.
  40899. Note that the size which this method returns isn't necessarily the one that
  40900. the menu will give it, as it will be stretched to fit the other items in
  40901. the menu.
  40902. */
  40903. virtual void getIdealSize (int& idealWidth,
  40904. int& idealHeight) = 0;
  40905. /** Dismisses the menu indicating that this item has been chosen.
  40906. This will cause the menu to exit from its modal state, returning
  40907. this item's id as the result.
  40908. */
  40909. void triggerMenuItem();
  40910. /** Returns true if this item should be highlighted because the mouse is
  40911. over it.
  40912. You can call this method in your paint() method to find out whether
  40913. to draw a highlight.
  40914. */
  40915. bool isItemHighlighted() const throw() { return isHighlighted; }
  40916. protected:
  40917. /** Constructor.
  40918. If isTriggeredAutomatically is true, then the menu will automatically detect
  40919. a click on this component and use that to trigger it. If it's false, then it's
  40920. up to your class to manually trigger the item if it wants to.
  40921. */
  40922. PopupMenuCustomComponent (bool isTriggeredAutomatically = true);
  40923. private:
  40924. friend class PopupMenu;
  40925. friend class PopupMenu::ItemComponent;
  40926. friend class PopupMenu::Window;
  40927. bool isHighlighted, isTriggeredAutomatically;
  40928. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  40929. PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  40930. };
  40931. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40932. /*** End of inlined file: juce_PopupMenuCustomComponent.h ***/
  40933. #endif
  40934. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  40935. #endif
  40936. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  40937. #endif
  40938. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  40939. #endif
  40940. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40941. #endif
  40942. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40943. /*** Start of inlined file: juce_LassoComponent.h ***/
  40944. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40945. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40946. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  40947. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40948. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40949. /** Manages a list of selectable items.
  40950. Use one of these to keep a track of things that the user has highlighted, like
  40951. icons or things in a list.
  40952. The class is templated so that you can use it to hold either a set of pointers
  40953. to objects, or a set of ID numbers or handles, for cases where each item may
  40954. not always have a corresponding object.
  40955. To be informed when items are selected/deselected, register a ChangeListener with
  40956. this object.
  40957. @see SelectableObject
  40958. */
  40959. template <class SelectableItemType>
  40960. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  40961. {
  40962. public:
  40963. typedef SelectableItemType ItemType;
  40964. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  40965. /** Creates an empty set. */
  40966. SelectedItemSet()
  40967. {
  40968. }
  40969. /** Creates a set based on an array of items. */
  40970. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  40971. : selectedItems (items)
  40972. {
  40973. }
  40974. /** Creates a copy of another set. */
  40975. SelectedItemSet (const SelectedItemSet& other)
  40976. : selectedItems (other.selectedItems)
  40977. {
  40978. }
  40979. /** Creates a copy of another set. */
  40980. SelectedItemSet& operator= (const SelectedItemSet& other)
  40981. {
  40982. if (selectedItems != other.selectedItems)
  40983. {
  40984. selectedItems = other.selectedItems;
  40985. changed();
  40986. }
  40987. return *this;
  40988. }
  40989. /** Destructor. */
  40990. ~SelectedItemSet()
  40991. {
  40992. }
  40993. /** Clears any other currently selected items, and selects this item.
  40994. If this item is already the only thing selected, no change notification
  40995. will be sent out.
  40996. @see addToSelection, addToSelectionBasedOnModifiers
  40997. */
  40998. void selectOnly (ParameterType item)
  40999. {
  41000. if (isSelected (item))
  41001. {
  41002. for (int i = selectedItems.size(); --i >= 0;)
  41003. {
  41004. if (selectedItems.getUnchecked(i) != item)
  41005. {
  41006. deselect (selectedItems.getUnchecked(i));
  41007. i = jmin (i, selectedItems.size());
  41008. }
  41009. }
  41010. }
  41011. else
  41012. {
  41013. deselectAll();
  41014. changed();
  41015. selectedItems.add (item);
  41016. itemSelected (item);
  41017. }
  41018. }
  41019. /** Selects an item.
  41020. If the item is already selected, no change notification will be sent out.
  41021. @see selectOnly, addToSelectionBasedOnModifiers
  41022. */
  41023. void addToSelection (ParameterType item)
  41024. {
  41025. if (! isSelected (item))
  41026. {
  41027. changed();
  41028. selectedItems.add (item);
  41029. itemSelected (item);
  41030. }
  41031. }
  41032. /** Selects or deselects an item.
  41033. This will use the modifier keys to decide whether to deselect other items
  41034. first.
  41035. So if the shift key is held down, the item will be added without deselecting
  41036. anything (same as calling addToSelection() )
  41037. If no modifiers are down, the current selection will be cleared first (same
  41038. as calling selectOnly() )
  41039. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  41040. so it'll be added to the set unless it's already there, in which case it'll be
  41041. deselected.
  41042. If the items that you're selecting can also be dragged, you may need to use the
  41043. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  41044. subtleties of this kind of usage.
  41045. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  41046. */
  41047. void addToSelectionBasedOnModifiers (ParameterType item,
  41048. const ModifierKeys& modifiers)
  41049. {
  41050. if (modifiers.isShiftDown())
  41051. {
  41052. addToSelection (item);
  41053. }
  41054. else if (modifiers.isCommandDown())
  41055. {
  41056. if (isSelected (item))
  41057. deselect (item);
  41058. else
  41059. addToSelection (item);
  41060. }
  41061. else
  41062. {
  41063. selectOnly (item);
  41064. }
  41065. }
  41066. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  41067. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  41068. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  41069. makes it easy to handle multiple-selection of sets of objects that can also
  41070. be dragged.
  41071. For example, if you have several items already selected, and you click on
  41072. one of them (without dragging), then you'd expect this to deselect the other, and
  41073. just select the item you clicked on. But if you had clicked on this item and
  41074. dragged it, you'd have expected them all to stay selected.
  41075. When you call this method, you'll need to store the boolean result, because the
  41076. addToSelectionOnMouseUp() method will need to be know this value.
  41077. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  41078. */
  41079. bool addToSelectionOnMouseDown (ParameterType item,
  41080. const ModifierKeys& modifiers)
  41081. {
  41082. if (isSelected (item))
  41083. {
  41084. return ! modifiers.isPopupMenu();
  41085. }
  41086. else
  41087. {
  41088. addToSelectionBasedOnModifiers (item, modifiers);
  41089. return false;
  41090. }
  41091. }
  41092. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  41093. Call this during a mouseUp callback, when you have previously called the
  41094. addToSelectionOnMouseDown() method during your mouseDown event.
  41095. See addToSelectionOnMouseDown() for more info
  41096. @param item the item to select (or deselect)
  41097. @param modifiers the modifiers from the mouse-up event
  41098. @param wasItemDragged true if your item was dragged during the mouse click
  41099. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  41100. back from the addToSelectionOnMouseDown() call that you
  41101. should have made during the matching mouseDown event
  41102. */
  41103. void addToSelectionOnMouseUp (ParameterType item,
  41104. const ModifierKeys& modifiers,
  41105. const bool wasItemDragged,
  41106. const bool resultOfMouseDownSelectMethod)
  41107. {
  41108. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  41109. addToSelectionBasedOnModifiers (item, modifiers);
  41110. }
  41111. /** Deselects an item. */
  41112. void deselect (ParameterType item)
  41113. {
  41114. const int i = selectedItems.indexOf (item);
  41115. if (i >= 0)
  41116. {
  41117. changed();
  41118. itemDeselected (selectedItems.remove (i));
  41119. }
  41120. }
  41121. /** Deselects all items. */
  41122. void deselectAll()
  41123. {
  41124. if (selectedItems.size() > 0)
  41125. {
  41126. changed();
  41127. for (int i = selectedItems.size(); --i >= 0;)
  41128. {
  41129. itemDeselected (selectedItems.remove (i));
  41130. i = jmin (i, selectedItems.size());
  41131. }
  41132. }
  41133. }
  41134. /** Returns the number of currently selected items.
  41135. @see getSelectedItem
  41136. */
  41137. int getNumSelected() const throw()
  41138. {
  41139. return selectedItems.size();
  41140. }
  41141. /** Returns one of the currently selected items.
  41142. Returns 0 if the index is out-of-range.
  41143. @see getNumSelected
  41144. */
  41145. SelectableItemType getSelectedItem (const int index) const throw()
  41146. {
  41147. return selectedItems [index];
  41148. }
  41149. /** True if this item is currently selected. */
  41150. bool isSelected (ParameterType item) const throw()
  41151. {
  41152. return selectedItems.contains (item);
  41153. }
  41154. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  41155. /** Can be overridden to do special handling when an item is selected.
  41156. For example, if the item is an object, you might want to call it and tell
  41157. it that it's being selected.
  41158. */
  41159. virtual void itemSelected (SelectableItemType item) { (void) item; }
  41160. /** Can be overridden to do special handling when an item is deselected.
  41161. For example, if the item is an object, you might want to call it and tell
  41162. it that it's being deselected.
  41163. */
  41164. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  41165. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  41166. */
  41167. void changed (const bool synchronous = false)
  41168. {
  41169. if (synchronous)
  41170. sendSynchronousChangeMessage (this);
  41171. else
  41172. sendChangeMessage (this);
  41173. }
  41174. juce_UseDebuggingNewOperator
  41175. private:
  41176. Array <SelectableItemType> selectedItems;
  41177. };
  41178. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  41179. /*** End of inlined file: juce_SelectedItemSet.h ***/
  41180. /**
  41181. A class used by the LassoComponent to manage the things that it selects.
  41182. This allows the LassoComponent to find out which items are within the lasso,
  41183. and to change the list of selected items.
  41184. @see LassoComponent, SelectedItemSet
  41185. */
  41186. template <class SelectableItemType>
  41187. class LassoSource
  41188. {
  41189. public:
  41190. /** Destructor. */
  41191. virtual ~LassoSource() {}
  41192. /** Returns the set of items that lie within a given lassoable region.
  41193. Your implementation of this method must find all the relevent items that lie
  41194. within the given rectangle. and add them to the itemsFound array.
  41195. The co-ordinates are relative to the top-left of the lasso component's parent
  41196. component. (i.e. they are the same as the size and position of the lasso
  41197. component itself).
  41198. */
  41199. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  41200. const Rectangle<int>& area) = 0;
  41201. /** Returns the SelectedItemSet that the lasso should update.
  41202. This set will be continuously updated by the LassoComponent as it gets
  41203. dragged around, so make sure that you've got a ChangeListener attached to
  41204. the set so that your UI objects will know when the selection changes and
  41205. be able to update themselves appropriately.
  41206. */
  41207. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  41208. };
  41209. /**
  41210. A component that acts as a rectangular selection region, which you drag with
  41211. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  41212. To use one of these:
  41213. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  41214. component, and call its beginLasso() method, giving it a
  41215. suitable LassoSource object that it can use to find out which items are in
  41216. the active area.
  41217. - Each time your parent component gets a mouseDrag event, call dragLasso()
  41218. to update the lasso's position - it will use its LassoSource to calculate and
  41219. update the current selection.
  41220. - After the drag has finished and you get a mouseUp callback, you should call
  41221. endLasso() to clean up. This will make the lasso component invisible, and you
  41222. can remove it from the parent component, or delete it.
  41223. The class takes into account the modifier keys that are being held down while
  41224. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  41225. be added to the original selection; if ctrl or command is pressed, they will be
  41226. xor'ed with any previously selected items.
  41227. @see LassoSource, SelectedItemSet
  41228. */
  41229. template <class SelectableItemType>
  41230. class LassoComponent : public Component
  41231. {
  41232. public:
  41233. /** Creates a Lasso component.
  41234. The fill colour is used to fill the lasso'ed rectangle, and the outline
  41235. colour is used to draw a line around its edge.
  41236. */
  41237. explicit LassoComponent (const int outlineThickness_ = 1)
  41238. : source (0),
  41239. outlineThickness (outlineThickness_)
  41240. {
  41241. }
  41242. /** Destructor. */
  41243. ~LassoComponent()
  41244. {
  41245. }
  41246. /** Call this in your mouseDown event, to initialise a drag.
  41247. Pass in a suitable LassoSource object which the lasso will use to find
  41248. the items and change the selection.
  41249. After using this method to initialise the lasso, repeatedly call dragLasso()
  41250. in your component's mouseDrag callback.
  41251. @see dragLasso, endLasso, LassoSource
  41252. */
  41253. void beginLasso (const MouseEvent& e,
  41254. LassoSource <SelectableItemType>* const lassoSource)
  41255. {
  41256. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  41257. jassert (lassoSource != 0); // the source can't be null!
  41258. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  41259. source = lassoSource;
  41260. if (lassoSource != 0)
  41261. originalSelection = lassoSource->getLassoSelection().getItemArray();
  41262. setSize (0, 0);
  41263. dragStartPos = e.getMouseDownPosition();
  41264. }
  41265. /** Call this in your mouseDrag event, to update the lasso's position.
  41266. This must be repeatedly calling when the mouse is dragged, after you've
  41267. first initialised the lasso with beginLasso().
  41268. This method takes into account the modifier keys that are being held down, so
  41269. if shift is pressed, then the lassoed items will be added to any that were
  41270. previously selected; if ctrl or command is pressed, then they will be xor'ed
  41271. with previously selected items.
  41272. @see beginLasso, endLasso
  41273. */
  41274. void dragLasso (const MouseEvent& e)
  41275. {
  41276. if (source != 0)
  41277. {
  41278. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  41279. setVisible (true);
  41280. Array <SelectableItemType> itemsInLasso;
  41281. source->findLassoItemsInArea (itemsInLasso, getBounds());
  41282. if (e.mods.isShiftDown())
  41283. {
  41284. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  41285. itemsInLasso.addArray (originalSelection);
  41286. }
  41287. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  41288. {
  41289. Array <SelectableItemType> originalMinusNew (originalSelection);
  41290. originalMinusNew.removeValuesIn (itemsInLasso);
  41291. itemsInLasso.removeValuesIn (originalSelection);
  41292. itemsInLasso.addArray (originalMinusNew);
  41293. }
  41294. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  41295. }
  41296. }
  41297. /** Call this in your mouseUp event, after the lasso has been dragged.
  41298. @see beginLasso, dragLasso
  41299. */
  41300. void endLasso()
  41301. {
  41302. source = 0;
  41303. originalSelection.clear();
  41304. setVisible (false);
  41305. }
  41306. /** A set of colour IDs to use to change the colour of various aspects of the label.
  41307. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41308. methods.
  41309. Note that you can also use the constants from TextEditor::ColourIds to change the
  41310. colour of the text editor that is opened when a label is editable.
  41311. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41312. */
  41313. enum ColourIds
  41314. {
  41315. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  41316. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  41317. };
  41318. /** @internal */
  41319. void paint (Graphics& g)
  41320. {
  41321. g.fillAll (findColour (lassoFillColourId));
  41322. g.setColour (findColour (lassoOutlineColourId));
  41323. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  41324. // this suggests that you've left a lasso comp lying around after the
  41325. // mouse drag has finished.. Be careful to call endLasso() when you get a
  41326. // mouse-up event.
  41327. jassert (isMouseButtonDownAnywhere());
  41328. }
  41329. /** @internal */
  41330. bool hitTest (int, int) { return false; }
  41331. juce_UseDebuggingNewOperator
  41332. private:
  41333. Array <SelectableItemType> originalSelection;
  41334. LassoSource <SelectableItemType>* source;
  41335. int outlineThickness;
  41336. Point<int> dragStartPos;
  41337. };
  41338. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  41339. /*** End of inlined file: juce_LassoComponent.h ***/
  41340. #endif
  41341. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  41342. #endif
  41343. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  41344. #endif
  41345. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41346. /*** Start of inlined file: juce_MouseHoverDetector.h ***/
  41347. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41348. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41349. /**
  41350. Monitors a component for mouse activity, and triggers a callback
  41351. when the mouse hovers in one place for a specified length of time.
  41352. To use a hover-detector, just create one and call its setHoverComponent()
  41353. method to start it watching a component. You can call setHoverComponent (0)
  41354. to make it inactive.
  41355. (Be careful not to delete a component that's being monitored without first
  41356. stopping or deleting the hover detector).
  41357. */
  41358. class JUCE_API MouseHoverDetector
  41359. {
  41360. public:
  41361. /** Creates a hover detector.
  41362. Initially the object is inactive, and you need to tell it which component
  41363. to monitor, using the setHoverComponent() method.
  41364. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  41365. needs to stay still before the mouseHovered() method
  41366. is invoked. You can change this setting later with
  41367. the setHoverTimeMillisecs() method
  41368. */
  41369. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  41370. /** Destructor. */
  41371. virtual ~MouseHoverDetector();
  41372. /** Changes the time for which the mouse has to stay still before it's considered
  41373. to be hovering.
  41374. */
  41375. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  41376. /** Changes the component that's being monitored for hovering.
  41377. Be careful not to delete a component that's being monitored without first
  41378. stopping or deleting the hover detector.
  41379. */
  41380. void setHoverComponent (Component* const newSourceComponent);
  41381. protected:
  41382. /** Called back when the mouse hovers.
  41383. After the mouse has stayed still over the component for the length of time
  41384. specified by setHoverTimeMillisecs(), this method will be invoked.
  41385. When the mouse is first moved after this callback has occurred, the
  41386. mouseMovedAfterHover() method will be called.
  41387. @param mouseX the mouse's X position relative to the component being monitored
  41388. @param mouseY the mouse's Y position relative to the component being monitored
  41389. */
  41390. virtual void mouseHovered (int mouseX,
  41391. int mouseY) = 0;
  41392. /** Called when the mouse is moved away after just having hovered. */
  41393. virtual void mouseMovedAfterHover() = 0;
  41394. private:
  41395. class JUCE_API HoverDetectorInternal : public MouseListener,
  41396. public Timer
  41397. {
  41398. public:
  41399. MouseHoverDetector* owner;
  41400. int lastX, lastY;
  41401. void timerCallback();
  41402. void mouseEnter (const MouseEvent&);
  41403. void mouseExit (const MouseEvent&);
  41404. void mouseDown (const MouseEvent&);
  41405. void mouseUp (const MouseEvent&);
  41406. void mouseMove (const MouseEvent&);
  41407. void mouseWheelMove (const MouseEvent&, float, float);
  41408. } internalTimer;
  41409. friend class HoverDetectorInternal;
  41410. Component* source;
  41411. int hoverTimeMillisecs;
  41412. bool hasJustHovered;
  41413. void hoverTimerCallback();
  41414. void checkJustHoveredCallback();
  41415. MouseHoverDetector (const MouseHoverDetector&);
  41416. MouseHoverDetector& operator= (const MouseHoverDetector&);
  41417. };
  41418. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41419. /*** End of inlined file: juce_MouseHoverDetector.h ***/
  41420. #endif
  41421. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41422. /*** Start of inlined file: juce_MouseInputSource.h ***/
  41423. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41424. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41425. class Component;
  41426. class ComponentPeer;
  41427. class MouseInputSourceInternal;
  41428. /**
  41429. Represents a linear source of mouse events from a mouse device or individual finger
  41430. in a multi-touch environment.
  41431. Each MouseEvent object contains a reference to the MouseInputSource that generated
  41432. it. In an environment with a single mouse for input, all events will come from the
  41433. same source, but in a multi-touch system, there may be multiple MouseInputSource
  41434. obects active, each representing a stream of events coming from a particular finger.
  41435. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  41436. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  41437. the only events that can happen between a mouseDown and its corresponding mouseUp are
  41438. mouseDrags, etc.
  41439. When there are multiple touches arriving from multiple MouseInputSources, their
  41440. event streams may arrive in an interleaved order, so you should use the getIndex()
  41441. method to find out which finger each event came from.
  41442. @see MouseEvent
  41443. */
  41444. class JUCE_API MouseInputSource
  41445. {
  41446. public:
  41447. /** Creates a MouseInputSource.
  41448. You should never actually create a MouseInputSource in your own code - the
  41449. library takes care of managing these objects.
  41450. */
  41451. MouseInputSource (int index, bool isMouseDevice);
  41452. /** Destructor. */
  41453. ~MouseInputSource();
  41454. /** Returns true if this object represents a normal desk-based mouse device. */
  41455. bool isMouse() const;
  41456. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  41457. bool isTouch() const;
  41458. /** Returns true if this source has an on-screen pointer that can hover over
  41459. items without clicking them.
  41460. */
  41461. bool canHover() const;
  41462. /** Returns true if this source may have a scroll wheel. */
  41463. bool hasMouseWheel() const;
  41464. /** Returns this source's index in the global list of possible sources.
  41465. If the system only has a single mouse, there will only be a single MouseInputSource
  41466. with an index of 0.
  41467. If the system supports multi-touch input, then the index will represent a finger
  41468. number, starting from 0. When the first touch event begins, it will have finger
  41469. number 0, and then if a second touch happens while the first is still down, it
  41470. will have index 1, etc.
  41471. */
  41472. int getIndex() const;
  41473. /** Returns true if this device is currently being pressed. */
  41474. bool isDragging() const;
  41475. /** Returns the last-known screen position of this source. */
  41476. const Point<int> getScreenPosition() const;
  41477. /** Returns a set of modifiers that indicate which buttons are currently
  41478. held down on this device.
  41479. */
  41480. const ModifierKeys getCurrentModifiers() const;
  41481. /** Returns the component that was last known to be under this pointer. */
  41482. Component* getComponentUnderMouse() const;
  41483. /** Tells the device to dispatch a mouse-move event.
  41484. This is asynchronous - the event will occur on the message thread.
  41485. */
  41486. void triggerFakeMove() const;
  41487. /** Returns the number of clicks that should be counted as belonging to the
  41488. current mouse event.
  41489. So the mouse is currently down and it's the second click of a double-click, this
  41490. will return 2.
  41491. */
  41492. int getNumberOfMultipleClicks() const throw();
  41493. /** Returns the time at which the last mouse-down occurred. */
  41494. const Time getLastMouseDownTime() const throw();
  41495. /** Returns the screen position at which the last mouse-down occurred. */
  41496. const Point<int> getLastMouseDownPosition() const throw();
  41497. /** Returns true if this mouse is currently down, and if it has been dragged more
  41498. than a couple of pixels from the place it was pressed.
  41499. */
  41500. bool hasMouseMovedSignificantlySincePressed() const throw();
  41501. bool hasMouseCursor() const throw();
  41502. void showMouseCursor (const MouseCursor& cursor);
  41503. void hideCursor();
  41504. void revealCursor();
  41505. void forceMouseCursorUpdate();
  41506. bool canDoUnboundedMovement() const throw();
  41507. /** Allows the mouse to move beyond the edges of the screen.
  41508. Calling this method when the mouse button is currently pressed will remove the cursor
  41509. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  41510. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  41511. can be used for things like custom slider controls or dragging objects around, where
  41512. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  41513. The unbounded mode is automatically turned off when the mouse button is released, or
  41514. it can be turned off explicitly by calling this method again.
  41515. @param isEnabled whether to turn this mode on or off
  41516. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  41517. hidden; if true, it will only be hidden when it
  41518. is moved beyond the edge of the screen
  41519. */
  41520. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  41521. juce_UseDebuggingNewOperator
  41522. /** @internal */
  41523. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  41524. /** @internal */
  41525. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  41526. private:
  41527. friend class Desktop;
  41528. friend class ComponentPeer;
  41529. friend class MouseInputSourceInternal;
  41530. ScopedPointer<MouseInputSourceInternal> pimpl;
  41531. MouseInputSource (const MouseInputSource&);
  41532. MouseInputSource& operator= (const MouseInputSource&);
  41533. };
  41534. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41535. /*** End of inlined file: juce_MouseInputSource.h ***/
  41536. #endif
  41537. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  41538. #endif
  41539. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  41540. #endif
  41541. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41542. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  41543. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41544. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41545. /**
  41546. A PropertyComponent that contains an on/off toggle button.
  41547. This type of property component can be used if you have a boolean value to
  41548. toggle on/off.
  41549. @see PropertyComponent
  41550. */
  41551. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  41552. private ButtonListener
  41553. {
  41554. protected:
  41555. /** Creates a button component.
  41556. If you use this constructor, you must override the getState() and setState()
  41557. methods.
  41558. @param propertyName the property name to be passed to the PropertyComponent
  41559. @param buttonTextWhenTrue the text shown in the button when the value is true
  41560. @param buttonTextWhenFalse the text shown in the button when the value is false
  41561. */
  41562. BooleanPropertyComponent (const String& propertyName,
  41563. const String& buttonTextWhenTrue,
  41564. const String& buttonTextWhenFalse);
  41565. public:
  41566. /** Creates a button component.
  41567. @param valueToControl a Value object that this property should refer to.
  41568. @param propertyName the property name to be passed to the PropertyComponent
  41569. @param buttonText the text shown in the ToggleButton component
  41570. */
  41571. BooleanPropertyComponent (const Value& valueToControl,
  41572. const String& propertyName,
  41573. const String& buttonText);
  41574. /** Destructor. */
  41575. ~BooleanPropertyComponent();
  41576. /** Called to change the state of the boolean value. */
  41577. virtual void setState (bool newState);
  41578. /** Must return the current value of the property. */
  41579. virtual bool getState() const;
  41580. /** @internal */
  41581. void paint (Graphics& g);
  41582. /** @internal */
  41583. void refresh();
  41584. /** @internal */
  41585. void buttonClicked (Button*);
  41586. juce_UseDebuggingNewOperator
  41587. private:
  41588. ToggleButton button;
  41589. String onText, offText;
  41590. BooleanPropertyComponent (const BooleanPropertyComponent&);
  41591. BooleanPropertyComponent& operator= (const BooleanPropertyComponent&);
  41592. };
  41593. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41594. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  41595. #endif
  41596. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41597. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  41598. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41599. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41600. /**
  41601. A PropertyComponent that contains a button.
  41602. This type of property component can be used if you need a button to trigger some
  41603. kind of action.
  41604. @see PropertyComponent
  41605. */
  41606. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  41607. private ButtonListener
  41608. {
  41609. public:
  41610. /** Creates a button component.
  41611. @param propertyName the property name to be passed to the PropertyComponent
  41612. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  41613. */
  41614. ButtonPropertyComponent (const String& propertyName,
  41615. bool triggerOnMouseDown);
  41616. /** Destructor. */
  41617. ~ButtonPropertyComponent();
  41618. /** Called when the user clicks the button.
  41619. */
  41620. virtual void buttonClicked() = 0;
  41621. /** Returns the string that should be displayed in the button.
  41622. If you need to change this string, call refresh() to update the component.
  41623. */
  41624. virtual const String getButtonText() const = 0;
  41625. /** @internal */
  41626. void refresh();
  41627. /** @internal */
  41628. void buttonClicked (Button*);
  41629. juce_UseDebuggingNewOperator
  41630. private:
  41631. TextButton button;
  41632. ButtonPropertyComponent (const ButtonPropertyComponent&);
  41633. ButtonPropertyComponent& operator= (const ButtonPropertyComponent&);
  41634. };
  41635. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41636. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  41637. #endif
  41638. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41639. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  41640. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41641. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41642. /**
  41643. A PropertyComponent that shows its value as a combo box.
  41644. This type of property component contains a list of options and has a
  41645. combo box to choose one.
  41646. Your subclass's constructor must add some strings to the choices StringArray
  41647. and these are shown in the list.
  41648. The getIndex() method will be called to find out which option is the currently
  41649. selected one. If you call refresh() it will call getIndex() to check whether
  41650. the value has changed, and will update the combo box if needed.
  41651. If the user selects a different item from the list, setIndex() will be
  41652. called to let your class process this.
  41653. @see PropertyComponent, PropertyPanel
  41654. */
  41655. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  41656. private ComboBoxListener
  41657. {
  41658. protected:
  41659. /** Creates the component.
  41660. Your subclass's constructor must add a list of options to the choices
  41661. member variable.
  41662. */
  41663. ChoicePropertyComponent (const String& propertyName);
  41664. public:
  41665. /** Creates the component.
  41666. @param valueToControl the value that the combo box will read and control
  41667. @param propertyName the name of the property
  41668. @param choices the list of possible values that the drop-down list will contain
  41669. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  41670. These are the values that will be read and written to the
  41671. valueToControl value. This array must contain the same number of items
  41672. as the choices array
  41673. */
  41674. ChoicePropertyComponent (const Value& valueToControl,
  41675. const String& propertyName,
  41676. const StringArray& choices,
  41677. const Array <var>& correspondingValues);
  41678. /** Destructor. */
  41679. ~ChoicePropertyComponent();
  41680. /** Called when the user selects an item from the combo box.
  41681. Your subclass must use this callback to update the value that this component
  41682. represents. The index is the index of the chosen item in the choices
  41683. StringArray.
  41684. */
  41685. virtual void setIndex (int newIndex);
  41686. /** Returns the index of the item that should currently be shown.
  41687. This is the index of the item in the choices StringArray that will be
  41688. shown.
  41689. */
  41690. virtual int getIndex() const;
  41691. /** Returns the list of options. */
  41692. const StringArray& getChoices() const;
  41693. /** @internal */
  41694. void refresh();
  41695. /** @internal */
  41696. void comboBoxChanged (ComboBox*);
  41697. juce_UseDebuggingNewOperator
  41698. protected:
  41699. /** The list of options that will be shown in the combo box.
  41700. Your subclass must populate this array in its constructor. If any empty
  41701. strings are added, these will be replaced with horizontal separators (see
  41702. ComboBox::addSeparator() for more info).
  41703. */
  41704. StringArray choices;
  41705. private:
  41706. ComboBox comboBox;
  41707. bool isCustomClass;
  41708. class RemapperValueSource;
  41709. void createComboBox();
  41710. ChoicePropertyComponent (const ChoicePropertyComponent&);
  41711. ChoicePropertyComponent& operator= (const ChoicePropertyComponent&);
  41712. };
  41713. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41714. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  41715. #endif
  41716. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  41717. #endif
  41718. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  41719. #endif
  41720. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41721. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  41722. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41723. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41724. /**
  41725. A PropertyComponent that shows its value as a slider.
  41726. @see PropertyComponent, Slider
  41727. */
  41728. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  41729. private SliderListener
  41730. {
  41731. protected:
  41732. /** Creates the property component.
  41733. The ranges, interval and skew factor are passed to the Slider component.
  41734. If you need to customise the slider in other ways, your constructor can
  41735. access the slider member variable and change it directly.
  41736. */
  41737. SliderPropertyComponent (const String& propertyName,
  41738. double rangeMin,
  41739. double rangeMax,
  41740. double interval,
  41741. double skewFactor = 1.0);
  41742. public:
  41743. /** Creates the property component.
  41744. The ranges, interval and skew factor are passed to the Slider component.
  41745. If you need to customise the slider in other ways, your constructor can
  41746. access the slider member variable and change it directly.
  41747. */
  41748. SliderPropertyComponent (const Value& valueToControl,
  41749. const String& propertyName,
  41750. double rangeMin,
  41751. double rangeMax,
  41752. double interval,
  41753. double skewFactor = 1.0);
  41754. /** Destructor. */
  41755. ~SliderPropertyComponent();
  41756. /** Called when the user moves the slider to change its value.
  41757. Your subclass must use this method to update whatever item this property
  41758. represents.
  41759. */
  41760. virtual void setValue (double newValue);
  41761. /** Returns the value that the slider should show. */
  41762. virtual double getValue() const;
  41763. /** @internal */
  41764. void refresh();
  41765. /** @internal */
  41766. void changeListenerCallback (void*);
  41767. /** @internal */
  41768. void sliderValueChanged (Slider*);
  41769. juce_UseDebuggingNewOperator
  41770. protected:
  41771. /** The slider component being used in this component.
  41772. Your subclass has access to this in case it needs to customise it in some way.
  41773. */
  41774. Slider slider;
  41775. SliderPropertyComponent (const SliderPropertyComponent&);
  41776. SliderPropertyComponent& operator= (const SliderPropertyComponent&);
  41777. };
  41778. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41779. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  41780. #endif
  41781. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41782. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  41783. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41784. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41785. /**
  41786. A PropertyComponent that shows its value as editable text.
  41787. @see PropertyComponent
  41788. */
  41789. class JUCE_API TextPropertyComponent : public PropertyComponent
  41790. {
  41791. protected:
  41792. /** Creates a text property component.
  41793. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41794. sets whether the text editor allows carriage returns.
  41795. @see TextEditor
  41796. */
  41797. TextPropertyComponent (const String& propertyName,
  41798. int maxNumChars,
  41799. bool isMultiLine);
  41800. public:
  41801. /** Creates a text property component.
  41802. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41803. sets whether the text editor allows carriage returns.
  41804. @see TextEditor
  41805. */
  41806. TextPropertyComponent (const Value& valueToControl,
  41807. const String& propertyName,
  41808. int maxNumChars,
  41809. bool isMultiLine);
  41810. /** Destructor. */
  41811. ~TextPropertyComponent();
  41812. /** Called when the user edits the text.
  41813. Your subclass must use this callback to change the value of whatever item
  41814. this property component represents.
  41815. */
  41816. virtual void setText (const String& newText);
  41817. /** Returns the text that should be shown in the text editor.
  41818. */
  41819. virtual const String getText() const;
  41820. /** @internal */
  41821. void refresh();
  41822. /** @internal */
  41823. void textWasEdited();
  41824. juce_UseDebuggingNewOperator
  41825. private:
  41826. Label* textEditor;
  41827. void createEditor (int maxNumChars, bool isMultiLine);
  41828. TextPropertyComponent (const TextPropertyComponent&);
  41829. TextPropertyComponent& operator= (const TextPropertyComponent&);
  41830. };
  41831. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41832. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  41833. #endif
  41834. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41835. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  41836. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41837. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41838. #if JUCE_WINDOWS || DOXYGEN
  41839. /**
  41840. A Windows-specific class that can create and embed an ActiveX control inside
  41841. itself.
  41842. To use it, create one of these, put it in place and make sure it's visible in a
  41843. window, then use createControl() to instantiate an ActiveX control. The control
  41844. will then be moved and resized to follow the movements of this component.
  41845. Of course, since the control is a heavyweight window, it'll obliterate any
  41846. juce components that may overlap this component, but that's life.
  41847. */
  41848. class JUCE_API ActiveXControlComponent : public Component
  41849. {
  41850. public:
  41851. /** Create an initially-empty container. */
  41852. ActiveXControlComponent();
  41853. /** Destructor. */
  41854. ~ActiveXControlComponent();
  41855. /** Tries to create an ActiveX control and embed it in this peer.
  41856. The peer controlIID is a pointer to an IID structure - it's treated
  41857. as a void* because when including the Juce headers, you might not always
  41858. have included windows.h first, in which case IID wouldn't be defined.
  41859. e.g. @code
  41860. const IID myIID = __uuidof (QTControl);
  41861. myControlComp->createControl (&myIID);
  41862. @endcode
  41863. */
  41864. bool createControl (const void* controlIID);
  41865. /** Deletes the ActiveX control, if one has been created.
  41866. */
  41867. void deleteControl();
  41868. /** Returns true if a control is currently in use. */
  41869. bool isControlOpen() const throw() { return control != 0; }
  41870. /** Does a QueryInterface call on the embedded control object.
  41871. This allows you to cast the control to whatever type of COM object you need.
  41872. The iid parameter is a pointer to an IID structure - it's treated
  41873. as a void* because when including the Juce headers, you might not always
  41874. have included windows.h first, in which case IID wouldn't be defined, but
  41875. you should just pass a pointer to an IID.
  41876. e.g. @code
  41877. const IID iid = __uuidof (IOleWindow);
  41878. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  41879. if (oleWindow != 0)
  41880. {
  41881. HWND hwnd;
  41882. oleWindow->GetWindow (&hwnd);
  41883. ...
  41884. oleWindow->Release();
  41885. }
  41886. @endcode
  41887. */
  41888. void* queryInterface (const void* iid) const;
  41889. /** Set this to false to stop mouse events being allowed through to the control.
  41890. */
  41891. void setMouseEventsAllowed (bool eventsCanReachControl);
  41892. /** Returns true if mouse events are allowed to get through to the control.
  41893. */
  41894. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  41895. /** @internal */
  41896. void paint (Graphics& g);
  41897. /** @internal */
  41898. void* originalWndProc;
  41899. juce_UseDebuggingNewOperator
  41900. private:
  41901. class Pimpl;
  41902. friend class Pimpl;
  41903. friend class ScopedPointer <Pimpl>;
  41904. ScopedPointer <Pimpl> control;
  41905. bool mouseEventsAllowed;
  41906. void setControlBounds (const Rectangle<int>& bounds) const;
  41907. void setControlVisible (bool b) const;
  41908. ActiveXControlComponent (const ActiveXControlComponent&);
  41909. ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  41910. };
  41911. #endif
  41912. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41913. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  41914. #endif
  41915. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41916. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41917. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41918. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41919. /**
  41920. A component containing controls to let the user change the audio settings of
  41921. an AudioDeviceManager object.
  41922. Very easy to use - just create one of these and show it to the user.
  41923. @see AudioDeviceManager
  41924. */
  41925. class JUCE_API AudioDeviceSelectorComponent : public Component,
  41926. public ComboBoxListener,
  41927. public ButtonListener,
  41928. public ChangeListener
  41929. {
  41930. public:
  41931. /** Creates the component.
  41932. If your app needs only output channels, you might ask for a maximum of 0 input
  41933. channels, and the component won't display any options for choosing the input
  41934. channels. And likewise if you're doing an input-only app.
  41935. @param deviceManager the device manager that this component should control
  41936. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  41937. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  41938. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  41939. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  41940. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  41941. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  41942. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  41943. treated as a set of separate mono channels.
  41944. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  41945. are shown, with an "advanced" button that shows the rest of them
  41946. */
  41947. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  41948. const int minAudioInputChannels,
  41949. const int maxAudioInputChannels,
  41950. const int minAudioOutputChannels,
  41951. const int maxAudioOutputChannels,
  41952. const bool showMidiInputOptions,
  41953. const bool showMidiOutputSelector,
  41954. const bool showChannelsAsStereoPairs,
  41955. const bool hideAdvancedOptionsWithButton);
  41956. /** Destructor */
  41957. ~AudioDeviceSelectorComponent();
  41958. /** @internal */
  41959. void resized();
  41960. /** @internal */
  41961. void comboBoxChanged (ComboBox*);
  41962. /** @internal */
  41963. void buttonClicked (Button*);
  41964. /** @internal */
  41965. void changeListenerCallback (void*);
  41966. /** @internal */
  41967. void childBoundsChanged (Component*);
  41968. juce_UseDebuggingNewOperator
  41969. private:
  41970. AudioDeviceManager& deviceManager;
  41971. ScopedPointer<ComboBox> deviceTypeDropDown;
  41972. ScopedPointer<Label> deviceTypeDropDownLabel;
  41973. ScopedPointer<Component> audioDeviceSettingsComp;
  41974. String audioDeviceSettingsCompType;
  41975. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  41976. const bool showChannelsAsStereoPairs;
  41977. const bool hideAdvancedOptionsWithButton;
  41978. class MidiInputSelectorComponentListBox;
  41979. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  41980. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  41981. ScopedPointer<ComboBox> midiOutputSelector;
  41982. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  41983. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  41984. AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  41985. };
  41986. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41987. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41988. #endif
  41989. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41990. /*** Start of inlined file: juce_BubbleComponent.h ***/
  41991. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41992. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41993. /**
  41994. A component for showing a message or other graphics inside a speech-bubble-shaped
  41995. outline, pointing at a location on the screen.
  41996. This is a base class that just draws and positions the bubble shape, but leaves
  41997. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  41998. that draws a text message.
  41999. To use it, create your subclass, then either add it to a parent component or
  42000. put it on the desktop with addToDesktop (0), use setPosition() to
  42001. resize and position it, then make it visible.
  42002. @see BubbleMessageComponent
  42003. */
  42004. class JUCE_API BubbleComponent : public Component
  42005. {
  42006. protected:
  42007. /** Creates a BubbleComponent.
  42008. Your subclass will need to implement the getContentSize() and paintContent()
  42009. methods to draw the bubble's contents.
  42010. */
  42011. BubbleComponent();
  42012. public:
  42013. /** Destructor. */
  42014. ~BubbleComponent();
  42015. /** A list of permitted placements for the bubble, relative to the co-ordinates
  42016. at which it should be pointing.
  42017. @see setAllowedPlacement
  42018. */
  42019. enum BubblePlacement
  42020. {
  42021. above = 1,
  42022. below = 2,
  42023. left = 4,
  42024. right = 8
  42025. };
  42026. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  42027. point at which it's pointing.
  42028. By default when setPosition() is called, the bubble will place itself either
  42029. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  42030. the values in BubblePlacement to restrict this choice.
  42031. E.g. if you only want your bubble to appear above or below the target area,
  42032. use setAllowedPlacement (above | below);
  42033. @see BubblePlacement
  42034. */
  42035. void setAllowedPlacement (int newPlacement);
  42036. /** Moves and resizes the bubble to point at a given component.
  42037. This will resize the bubble to fit its content, then find a position for it
  42038. so that it's next to, but doesn't overlap the given component.
  42039. It'll put itself either above, below, or to the side of the component depending
  42040. on where there's the most space, honouring any restrictions that were set
  42041. with setAllowedPlacement().
  42042. */
  42043. void setPosition (Component* componentToPointTo);
  42044. /** Moves and resizes the bubble to point at a given point.
  42045. This will resize the bubble to fit its content, then position it
  42046. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  42047. are relative to either the bubble component's parent component if it has one, or
  42048. they are screen co-ordinates if not.
  42049. It'll put itself either above, below, or to the side of this point, depending
  42050. on where there's the most space, honouring any restrictions that were set
  42051. with setAllowedPlacement().
  42052. */
  42053. void setPosition (int arrowTipX,
  42054. int arrowTipY);
  42055. /** Moves and resizes the bubble to point at a given rectangle.
  42056. This will resize the bubble to fit its content, then find a position for it
  42057. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  42058. co-ordinates are relative to either the bubble component's parent component
  42059. if it has one, or they are screen co-ordinates if not.
  42060. It'll put itself either above, below, or to the side of the component depending
  42061. on where there's the most space, honouring any restrictions that were set
  42062. with setAllowedPlacement().
  42063. */
  42064. void setPosition (const Rectangle<int>& rectangleToPointTo);
  42065. protected:
  42066. /** Subclasses should override this to return the size of the content they
  42067. want to draw inside the bubble.
  42068. */
  42069. virtual void getContentSize (int& width, int& height) = 0;
  42070. /** Subclasses should override this to draw their bubble's contents.
  42071. The graphics object's clip region and the dimensions passed in here are
  42072. set up to paint just the rectangle inside the bubble.
  42073. */
  42074. virtual void paintContent (Graphics& g, int width, int height) = 0;
  42075. public:
  42076. /** @internal */
  42077. void paint (Graphics& g);
  42078. juce_UseDebuggingNewOperator
  42079. private:
  42080. Rectangle<int> content;
  42081. int side, allowablePlacements;
  42082. float arrowTipX, arrowTipY;
  42083. DropShadowEffect shadow;
  42084. BubbleComponent (const BubbleComponent&);
  42085. BubbleComponent& operator= (const BubbleComponent&);
  42086. };
  42087. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42088. /*** End of inlined file: juce_BubbleComponent.h ***/
  42089. #endif
  42090. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42091. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  42092. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42093. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42094. /**
  42095. A speech-bubble component that displays a short message.
  42096. This can be used to show a message with the tail of the speech bubble
  42097. pointing to a particular component or location on the screen.
  42098. @see BubbleComponent
  42099. */
  42100. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  42101. private Timer
  42102. {
  42103. public:
  42104. /** Creates a bubble component.
  42105. After creating one a BubbleComponent, do the following:
  42106. - add it to an appropriate parent component, or put it on the
  42107. desktop with Component::addToDesktop (0).
  42108. - use the showAt() method to show a message.
  42109. - it will make itself invisible after it times-out (and can optionally
  42110. also delete itself), or you can reuse it somewhere else by calling
  42111. showAt() again.
  42112. */
  42113. BubbleMessageComponent (int fadeOutLengthMs = 150);
  42114. /** Destructor. */
  42115. ~BubbleMessageComponent();
  42116. /** Shows a message bubble at a particular position.
  42117. This shows the bubble with its stem pointing to the given location
  42118. (co-ordinates being relative to its parent component).
  42119. For details about exactly how it decides where to position itself, see
  42120. BubbleComponent::updatePosition().
  42121. @param x the x co-ordinate of end of the bubble's tail
  42122. @param y the y co-ordinate of end of the bubble's tail
  42123. @param message the text to display
  42124. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  42125. from its parent compnent. If this is 0 or less, it
  42126. will stay there until manually removed.
  42127. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  42128. mouse button is pressed (anywhere on the screen)
  42129. @param deleteSelfAfterUse if true, then the component will delete itself after
  42130. it becomes invisible
  42131. */
  42132. void showAt (int x, int y,
  42133. const String& message,
  42134. int numMillisecondsBeforeRemoving,
  42135. bool removeWhenMouseClicked = true,
  42136. bool deleteSelfAfterUse = false);
  42137. /** Shows a message bubble next to a particular component.
  42138. This shows the bubble with its stem pointing at the given component.
  42139. For details about exactly how it decides where to position itself, see
  42140. BubbleComponent::updatePosition().
  42141. @param component the component that you want to point at
  42142. @param message the text to display
  42143. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  42144. from its parent compnent. If this is 0 or less, it
  42145. will stay there until manually removed.
  42146. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  42147. mouse button is pressed (anywhere on the screen)
  42148. @param deleteSelfAfterUse if true, then the component will delete itself after
  42149. it becomes invisible
  42150. */
  42151. void showAt (Component* component,
  42152. const String& message,
  42153. int numMillisecondsBeforeRemoving,
  42154. bool removeWhenMouseClicked = true,
  42155. bool deleteSelfAfterUse = false);
  42156. /** @internal */
  42157. void getContentSize (int& w, int& h);
  42158. /** @internal */
  42159. void paintContent (Graphics& g, int w, int h);
  42160. /** @internal */
  42161. void timerCallback();
  42162. juce_UseDebuggingNewOperator
  42163. private:
  42164. int fadeOutLength, mouseClickCounter;
  42165. TextLayout textLayout;
  42166. int64 expiryTime;
  42167. bool deleteAfterUse;
  42168. void init (int numMillisecondsBeforeRemoving,
  42169. bool removeWhenMouseClicked,
  42170. bool deleteSelfAfterUse);
  42171. BubbleMessageComponent (const BubbleMessageComponent&);
  42172. BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  42173. };
  42174. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42175. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  42176. #endif
  42177. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  42178. /*** Start of inlined file: juce_ColourSelector.h ***/
  42179. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  42180. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  42181. /**
  42182. A component that lets the user choose a colour.
  42183. This shows RGB sliders and a colourspace that the user can pick colours from.
  42184. This class is also a ChangeBroadcaster, so listeners can register to be told
  42185. when the colour changes.
  42186. */
  42187. class JUCE_API ColourSelector : public Component,
  42188. public ChangeBroadcaster,
  42189. protected SliderListener
  42190. {
  42191. public:
  42192. /** Options for the type of selector to show. These are passed into the constructor. */
  42193. enum ColourSelectorOptions
  42194. {
  42195. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  42196. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  42197. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  42198. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  42199. };
  42200. /** Creates a ColourSelector object.
  42201. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  42202. which of the selector's features should be visible.
  42203. The edgeGap value specifies the amount of space to leave around the edge.
  42204. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  42205. colourspace and hue selector components.
  42206. */
  42207. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  42208. int edgeGap = 4,
  42209. int gapAroundColourSpaceComponent = 7);
  42210. /** Destructor. */
  42211. ~ColourSelector();
  42212. /** Returns the colour that the user has currently selected.
  42213. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  42214. register to be told when the colour changes.
  42215. @see setCurrentColour
  42216. */
  42217. const Colour getCurrentColour() const;
  42218. /** Changes the colour that is currently being shown.
  42219. */
  42220. void setCurrentColour (const Colour& newColour);
  42221. /** Tells the selector how many preset colour swatches you want to have on the component.
  42222. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42223. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42224. their values.
  42225. */
  42226. virtual int getNumSwatches() const;
  42227. /** Called by the selector to find out the colour of one of the swatches.
  42228. Your subclass should return the colour of the swatch with the given index.
  42229. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42230. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42231. their values.
  42232. */
  42233. virtual const Colour getSwatchColour (int index) const;
  42234. /** Called by the selector when the user puts a new colour into one of the swatches.
  42235. Your subclass should change the colour of the swatch with the given index.
  42236. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42237. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42238. their values.
  42239. */
  42240. virtual void setSwatchColour (int index, const Colour& newColour) const;
  42241. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  42242. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42243. methods.
  42244. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42245. */
  42246. enum ColourIds
  42247. {
  42248. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  42249. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  42250. };
  42251. juce_UseDebuggingNewOperator
  42252. private:
  42253. class ColourSpaceView;
  42254. class HueSelectorComp;
  42255. class SwatchComponent;
  42256. friend class ColourSpaceView;
  42257. friend class HueSelectorComp;
  42258. Colour colour;
  42259. float h, s, v;
  42260. Slider* sliders[4];
  42261. ColourSpaceView* colourSpace;
  42262. HueSelectorComp* hueSelector;
  42263. OwnedArray <SwatchComponent> swatchComponents;
  42264. const int flags;
  42265. int edgeGap;
  42266. Rectangle<int> previewArea;
  42267. void setHue (float newH);
  42268. void setSV (float newS, float newV);
  42269. void updateHSV();
  42270. void update();
  42271. void sliderValueChanged (Slider*);
  42272. void paint (Graphics& g);
  42273. void resized();
  42274. ColourSelector (const ColourSelector&);
  42275. ColourSelector& operator= (const ColourSelector&);
  42276. // this constructor is here temporarily to prevent old code compiling, because the parameters
  42277. // have changed - if you get an error here, update your code to use the new constructor instead..
  42278. // (xxx - note to self: remember to remove this at some point in the future)
  42279. ColourSelector (bool);
  42280. };
  42281. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  42282. /*** End of inlined file: juce_ColourSelector.h ***/
  42283. #endif
  42284. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42285. #endif
  42286. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42287. /*** Start of inlined file: juce_MagnifierComponent.h ***/
  42288. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42289. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42290. /**
  42291. A component that contains another component, and can magnify or shrink it.
  42292. This component will continually update its size so that it fits the zoomed
  42293. version of the content component that you put inside it, so don't try to
  42294. change the size of this component directly - instead change that of the
  42295. content component.
  42296. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  42297. to remap mouse events correctly. This means that the content component won't
  42298. appear to be a direct child of this component, and instead will think its
  42299. on the desktop.
  42300. */
  42301. class JUCE_API MagnifierComponent : public Component
  42302. {
  42303. public:
  42304. /** Creates a MagnifierComponent.
  42305. This component will continually update its size so that it fits the zoomed
  42306. version of the content component that you put inside it, so don't try to
  42307. change the size of this component directly - instead change that of the
  42308. content component.
  42309. @param contentComponent the component to add as the magnified one
  42310. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  42311. be deleted when this component is deleted. If false,
  42312. it's the caller's responsibility to delete it later.
  42313. */
  42314. MagnifierComponent (Component* contentComponent,
  42315. bool deleteContentCompWhenNoLongerNeeded);
  42316. /** Destructor. */
  42317. ~MagnifierComponent();
  42318. /** Returns the current content component. */
  42319. Component* getContentComponent() const { return content; }
  42320. /** Changes the zoom level.
  42321. The scale factor must be greater than zero. Values less than 1 will shrink the
  42322. image; values greater than 1 will multiply its size by this amount.
  42323. When this is called, this component will change its size to fit the full extent
  42324. of the newly zoomed content.
  42325. */
  42326. void setScaleFactor (double newScaleFactor);
  42327. /** Returns the current zoom factor. */
  42328. double getScaleFactor() const { return scaleFactor; }
  42329. /** Changes the quality setting used to rescale the graphics.
  42330. */
  42331. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  42332. juce_UseDebuggingNewOperator
  42333. /** @internal */
  42334. void childBoundsChanged (Component*);
  42335. private:
  42336. Component* content;
  42337. Component* holderComp;
  42338. double scaleFactor;
  42339. ComponentPeer* peer;
  42340. bool deleteContent;
  42341. Graphics::ResamplingQuality quality;
  42342. MouseInputSource mouseSource;
  42343. void paint (Graphics& g);
  42344. void mouseDown (const MouseEvent& e);
  42345. void mouseUp (const MouseEvent& e);
  42346. void mouseDrag (const MouseEvent& e);
  42347. void mouseMove (const MouseEvent& e);
  42348. void mouseEnter (const MouseEvent& e);
  42349. void mouseExit (const MouseEvent& e);
  42350. void mouseWheelMove (const MouseEvent& e, float, float);
  42351. void passOnMouseEventToPeer (const MouseEvent& e);
  42352. int scaleInt (int n) const;
  42353. MagnifierComponent (const MagnifierComponent&);
  42354. MagnifierComponent& operator= (const MagnifierComponent&);
  42355. };
  42356. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42357. /*** End of inlined file: juce_MagnifierComponent.h ***/
  42358. #endif
  42359. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42360. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  42361. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42362. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42363. /**
  42364. A component that displays a piano keyboard, whose notes can be clicked on.
  42365. This component will mimic a physical midi keyboard, showing the current state of
  42366. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  42367. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  42368. Another feature is that the computer keyboard can also be used to play notes. By
  42369. default it maps the top two rows of a standard querty keyboard to the notes, but
  42370. these can be remapped if needed. It will only respond to keypresses when it has
  42371. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  42372. The component is also a ChangeBroadcaster, so if you want to be informed when the
  42373. keyboard is scrolled, you can register a ChangeListener for callbacks.
  42374. @see MidiKeyboardState
  42375. */
  42376. class JUCE_API MidiKeyboardComponent : public Component,
  42377. public MidiKeyboardStateListener,
  42378. public ChangeBroadcaster,
  42379. private Timer,
  42380. private AsyncUpdater
  42381. {
  42382. public:
  42383. /** The direction of the keyboard.
  42384. @see setOrientation
  42385. */
  42386. enum Orientation
  42387. {
  42388. horizontalKeyboard,
  42389. verticalKeyboardFacingLeft,
  42390. verticalKeyboardFacingRight,
  42391. };
  42392. /** Creates a MidiKeyboardComponent.
  42393. @param state the midi keyboard model that this component will represent
  42394. @param orientation whether the keyboard is horizonal or vertical
  42395. */
  42396. MidiKeyboardComponent (MidiKeyboardState& state,
  42397. Orientation orientation);
  42398. /** Destructor. */
  42399. ~MidiKeyboardComponent();
  42400. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  42401. on the component.
  42402. Values are 0 to 1.0, where 1.0 is the heaviest.
  42403. @see setMidiChannel
  42404. */
  42405. void setVelocity (float velocity, bool useMousePositionForVelocity);
  42406. /** Changes the midi channel number that will be used for events triggered by clicking
  42407. on the component.
  42408. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  42409. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  42410. Although this is the channel used for outgoing events, the component can display
  42411. incoming events from more than one channel - see setMidiChannelsToDisplay()
  42412. @see setVelocity
  42413. */
  42414. void setMidiChannel (int midiChannelNumber);
  42415. /** Returns the midi channel that the keyboard is using for midi messages.
  42416. @see setMidiChannel
  42417. */
  42418. int getMidiChannel() const throw() { return midiChannel; }
  42419. /** Sets a mask to indicate which incoming midi channels should be represented by
  42420. key movements.
  42421. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  42422. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  42423. in this mask, the on-screen keys will also go down.
  42424. By default, this mask is set to 0xffff (all channels displayed).
  42425. @see setMidiChannel
  42426. */
  42427. void setMidiChannelsToDisplay (int midiChannelMask);
  42428. /** Returns the current set of midi channels represented by the component.
  42429. This is the value that was set with setMidiChannelsToDisplay().
  42430. */
  42431. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  42432. /** Changes the width used to draw the white keys. */
  42433. void setKeyWidth (float widthInPixels);
  42434. /** Returns the width that was set by setKeyWidth(). */
  42435. float getKeyWidth() const throw() { return keyWidth; }
  42436. /** Changes the keyboard's current direction. */
  42437. void setOrientation (Orientation newOrientation);
  42438. /** Returns the keyboard's current direction. */
  42439. const Orientation getOrientation() const throw() { return orientation; }
  42440. /** Sets the range of midi notes that the keyboard will be limited to.
  42441. By default the range is 0 to 127 (inclusive), but you can limit this if you
  42442. only want a restricted set of the keys to be shown.
  42443. Note that the values here are inclusive and must be between 0 and 127.
  42444. */
  42445. void setAvailableRange (int lowestNote,
  42446. int highestNote);
  42447. /** Returns the first note in the available range.
  42448. @see setAvailableRange
  42449. */
  42450. int getRangeStart() const throw() { return rangeStart; }
  42451. /** Returns the last note in the available range.
  42452. @see setAvailableRange
  42453. */
  42454. int getRangeEnd() const throw() { return rangeEnd; }
  42455. /** If the keyboard extends beyond the size of the component, this will scroll
  42456. it to show the given key at the start.
  42457. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  42458. base class to send a callback to any ChangeListeners that have been registered.
  42459. */
  42460. void setLowestVisibleKey (int noteNumber);
  42461. /** Returns the number of the first key shown in the component.
  42462. @see setLowestVisibleKey
  42463. */
  42464. int getLowestVisibleKey() const throw() { return firstKey; }
  42465. /** Returns the length of the black notes.
  42466. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  42467. */
  42468. int getBlackNoteLength() const throw() { return blackNoteLength; }
  42469. /** If set to true, then scroll buttons will appear at either end of the keyboard
  42470. if there are too many notes to fit them all in the component at once.
  42471. */
  42472. void setScrollButtonsVisible (bool canScroll);
  42473. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  42474. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42475. methods.
  42476. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42477. */
  42478. enum ColourIds
  42479. {
  42480. whiteNoteColourId = 0x1005000,
  42481. blackNoteColourId = 0x1005001,
  42482. keySeparatorLineColourId = 0x1005002,
  42483. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  42484. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  42485. textLabelColourId = 0x1005005,
  42486. upDownButtonBackgroundColourId = 0x1005006,
  42487. upDownButtonArrowColourId = 0x1005007
  42488. };
  42489. /** Returns the position within the component of the left-hand edge of a key.
  42490. Depending on the keyboard's orientation, this may be a horizontal or vertical
  42491. distance, in either direction.
  42492. */
  42493. int getKeyStartPosition (const int midiNoteNumber) const;
  42494. /** Deletes all key-mappings.
  42495. @see setKeyPressForNote
  42496. */
  42497. void clearKeyMappings();
  42498. /** Maps a key-press to a given note.
  42499. @param key the key that should trigger the note
  42500. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  42501. be. The actual midi note that gets played will be
  42502. this value + (12 * the current base octave). To change
  42503. the base octave, see setKeyPressBaseOctave()
  42504. */
  42505. void setKeyPressForNote (const KeyPress& key,
  42506. int midiNoteOffsetFromC);
  42507. /** Removes any key-mappings for a given note.
  42508. For a description of what the note number means, see setKeyPressForNote().
  42509. */
  42510. void removeKeyPressForNote (int midiNoteOffsetFromC);
  42511. /** Changes the base note above which key-press-triggered notes are played.
  42512. The set of key-mappings that trigger notes can be moved up and down to cover
  42513. the entire scale using this method.
  42514. The value passed in is an octave number between 0 and 10 (inclusive), and
  42515. indicates which C is the base note to which the key-mapped notes are
  42516. relative.
  42517. */
  42518. void setKeyPressBaseOctave (int newOctaveNumber);
  42519. /** This sets the octave number which is shown as the octave number for middle C.
  42520. This affects only the default implementation of getWhiteNoteText(), which
  42521. passes this octave number to MidiMessage::getMidiNoteName() in order to
  42522. get the note text. See MidiMessage::getMidiNoteName() for more info about
  42523. the parameter.
  42524. By default this value is set to 3.
  42525. @see getOctaveForMiddleC
  42526. */
  42527. void setOctaveForMiddleC (int octaveNumForMiddleC);
  42528. /** This returns the value set by setOctaveForMiddleC().
  42529. @see setOctaveForMiddleC
  42530. */
  42531. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  42532. /** @internal */
  42533. void paint (Graphics& g);
  42534. /** @internal */
  42535. void resized();
  42536. /** @internal */
  42537. void mouseMove (const MouseEvent& e);
  42538. /** @internal */
  42539. void mouseDrag (const MouseEvent& e);
  42540. /** @internal */
  42541. void mouseDown (const MouseEvent& e);
  42542. /** @internal */
  42543. void mouseUp (const MouseEvent& e);
  42544. /** @internal */
  42545. void mouseEnter (const MouseEvent& e);
  42546. /** @internal */
  42547. void mouseExit (const MouseEvent& e);
  42548. /** @internal */
  42549. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  42550. /** @internal */
  42551. void timerCallback();
  42552. /** @internal */
  42553. bool keyStateChanged (bool isKeyDown);
  42554. /** @internal */
  42555. void focusLost (FocusChangeType cause);
  42556. /** @internal */
  42557. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  42558. /** @internal */
  42559. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  42560. /** @internal */
  42561. void handleAsyncUpdate();
  42562. /** @internal */
  42563. void colourChanged();
  42564. juce_UseDebuggingNewOperator
  42565. protected:
  42566. friend class MidiKeyboardUpDownButton;
  42567. /** Draws a white note in the given rectangle.
  42568. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42569. currently pressed down.
  42570. When doing this, be sure to note the keyboard's orientation.
  42571. */
  42572. virtual void drawWhiteNote (int midiNoteNumber,
  42573. Graphics& g,
  42574. int x, int y, int w, int h,
  42575. bool isDown, bool isOver,
  42576. const Colour& lineColour,
  42577. const Colour& textColour);
  42578. /** Draws a black note in the given rectangle.
  42579. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42580. currently pressed down.
  42581. When doing this, be sure to note the keyboard's orientation.
  42582. */
  42583. virtual void drawBlackNote (int midiNoteNumber,
  42584. Graphics& g,
  42585. int x, int y, int w, int h,
  42586. bool isDown, bool isOver,
  42587. const Colour& noteFillColour);
  42588. /** Allows text to be drawn on the white notes.
  42589. By default this is used to label the C in each octave, but could be used for other things.
  42590. @see setOctaveForMiddleC
  42591. */
  42592. virtual const String getWhiteNoteText (const int midiNoteNumber);
  42593. /** Draws the up and down buttons that change the base note. */
  42594. virtual void drawUpDownButton (Graphics& g, int w, int h,
  42595. const bool isMouseOver,
  42596. const bool isButtonPressed,
  42597. const bool movesOctavesUp);
  42598. /** Callback when the mouse is clicked on a key.
  42599. You could use this to do things like handle right-clicks on keys, etc.
  42600. Return true if you want the click to trigger the note, or false if you
  42601. want to handle it yourself and not have the note played.
  42602. @see mouseDraggedToKey
  42603. */
  42604. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  42605. /** Callback when the mouse is dragged from one key onto another.
  42606. @see mouseDownOnKey
  42607. */
  42608. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  42609. /** Calculates the positon of a given midi-note.
  42610. This can be overridden to create layouts with custom key-widths.
  42611. @param midiNoteNumber the note to find
  42612. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  42613. @param x the x position of the left-hand edge of the key (this method
  42614. always works in terms of a horizontal keyboard)
  42615. @param w the width of the key
  42616. */
  42617. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  42618. int& x, int& w) const;
  42619. private:
  42620. MidiKeyboardState& state;
  42621. int xOffset, blackNoteLength;
  42622. float keyWidth;
  42623. Orientation orientation;
  42624. int midiChannel, midiInChannelMask;
  42625. float velocity;
  42626. int noteUnderMouse, mouseDownNote;
  42627. BigInteger keysPressed, keysCurrentlyDrawnDown;
  42628. int rangeStart, rangeEnd, firstKey;
  42629. bool canScroll, mouseDragging, useMousePositionForVelocity;
  42630. Button* scrollDown;
  42631. Button* scrollUp;
  42632. Array <KeyPress> keyPresses;
  42633. Array <int> keyPressNotes;
  42634. int keyMappingOctave;
  42635. int octaveNumForMiddleC;
  42636. static const uint8 whiteNotes[];
  42637. static const uint8 blackNotes[];
  42638. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  42639. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  42640. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  42641. void resetAnyKeysInUse();
  42642. void updateNoteUnderMouse (const Point<int>& pos);
  42643. void repaintNote (const int midiNoteNumber);
  42644. MidiKeyboardComponent (const MidiKeyboardComponent&);
  42645. MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  42646. };
  42647. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42648. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  42649. #endif
  42650. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42651. /*** Start of inlined file: juce_NSViewComponent.h ***/
  42652. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42653. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42654. #if ! DOXYGEN
  42655. class NSViewComponentInternal;
  42656. #endif
  42657. #if JUCE_MAC || DOXYGEN
  42658. /**
  42659. A Mac-specific class that can create and embed an NSView inside itself.
  42660. To use it, create one of these, put it in place and make sure it's visible in a
  42661. window, then use setView() to assign an NSView to it. The view will then be
  42662. moved and resized to follow the movements of this component.
  42663. Of course, since the view is a native object, it'll obliterate any
  42664. juce components that may overlap this component, but that's life.
  42665. */
  42666. class JUCE_API NSViewComponent : public Component
  42667. {
  42668. public:
  42669. /** Create an initially-empty container. */
  42670. NSViewComponent();
  42671. /** Destructor. */
  42672. ~NSViewComponent();
  42673. /** Assigns an NSView to this peer.
  42674. The view will be retained and released by this component for as long as
  42675. it is needed. To remove the current view, just call setView (0).
  42676. Note: a void* is used here to avoid including the cocoa headers as
  42677. part of the juce.h, but the method expects an NSView*.
  42678. */
  42679. void setView (void* nsView);
  42680. /** Returns the current NSView.
  42681. Note: a void* is returned here to avoid including the cocoa headers as
  42682. a requirement of juce.h, so you should just cast the object to an NSView*.
  42683. */
  42684. void* getView() const;
  42685. /** @internal */
  42686. void paint (Graphics& g);
  42687. juce_UseDebuggingNewOperator
  42688. private:
  42689. friend class NSViewComponentInternal;
  42690. ScopedPointer <NSViewComponentInternal> info;
  42691. NSViewComponent (const NSViewComponent&);
  42692. NSViewComponent& operator= (const NSViewComponent&);
  42693. };
  42694. #endif
  42695. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42696. /*** End of inlined file: juce_NSViewComponent.h ***/
  42697. #endif
  42698. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42699. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  42700. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42701. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42702. // this is used to disable OpenGL, and is defined in juce_Config.h
  42703. #if JUCE_OPENGL || DOXYGEN
  42704. /**
  42705. Represents the various properties of an OpenGL bitmap format.
  42706. @see OpenGLComponent::setPixelFormat
  42707. */
  42708. class JUCE_API OpenGLPixelFormat
  42709. {
  42710. public:
  42711. /** Creates an OpenGLPixelFormat.
  42712. The default constructor just initialises the object as a simple 8-bit
  42713. RGBA format.
  42714. */
  42715. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  42716. int alphaBits = 8,
  42717. int depthBufferBits = 16,
  42718. int stencilBufferBits = 0);
  42719. OpenGLPixelFormat (const OpenGLPixelFormat&);
  42720. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  42721. bool operator== (const OpenGLPixelFormat&) const;
  42722. int redBits; /**< The number of bits per pixel to use for the red channel. */
  42723. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  42724. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  42725. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  42726. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  42727. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  42728. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  42729. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  42730. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  42731. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  42732. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  42733. /** Returns a list of all the pixel formats that can be used in this system.
  42734. A reference component is needed in case there are multiple screens with different
  42735. capabilities - in which case, the one that the component is on will be used.
  42736. */
  42737. static void getAvailablePixelFormats (Component* component,
  42738. OwnedArray <OpenGLPixelFormat>& results);
  42739. juce_UseDebuggingNewOperator
  42740. };
  42741. /**
  42742. A base class for types of OpenGL context.
  42743. An OpenGLComponent will supply its own context for drawing in its window.
  42744. */
  42745. class JUCE_API OpenGLContext
  42746. {
  42747. public:
  42748. /** Destructor. */
  42749. virtual ~OpenGLContext();
  42750. /** Makes this context the currently active one. */
  42751. virtual bool makeActive() const throw() = 0;
  42752. /** If this context is currently active, it is disactivated. */
  42753. virtual bool makeInactive() const throw() = 0;
  42754. /** Returns true if this context is currently active. */
  42755. virtual bool isActive() const throw() = 0;
  42756. /** Swaps the buffers (if the context can do this). */
  42757. virtual void swapBuffers() = 0;
  42758. /** Sets whether the context checks the vertical sync before swapping.
  42759. The value is the number of frames to allow between buffer-swapping. This is
  42760. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  42761. and greater numbers indicate that it should swap less often.
  42762. Returns true if it sets the value successfully.
  42763. */
  42764. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  42765. /** Returns the current swap-sync interval.
  42766. See setSwapInterval() for info about the value returned.
  42767. */
  42768. virtual int getSwapInterval() const = 0;
  42769. /** Returns the pixel format being used by this context. */
  42770. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  42771. /** For windowed contexts, this moves the context within the bounds of
  42772. its parent window.
  42773. */
  42774. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  42775. /** For windowed contexts, this triggers a repaint of the window.
  42776. (Not relevent on all platforms).
  42777. */
  42778. virtual void repaint() = 0;
  42779. /** Returns an OS-dependent handle to the raw GL context.
  42780. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  42781. a GLXContext.
  42782. */
  42783. virtual void* getRawContext() const throw() = 0;
  42784. /** Returns the context that's currently in active use by the calling thread.
  42785. Returns 0 if there isn't an active context.
  42786. */
  42787. static OpenGLContext* getCurrentContext();
  42788. juce_UseDebuggingNewOperator
  42789. protected:
  42790. OpenGLContext() throw();
  42791. };
  42792. /**
  42793. A component that contains an OpenGL canvas.
  42794. Override this, add it to whatever component you want to, and use the renderOpenGL()
  42795. method to draw its contents.
  42796. */
  42797. class JUCE_API OpenGLComponent : public Component
  42798. {
  42799. public:
  42800. /** Used to select the type of openGL API to use, if more than one choice is available
  42801. on a particular platform.
  42802. */
  42803. enum OpenGLType
  42804. {
  42805. openGLDefault = 0,
  42806. #if JUCE_IPHONE
  42807. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  42808. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  42809. #endif
  42810. };
  42811. /** Creates an OpenGLComponent. */
  42812. OpenGLComponent (OpenGLType type = openGLDefault);
  42813. /** Destructor. */
  42814. ~OpenGLComponent();
  42815. /** Changes the pixel format used by this component.
  42816. @see OpenGLPixelFormat::getAvailablePixelFormats()
  42817. */
  42818. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  42819. /** Returns the pixel format that this component is currently using. */
  42820. const OpenGLPixelFormat getPixelFormat() const;
  42821. /** Specifies an OpenGL context which should be shared with the one that this
  42822. component is using.
  42823. This is an OpenGL feature that lets two contexts share their texture data.
  42824. Note that this pointer is stored by the component, and when the component
  42825. needs to recreate its internal context for some reason, the same context
  42826. will be used again to share lists. So if you pass a context in here,
  42827. don't delete the context while this component is still using it! You can
  42828. call shareWith (0) to stop this component from sharing with it.
  42829. */
  42830. void shareWith (OpenGLContext* contextToShareListsWith);
  42831. /** Returns the context that this component is sharing with.
  42832. @see shareWith
  42833. */
  42834. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  42835. /** Flips the openGL buffers over. */
  42836. void swapBuffers();
  42837. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  42838. When this is called, makeCurrentContextActive() will already have been called
  42839. for you, so you just need to draw.
  42840. */
  42841. virtual void renderOpenGL() = 0;
  42842. /** This method is called when the component creates a new OpenGL context.
  42843. A new context may be created when the component is first used, or when it
  42844. is moved to a different window, or when the window is hidden and re-shown,
  42845. etc.
  42846. You can use this callback as an opportunity to set up things like textures
  42847. that your context needs.
  42848. New contexts are created on-demand by the makeCurrentContextActive() method - so
  42849. if the context is deleted, e.g. by changing the pixel format or window, no context
  42850. will be created until the next call to makeCurrentContextActive(), which will
  42851. synchronously create one and call this method. This means that if you're using
  42852. a non-GUI thread for rendering, you can make sure this method is be called by
  42853. your renderer thread.
  42854. When this callback happens, the context will already have been made current
  42855. using the makeCurrentContextActive() method, so there's no need to call it
  42856. again in your code.
  42857. */
  42858. virtual void newOpenGLContextCreated() = 0;
  42859. /** Returns the context that will draw into this component.
  42860. This may return 0 if the component is currently invisible or hasn't currently
  42861. got a context. The context object can be deleted and a new one created during
  42862. the lifetime of this component, and there may be times when it doesn't have one.
  42863. @see newOpenGLContextCreated()
  42864. */
  42865. OpenGLContext* getCurrentContext() const throw() { return context; }
  42866. /** Makes this component the current openGL context.
  42867. You might want to use this in things like your resize() method, before calling
  42868. GL commands.
  42869. If this returns false, then the context isn't active, so you should avoid
  42870. making any calls.
  42871. This call may actually create a context if one isn't currently initialised. If
  42872. it does this, it will also synchronously call the newOpenGLContextCreated()
  42873. method to let you initialise it as necessary.
  42874. @see OpenGLContext::makeActive
  42875. */
  42876. bool makeCurrentContextActive();
  42877. /** Stops the current component being the active OpenGL context.
  42878. This is the opposite of makeCurrentContextActive()
  42879. @see OpenGLContext::makeInactive
  42880. */
  42881. void makeCurrentContextInactive();
  42882. /** Returns true if this component is the active openGL context for the
  42883. current thread.
  42884. @see OpenGLContext::isActive
  42885. */
  42886. bool isActiveContext() const throw();
  42887. /** Calls the rendering callback, and swaps the buffers afterwards.
  42888. This is called automatically by paint() when the component needs to be rendered.
  42889. It can be overridden if you need to decouple the rendering from the paint callback
  42890. and render with a custom thread.
  42891. Returns true if the operation succeeded.
  42892. */
  42893. virtual bool renderAndSwapBuffers();
  42894. /** This returns a critical section that can be used to lock the current context.
  42895. Because the context that is used by this component can change, e.g. when the
  42896. component is shown or hidden, then if you're rendering to it on a background
  42897. thread, this allows you to lock the context for the duration of your rendering
  42898. routine.
  42899. */
  42900. CriticalSection& getContextLock() throw() { return contextLock; }
  42901. /** @internal */
  42902. void paint (Graphics& g);
  42903. /** Returns the native handle of an embedded heavyweight window, if there is one.
  42904. E.g. On windows, this will return the HWND of the sub-window containing
  42905. the opengl context, on the mac it'll be the NSOpenGLView.
  42906. */
  42907. void* getNativeWindowHandle() const;
  42908. /** Call this to manually delete the current GL context, if there is one.
  42909. This can be useful to cause a clear-out of the context, which will be automatically
  42910. re-created when it's needed.
  42911. */
  42912. void deleteContext();
  42913. juce_UseDebuggingNewOperator
  42914. private:
  42915. const OpenGLType type;
  42916. class OpenGLComponentWatcher;
  42917. friend class OpenGLComponentWatcher;
  42918. friend class ScopedPointer <OpenGLComponentWatcher>;
  42919. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  42920. ScopedPointer <OpenGLContext> context;
  42921. OpenGLContext* contextToShareListsWith;
  42922. CriticalSection contextLock;
  42923. OpenGLPixelFormat preferredPixelFormat;
  42924. bool needToUpdateViewport;
  42925. OpenGLContext* createContext();
  42926. void updateContextPosition();
  42927. void internalRepaint (int x, int y, int w, int h);
  42928. OpenGLComponent (const OpenGLComponent&);
  42929. OpenGLComponent& operator= (const OpenGLComponent&);
  42930. };
  42931. #endif
  42932. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42933. /*** End of inlined file: juce_OpenGLComponent.h ***/
  42934. #endif
  42935. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42936. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  42937. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42938. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42939. /**
  42940. A component with a set of buttons at the top for changing between pages of
  42941. preferences.
  42942. This is just a handy way of writing a Mac-style preferences panel where you
  42943. have a row of buttons along the top for the different preference categories,
  42944. each button having an icon above its name. Clicking these will show an
  42945. appropriate prefs page below it.
  42946. You can either put one of these inside your own component, or just use the
  42947. showInDialogBox() method to show it in a window and run it modally.
  42948. To use it, just add a set of named pages with the addSettingsPage() method,
  42949. and implement the createComponentForPage() method to create suitable components
  42950. for each of these pages.
  42951. */
  42952. class JUCE_API PreferencesPanel : public Component,
  42953. private ButtonListener
  42954. {
  42955. public:
  42956. /** Creates an empty panel.
  42957. Use addSettingsPage() to add some pages to it in your constructor.
  42958. */
  42959. PreferencesPanel();
  42960. /** Destructor. */
  42961. ~PreferencesPanel();
  42962. /** Creates a page using a set of drawables to define the page's icon.
  42963. Note that the other version of this method is much easier if you're using
  42964. an image instead of a custom drawable.
  42965. @param pageTitle the name of this preferences page - you'll need to
  42966. make sure your createComponentForPage() method creates
  42967. a suitable component when it is passed this name
  42968. @param normalIcon the drawable to display in the page's button normally
  42969. @param overIcon the drawable to display in the page's button when the mouse is over
  42970. @param downIcon the drawable to display in the page's button when the button is down
  42971. @see DrawableButton
  42972. */
  42973. void addSettingsPage (const String& pageTitle,
  42974. const Drawable* normalIcon,
  42975. const Drawable* overIcon,
  42976. const Drawable* downIcon);
  42977. /** Creates a page using a set of drawables to define the page's icon.
  42978. The other version of this method gives you more control over the icon, but this
  42979. one is much easier if you're just loading it from a file.
  42980. @param pageTitle the name of this preferences page - you'll need to
  42981. make sure your createComponentForPage() method creates
  42982. a suitable component when it is passed this name
  42983. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  42984. For this to look good, you'll probably want to use a nice
  42985. transparent png file.
  42986. @param imageDataSize the size of the image data, in bytes
  42987. */
  42988. void addSettingsPage (const String& pageTitle,
  42989. const void* imageData,
  42990. int imageDataSize);
  42991. /** Utility method to display this panel in a DialogWindow.
  42992. Calling this will create a DialogWindow containing this panel with the
  42993. given size and title, and will run it modally, returning when the user
  42994. closes the dialog box.
  42995. */
  42996. void showInDialogBox (const String& dialogtitle,
  42997. int dialogWidth,
  42998. int dialogHeight,
  42999. const Colour& backgroundColour = Colours::white);
  43000. /** Subclasses must override this to return a component for each preferences page.
  43001. The subclass should return a pointer to a new component representing the named
  43002. page, which the panel will then display.
  43003. The panel will delete the component later when the user goes to another page
  43004. or deletes the panel.
  43005. */
  43006. virtual Component* createComponentForPage (const String& pageName) = 0;
  43007. /** Changes the current page being displayed. */
  43008. void setCurrentPage (const String& pageName);
  43009. /** @internal */
  43010. void resized();
  43011. /** @internal */
  43012. void paint (Graphics& g);
  43013. /** @internal */
  43014. void buttonClicked (Button* button);
  43015. juce_UseDebuggingNewOperator
  43016. private:
  43017. String currentPageName;
  43018. ScopedPointer <Component> currentPage;
  43019. int buttonSize;
  43020. PreferencesPanel (const PreferencesPanel&);
  43021. PreferencesPanel& operator= (const PreferencesPanel&);
  43022. };
  43023. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  43024. /*** End of inlined file: juce_PreferencesPanel.h ***/
  43025. #endif
  43026. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43027. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  43028. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43029. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43030. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  43031. // amalgamated build)
  43032. #if JUCE_WINDOWS
  43033. typedef ActiveXControlComponent QTCompBaseClass;
  43034. #elif JUCE_MAC
  43035. typedef NSViewComponent QTCompBaseClass;
  43036. #endif
  43037. // this is used to disable QuickTime, and is defined in juce_Config.h
  43038. #if JUCE_QUICKTIME || DOXYGEN
  43039. /**
  43040. A window that can play back a QuickTime movie.
  43041. */
  43042. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  43043. {
  43044. public:
  43045. /** Creates a QuickTimeMovieComponent, initially blank.
  43046. Use the loadMovie() method to load a movie once you've added the
  43047. component to a window, (or put it on the desktop as a heavyweight window).
  43048. Loading a movie when the component isn't visible can cause problems, as
  43049. QuickTime needs a window handle to initialise properly.
  43050. */
  43051. QuickTimeMovieComponent();
  43052. /** Destructor. */
  43053. ~QuickTimeMovieComponent();
  43054. /** Returns true if QT is installed and working on this machine.
  43055. */
  43056. static bool isQuickTimeAvailable() throw();
  43057. /** Tries to load a QuickTime movie from a file into the player.
  43058. It's best to call this function once you've added the component to a window,
  43059. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43060. component isn't visible can cause problems, because QuickTime needs a window
  43061. handle to do its stuff.
  43062. @param movieFile the .mov file to open
  43063. @param isControllerVisible whether to show a controller bar at the bottom
  43064. @returns true if the movie opens successfully
  43065. */
  43066. bool loadMovie (const File& movieFile,
  43067. bool isControllerVisible);
  43068. /** Tries to load a QuickTime movie from a URL into the player.
  43069. It's best to call this function once you've added the component to a window,
  43070. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43071. component isn't visible can cause problems, because QuickTime needs a window
  43072. handle to do its stuff.
  43073. @param movieURL the .mov file to open
  43074. @param isControllerVisible whether to show a controller bar at the bottom
  43075. @returns true if the movie opens successfully
  43076. */
  43077. bool loadMovie (const URL& movieURL,
  43078. bool isControllerVisible);
  43079. /** Tries to load a QuickTime movie from a stream into the player.
  43080. It's best to call this function once you've added the component to a window,
  43081. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43082. component isn't visible can cause problems, because QuickTime needs a window
  43083. handle to do its stuff.
  43084. @param movieStream a stream containing a .mov file. The component may try
  43085. to read the whole stream before playing, rather than
  43086. streaming from it.
  43087. @param isControllerVisible whether to show a controller bar at the bottom
  43088. @returns true if the movie opens successfully
  43089. */
  43090. bool loadMovie (InputStream* movieStream,
  43091. bool isControllerVisible);
  43092. /** Closes the movie, if one is open. */
  43093. void closeMovie();
  43094. /** Returns the movie file that is currently open.
  43095. If there isn't one, this returns File::nonexistent
  43096. */
  43097. const File getCurrentMovieFile() const;
  43098. /** Returns true if there's currently a movie open. */
  43099. bool isMovieOpen() const;
  43100. /** Returns the length of the movie, in seconds. */
  43101. double getMovieDuration() const;
  43102. /** Returns the movie's natural size, in pixels.
  43103. You can use this to resize the component to show the movie at its preferred
  43104. scale.
  43105. If no movie is loaded, the size returned will be 0 x 0.
  43106. */
  43107. void getMovieNormalSize (int& width, int& height) const;
  43108. /** This will position the component within a given area, keeping its aspect
  43109. ratio correct according to the movie's normal size.
  43110. The component will be made as large as it can go within the space, and will
  43111. be aligned according to the justification value if this means there are gaps at
  43112. the top or sides.
  43113. */
  43114. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  43115. const RectanglePlacement& placement);
  43116. /** Starts the movie playing. */
  43117. void play();
  43118. /** Stops the movie playing. */
  43119. void stop();
  43120. /** Returns true if the movie is currently playing. */
  43121. bool isPlaying() const;
  43122. /** Moves the movie's position back to the start. */
  43123. void goToStart();
  43124. /** Sets the movie's position to a given time. */
  43125. void setPosition (double seconds);
  43126. /** Returns the current play position of the movie. */
  43127. double getPosition() const;
  43128. /** Changes the movie playback rate.
  43129. A value of 1 is normal speed, greater values play it proportionately faster,
  43130. smaller values play it slower.
  43131. */
  43132. void setSpeed (float newSpeed);
  43133. /** Changes the movie's playback volume.
  43134. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  43135. */
  43136. void setMovieVolume (float newVolume);
  43137. /** Returns the movie's playback volume.
  43138. @returns the volume in the range 0 (silent) to 1.0 (full)
  43139. */
  43140. float getMovieVolume() const;
  43141. /** Tells the movie whether it should loop. */
  43142. void setLooping (bool shouldLoop);
  43143. /** Returns true if the movie is currently looping.
  43144. @see setLooping
  43145. */
  43146. bool isLooping() const;
  43147. /** True if the native QuickTime controller bar is shown in the window.
  43148. @see loadMovie
  43149. */
  43150. bool isControllerVisible() const;
  43151. /** @internal */
  43152. void paint (Graphics& g);
  43153. juce_UseDebuggingNewOperator
  43154. private:
  43155. File movieFile;
  43156. bool movieLoaded, controllerVisible, looping;
  43157. #if JUCE_WINDOWS
  43158. void parentHierarchyChanged();
  43159. void visibilityChanged();
  43160. void createControlIfNeeded();
  43161. bool isControlCreated() const;
  43162. class Pimpl;
  43163. friend class ScopedPointer <Pimpl>;
  43164. ScopedPointer <Pimpl> pimpl;
  43165. #else
  43166. void* movie;
  43167. #endif
  43168. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  43169. QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  43170. };
  43171. #endif
  43172. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43173. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  43174. #endif
  43175. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43176. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  43177. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43178. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43179. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  43180. /**
  43181. On Windows only, this component sits in the taskbar tray as a small icon.
  43182. To use it, just create one of these components, but don't attempt to make it
  43183. visible, add it to a parent, or put it on the desktop.
  43184. You can then call setIconImage() to create an icon for it in the taskbar.
  43185. To change the icon's tooltip, you can use setIconTooltip().
  43186. To respond to mouse-events, you can override the normal mouseDown(),
  43187. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  43188. position will not be valid, you can use this to respond to clicks. Traditionally
  43189. you'd use a left-click to show your application's window, and a right-click
  43190. to show a pop-up menu.
  43191. */
  43192. class JUCE_API SystemTrayIconComponent : public Component
  43193. {
  43194. public:
  43195. SystemTrayIconComponent();
  43196. /** Destructor. */
  43197. ~SystemTrayIconComponent();
  43198. /** Changes the image shown in the taskbar.
  43199. */
  43200. void setIconImage (const Image& newImage);
  43201. /** Changes the tooltip that Windows shows above the icon. */
  43202. void setIconTooltip (const String& tooltip);
  43203. #if JUCE_LINUX
  43204. /** @internal */
  43205. void paint (Graphics& g);
  43206. #endif
  43207. juce_UseDebuggingNewOperator
  43208. private:
  43209. SystemTrayIconComponent (const SystemTrayIconComponent&);
  43210. SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  43211. };
  43212. #endif
  43213. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43214. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  43215. #endif
  43216. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43217. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  43218. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43219. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43220. #if JUCE_WEB_BROWSER || DOXYGEN
  43221. #if ! DOXYGEN
  43222. class WebBrowserComponentInternal;
  43223. #endif
  43224. /**
  43225. A component that displays an embedded web browser.
  43226. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  43227. Windows, probably IE.
  43228. */
  43229. class JUCE_API WebBrowserComponent : public Component
  43230. {
  43231. public:
  43232. /** Creates a WebBrowserComponent.
  43233. Once it's created and visible, send the browser to a URL using goToURL().
  43234. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  43235. component is taken offscreen, it'll clear the current page
  43236. and replace it with a blank page - this can be handy to stop
  43237. the browser using resources in the background when it's not
  43238. actually being used.
  43239. */
  43240. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  43241. /** Destructor. */
  43242. ~WebBrowserComponent();
  43243. /** Sends the browser to a particular URL.
  43244. @param url the URL to go to.
  43245. @param headers an optional set of parameters to put in the HTTP header. If
  43246. you supply this, it should be a set of string in the form
  43247. "HeaderKey: HeaderValue"
  43248. @param postData an optional block of data that will be attached to the HTTP
  43249. POST request
  43250. */
  43251. void goToURL (const String& url,
  43252. const StringArray* headers = 0,
  43253. const MemoryBlock* postData = 0);
  43254. /** Stops the current page loading.
  43255. */
  43256. void stop();
  43257. /** Sends the browser back one page.
  43258. */
  43259. void goBack();
  43260. /** Sends the browser forward one page.
  43261. */
  43262. void goForward();
  43263. /** Refreshes the browser.
  43264. */
  43265. void refresh();
  43266. /** This callback is called when the browser is about to navigate
  43267. to a new location.
  43268. You can override this method to perform some action when the user
  43269. tries to go to a particular URL. To allow the operation to carry on,
  43270. return true, or return false to stop the navigation happening.
  43271. */
  43272. virtual bool pageAboutToLoad (const String& newURL);
  43273. /** @internal */
  43274. void paint (Graphics& g);
  43275. /** @internal */
  43276. void resized();
  43277. /** @internal */
  43278. void parentHierarchyChanged();
  43279. /** @internal */
  43280. void visibilityChanged();
  43281. juce_UseDebuggingNewOperator
  43282. private:
  43283. WebBrowserComponentInternal* browser;
  43284. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  43285. String lastURL;
  43286. StringArray lastHeaders;
  43287. MemoryBlock lastPostData;
  43288. void reloadLastURL();
  43289. void checkWindowAssociation();
  43290. WebBrowserComponent (const WebBrowserComponent&);
  43291. WebBrowserComponent& operator= (const WebBrowserComponent&);
  43292. };
  43293. #endif
  43294. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43295. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  43296. #endif
  43297. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43298. #endif
  43299. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  43300. /*** Start of inlined file: juce_CallOutBox.h ***/
  43301. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  43302. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  43303. /**
  43304. A box with a small arrow that can be used as a temporary pop-up window to show
  43305. extra controls when a button or other component is clicked.
  43306. Using one of these is similar to having a popup menu attached to a button or
  43307. other component - but it looks fancier, and has an arrow that can indicate the
  43308. object that it applies to.
  43309. Normally, you'd create one of these on the stack and run it modally, e.g.
  43310. @code
  43311. void mouseUp (const MouseEvent& e)
  43312. {
  43313. MyContentComponent content;
  43314. content.setSize (300, 300);
  43315. CallOutBox callOut (content, *this, 0);
  43316. callOut.runModalLoop();
  43317. }
  43318. @endcode
  43319. The call-out will resize and position itself when the content changes size.
  43320. */
  43321. class JUCE_API CallOutBox : public Component
  43322. {
  43323. public:
  43324. /** Creates a CallOutBox.
  43325. @param contentComponent the component to display inside the call-out. This should
  43326. already have a size set (although the call-out will also
  43327. update itself when the component's size is changed later).
  43328. Obviously this component must not be deleted until the
  43329. call-out box has been deleted.
  43330. @param componentToPointTo the component that the call-out's arrow should point towards
  43331. @param parentComponent if non-zero, this is the component to add the call-out to. If
  43332. this is zero, the call-out will be added to the desktop.
  43333. */
  43334. CallOutBox (Component& contentComponent,
  43335. Component& componentToPointTo,
  43336. Component* parentComponent);
  43337. /** Destructor. */
  43338. ~CallOutBox();
  43339. /** Changes the length of the arrow. */
  43340. void setArrowSize (float newSize);
  43341. /** Updates the position and size of the box.
  43342. You shouldn't normally need to call this, unless you need more precise control over the
  43343. layout.
  43344. @param newAreaToPointTo the rectangle to make the box's arrow point to
  43345. @param newAreaToFitIn the area within which the box's position should be constrained
  43346. */
  43347. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  43348. const Rectangle<int>& newAreaToFitIn);
  43349. /** @internal */
  43350. void paint (Graphics& g);
  43351. /** @internal */
  43352. void resized();
  43353. /** @internal */
  43354. void moved();
  43355. /** @internal */
  43356. void childBoundsChanged (Component*);
  43357. /** @internal */
  43358. bool hitTest (int x, int y);
  43359. /** @internal */
  43360. void inputAttemptWhenModal();
  43361. /** @internal */
  43362. bool keyPressed (const KeyPress& key);
  43363. /** @internal */
  43364. void handleCommandMessage (int commandId);
  43365. juce_UseDebuggingNewOperator
  43366. private:
  43367. int borderSpace;
  43368. float arrowSize;
  43369. Component& content;
  43370. Path outline;
  43371. Point<float> targetPoint;
  43372. Rectangle<int> availableArea, targetArea;
  43373. Image background;
  43374. void refreshPath();
  43375. void drawCallOutBoxBackground (Graphics& g, const Path& outline, int width, int height);
  43376. CallOutBox (const CallOutBox&);
  43377. CallOutBox& operator= (const CallOutBox&);
  43378. };
  43379. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  43380. /*** End of inlined file: juce_CallOutBox.h ***/
  43381. #endif
  43382. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  43383. /*** Start of inlined file: juce_ComponentPeer.h ***/
  43384. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  43385. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  43386. class ComponentBoundsConstrainer;
  43387. /**
  43388. The base class for window objects that wrap a component as a real operating
  43389. system object.
  43390. This is an abstract base class - the platform specific code contains default
  43391. implementations of it that create and manage windows.
  43392. @see Component::createNewPeer
  43393. */
  43394. class JUCE_API ComponentPeer
  43395. {
  43396. public:
  43397. /** A combination of these flags is passed to the ComponentPeer constructor. */
  43398. enum StyleFlags
  43399. {
  43400. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  43401. entry on the taskbar (ignored on MacOSX) */
  43402. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  43403. tooltip, etc. */
  43404. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  43405. through it (may not be possible on some platforms). */
  43406. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  43407. title bar and frame\. if not specified, the window will be
  43408. borderless. */
  43409. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  43410. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  43411. minimise button on it. */
  43412. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  43413. maximise button on it. */
  43414. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  43415. close button on it. */
  43416. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  43417. not be possible on all platforms). */
  43418. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  43419. do its own repainting, but only to repaint when the
  43420. performAnyPendingRepaintsNow() method is called. */
  43421. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  43422. be used for things like plugin windows, to stop them interfering
  43423. with the host's shortcut keys */
  43424. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  43425. };
  43426. /** Creates a peer.
  43427. The component is the one that we intend to represent, and the style flags are
  43428. a combination of the values in the StyleFlags enum
  43429. */
  43430. ComponentPeer (Component* component, int styleFlags);
  43431. /** Destructor. */
  43432. virtual ~ComponentPeer();
  43433. /** Returns the component being represented by this peer. */
  43434. Component* getComponent() const throw() { return component; }
  43435. /** Returns the set of style flags that were set when the window was created.
  43436. @see Component::addToDesktop
  43437. */
  43438. int getStyleFlags() const throw() { return styleFlags; }
  43439. /** Returns the raw handle to whatever kind of window is being used.
  43440. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  43441. but rememeber there's no guarantees what you'll get back.
  43442. */
  43443. virtual void* getNativeHandle() const = 0;
  43444. /** Shows or hides the window. */
  43445. virtual void setVisible (bool shouldBeVisible) = 0;
  43446. /** Changes the title of the window. */
  43447. virtual void setTitle (const String& title) = 0;
  43448. /** Moves the window without changing its size.
  43449. If the native window is contained in another window, then the co-ordinates are
  43450. relative to the parent window's origin, not the screen origin.
  43451. This should result in a callback to handleMovedOrResized().
  43452. */
  43453. virtual void setPosition (int x, int y) = 0;
  43454. /** Resizes the window without changing its position.
  43455. This should result in a callback to handleMovedOrResized().
  43456. */
  43457. virtual void setSize (int w, int h) = 0;
  43458. /** Moves and resizes the window.
  43459. If the native window is contained in another window, then the co-ordinates are
  43460. relative to the parent window's origin, not the screen origin.
  43461. This should result in a callback to handleMovedOrResized().
  43462. */
  43463. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  43464. /** Returns the current position and size of the window.
  43465. If the native window is contained in another window, then the co-ordinates are
  43466. relative to the parent window's origin, not the screen origin.
  43467. */
  43468. virtual const Rectangle<int> getBounds() const = 0;
  43469. /** Returns the x-position of this window, relative to the screen's origin. */
  43470. virtual const Point<int> getScreenPosition() const = 0;
  43471. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  43472. virtual const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) = 0;
  43473. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  43474. virtual const Point<int> globalPositionToRelative (const Point<int>& screenPosition) = 0;
  43475. /** Minimises the window. */
  43476. virtual void setMinimised (bool shouldBeMinimised) = 0;
  43477. /** True if the window is currently minimised. */
  43478. virtual bool isMinimised() const = 0;
  43479. /** Enable/disable fullscreen mode for the window. */
  43480. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  43481. /** True if the window is currently full-screen. */
  43482. virtual bool isFullScreen() const = 0;
  43483. /** Sets the size to restore to if fullscreen mode is turned off. */
  43484. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  43485. /** Returns the size to restore to if fullscreen mode is turned off. */
  43486. const Rectangle<int>& getNonFullScreenBounds() const throw();
  43487. /** Attempts to change the icon associated with this window.
  43488. */
  43489. virtual void setIcon (const Image& newIcon) = 0;
  43490. /** Sets a constrainer to use if the peer can resize itself.
  43491. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  43492. */
  43493. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  43494. /** Returns the current constrainer, if one has been set. */
  43495. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  43496. /** Checks if a point is in the window.
  43497. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  43498. is false, then this returns false if the point is actually inside a child of this
  43499. window.
  43500. */
  43501. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  43502. /** Returns the size of the window frame that's around this window.
  43503. Whether or not the window has a normal window frame depends on the flags
  43504. that were set when the window was created by Component::addToDesktop()
  43505. */
  43506. virtual const BorderSize getFrameSize() const = 0;
  43507. /** This is called when the window's bounds change.
  43508. A peer implementation must call this when the window is moved and resized, so that
  43509. this method can pass the message on to the component.
  43510. */
  43511. void handleMovedOrResized();
  43512. /** This is called if the screen resolution changes.
  43513. A peer implementation must call this if the monitor arrangement changes or the available
  43514. screen size changes.
  43515. */
  43516. void handleScreenSizeChange();
  43517. /** This is called to repaint the component into the given context. */
  43518. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  43519. /** Sets this window to either be always-on-top or normal.
  43520. Some kinds of window might not be able to do this, so should return false.
  43521. */
  43522. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  43523. /** Brings the window to the top, optionally also giving it focus. */
  43524. virtual void toFront (bool makeActive) = 0;
  43525. /** Moves the window to be just behind another one. */
  43526. virtual void toBehind (ComponentPeer* other) = 0;
  43527. /** Called when the window is brought to the front, either by the OS or by a call
  43528. to toFront().
  43529. */
  43530. void handleBroughtToFront();
  43531. /** True if the window has the keyboard focus. */
  43532. virtual bool isFocused() const = 0;
  43533. /** Tries to give the window keyboard focus. */
  43534. virtual void grabFocus() = 0;
  43535. /** Tells the window that text input may be required at the given position.
  43536. This may cause things like a virtual on-screen keyboard to appear, depending
  43537. on the OS.
  43538. */
  43539. virtual void textInputRequired (const Point<int>& position) = 0;
  43540. /** Called when the window gains keyboard focus. */
  43541. void handleFocusGain();
  43542. /** Called when the window loses keyboard focus. */
  43543. void handleFocusLoss();
  43544. Component* getLastFocusedSubcomponent() const throw();
  43545. /** Called when a key is pressed.
  43546. For keycode info, see the KeyPress class.
  43547. Returns true if the keystroke was used.
  43548. */
  43549. bool handleKeyPress (int keyCode,
  43550. juce_wchar textCharacter);
  43551. /** Called whenever a key is pressed or released.
  43552. Returns true if the keystroke was used.
  43553. */
  43554. bool handleKeyUpOrDown (bool isKeyDown);
  43555. /** Called whenever a modifier key is pressed or released. */
  43556. void handleModifierKeysChange();
  43557. /** Returns the currently focused TextInputTarget, or null if none is found. */
  43558. TextInputTarget* findCurrentTextInputTarget();
  43559. /** Invalidates a region of the window to be repainted asynchronously. */
  43560. virtual void repaint (const Rectangle<int>& area) = 0;
  43561. /** This can be called (from the message thread) to cause the immediate redrawing
  43562. of any areas of this window that need repainting.
  43563. You shouldn't ever really need to use this, it's mainly for special purposes
  43564. like supporting audio plugins where the host's event loop is out of our control.
  43565. */
  43566. virtual void performAnyPendingRepaintsNow() = 0;
  43567. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  43568. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  43569. void handleUserClosingWindow();
  43570. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  43571. void handleFileDragExit (const StringArray& files);
  43572. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  43573. /** Resets the masking region.
  43574. The subclass should call this every time it's about to call the handlePaint
  43575. method.
  43576. @see addMaskedRegion
  43577. */
  43578. void clearMaskedRegion();
  43579. /** Adds a rectangle to the set of areas not to paint over.
  43580. A component can call this on its peer during its paint() method, to signal
  43581. that the painting code should ignore a given region. The reason
  43582. for this is to stop embedded windows (such as OpenGL) getting painted over.
  43583. The masked region is cleared each time before a paint happens, so a component
  43584. will have to make sure it calls this every time it's painted.
  43585. */
  43586. void addMaskedRegion (int x, int y, int w, int h);
  43587. /** Returns the number of currently-active peers.
  43588. @see getPeer
  43589. */
  43590. static int getNumPeers() throw();
  43591. /** Returns one of the currently-active peers.
  43592. @see getNumPeers
  43593. */
  43594. static ComponentPeer* getPeer (int index) throw();
  43595. /** Checks if this peer object is valid.
  43596. @see getNumPeers
  43597. */
  43598. static bool isValidPeer (const ComponentPeer* peer) throw();
  43599. static void bringModalComponentToFront();
  43600. virtual const StringArray getAvailableRenderingEngines() throw();
  43601. virtual int getCurrentRenderingEngine() throw();
  43602. virtual void setCurrentRenderingEngine (int index) throw();
  43603. juce_UseDebuggingNewOperator
  43604. protected:
  43605. Component* const component;
  43606. const int styleFlags;
  43607. RectangleList maskedRegion;
  43608. Rectangle<int> lastNonFullscreenBounds;
  43609. uint32 lastPaintTime;
  43610. ComponentBoundsConstrainer* constrainer;
  43611. static void updateCurrentModifiers() throw();
  43612. private:
  43613. Component::SafePointer<Component> lastFocusedComponent, dragAndDropTargetComponent;
  43614. Component* lastDragAndDropCompUnderMouse;
  43615. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  43616. friend class Component;
  43617. static ComponentPeer* getPeerFor (const Component* component) throw();
  43618. void setLastDragDropTarget (Component* comp);
  43619. ComponentPeer (const ComponentPeer&);
  43620. ComponentPeer& operator= (const ComponentPeer&);
  43621. };
  43622. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  43623. /*** End of inlined file: juce_ComponentPeer.h ***/
  43624. #endif
  43625. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43626. /*** Start of inlined file: juce_DialogWindow.h ***/
  43627. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43628. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  43629. /**
  43630. A dialog-box style window.
  43631. This class is a convenient way of creating a DocumentWindow with a close button
  43632. that can be triggered by pressing the escape key.
  43633. Any of the methods available to a DocumentWindow or ResizableWindow are also
  43634. available to this, so it can be made resizable, have a menu bar, etc.
  43635. To add items to the box, see the ResizableWindow::setContentComponent() method.
  43636. Don't add components directly to this class - always put them in a content component!
  43637. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  43638. the user clicking the close button - for more info, see the DocumentWindow
  43639. help.
  43640. @see DocumentWindow, ResizableWindow
  43641. */
  43642. class JUCE_API DialogWindow : public DocumentWindow
  43643. {
  43644. public:
  43645. /** Creates a DialogWindow.
  43646. @param name the name to give the component - this is also
  43647. the title shown at the top of the window. To change
  43648. this later, use setName()
  43649. @param backgroundColour the colour to use for filling the window's background.
  43650. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43651. close button to be triggered
  43652. @param addToDesktop if true, the window will be automatically added to the
  43653. desktop; if false, you can use it as a child component
  43654. */
  43655. DialogWindow (const String& name,
  43656. const Colour& backgroundColour,
  43657. bool escapeKeyTriggersCloseButton,
  43658. bool addToDesktop = true);
  43659. /** Destructor.
  43660. If a content component has been set with setContentComponent(), it
  43661. will be deleted.
  43662. */
  43663. ~DialogWindow();
  43664. /** Easy way of quickly showing a dialog box containing a given component.
  43665. This will open and display a DialogWindow containing a given component, returning
  43666. when the user clicks its close button.
  43667. It returns the value that was returned by the dialog box's runModalLoop() call.
  43668. To close the dialog programatically, you should call exitModalState (returnValue) on
  43669. the DialogWindow that is created. To find a pointer to this window from your
  43670. contentComponent, you can do something like this:
  43671. @code
  43672. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  43673. if (dw != 0)
  43674. dw->exitModalState (1234);
  43675. @endcode
  43676. @param dialogTitle the dialog box's title
  43677. @param contentComponent the content component for the dialog box. Make sure
  43678. that this has been set to the size you want it to
  43679. be before calling this method. The component won't
  43680. be deleted by this call, so you can re-use it or delete
  43681. it afterwards
  43682. @param componentToCentreAround if this is non-zero, it indicates a component that
  43683. you'd like to show this dialog box in front of. See the
  43684. DocumentWindow::centreAroundComponent() method for more
  43685. info on this parameter
  43686. @param backgroundColour a colour to use for the dialog box's background colour
  43687. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43688. close button to be triggered
  43689. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  43690. a corner resizer
  43691. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  43692. to use a border or corner resizer component. See ResizableWindow::setResizable()
  43693. */
  43694. static int showModalDialog (const String& dialogTitle,
  43695. Component* contentComponent,
  43696. Component* componentToCentreAround,
  43697. const Colour& backgroundColour,
  43698. bool escapeKeyTriggersCloseButton,
  43699. bool shouldBeResizable = false,
  43700. bool useBottomRightCornerResizer = false);
  43701. juce_UseDebuggingNewOperator
  43702. protected:
  43703. /** @internal */
  43704. void resized();
  43705. private:
  43706. bool escapeKeyTriggersCloseButton;
  43707. DialogWindow (const DialogWindow&);
  43708. DialogWindow& operator= (const DialogWindow&);
  43709. };
  43710. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  43711. /*** End of inlined file: juce_DialogWindow.h ***/
  43712. #endif
  43713. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43714. #endif
  43715. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43716. #endif
  43717. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43718. /*** Start of inlined file: juce_SplashScreen.h ***/
  43719. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43720. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  43721. /** A component for showing a splash screen while your app starts up.
  43722. This will automatically position itself, and delete itself when the app has
  43723. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  43724. this).
  43725. To use it, just create one of these in your JUCEApplication::initialise() method,
  43726. call its show() method and let the object delete itself later.
  43727. E.g. @code
  43728. void MyApp::initialise (const String& commandLine)
  43729. {
  43730. SplashScreen* splash = new SplashScreen();
  43731. splash->show ("welcome to my app",
  43732. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  43733. 4000, false);
  43734. .. no need to delete the splash screen - it'll do that itself.
  43735. }
  43736. @endcode
  43737. */
  43738. class JUCE_API SplashScreen : public Component,
  43739. public Timer,
  43740. private DeletedAtShutdown
  43741. {
  43742. public:
  43743. /** Creates a SplashScreen object.
  43744. After creating one of these (or your subclass of it), call one of the show()
  43745. methods to display it.
  43746. */
  43747. SplashScreen();
  43748. /** Destructor. */
  43749. ~SplashScreen();
  43750. /** Creates a SplashScreen object that will display an image.
  43751. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43752. screen. This method will also dispatch any pending messages to make sure that when
  43753. it returns, the splash screen has been completely drawn, and your initialisation
  43754. code can carry on.
  43755. @param title the name to give the component
  43756. @param backgroundImage an image to draw on the component. The component's size
  43757. will be set to the size of this image, and if the image is
  43758. semi-transparent, the component will be made semi-transparent
  43759. too. This image will be deleted (or released from the ImageCache
  43760. if that's how it was created) by the splash screen object when
  43761. it is itself deleted.
  43762. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43763. should stay visible for. If the initialisation takes longer than
  43764. this time, the splash screen will wait for it to finish before
  43765. disappearing, but if initialisation is very quick, this lets
  43766. you make sure that people get a good look at your splash.
  43767. @param useDropShadow if true, the window will have a drop shadow
  43768. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43769. the mouse (anywhere)
  43770. */
  43771. void show (const String& title,
  43772. const Image& backgroundImage,
  43773. int minimumTimeToDisplayFor,
  43774. bool useDropShadow,
  43775. bool removeOnMouseClick = true);
  43776. /** Creates a SplashScreen object with a specified size.
  43777. For a custom splash screen, you can use this method to display it at a certain size
  43778. and then override the paint() method yourself to do whatever's necessary.
  43779. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43780. screen. This method will also dispatch any pending messages to make sure that when
  43781. it returns, the splash screen has been completely drawn, and your initialisation
  43782. code can carry on.
  43783. @param title the name to give the component
  43784. @param width the width to use
  43785. @param height the height to use
  43786. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43787. should stay visible for. If the initialisation takes longer than
  43788. this time, the splash screen will wait for it to finish before
  43789. disappearing, but if initialisation is very quick, this lets
  43790. you make sure that people get a good look at your splash.
  43791. @param useDropShadow if true, the window will have a drop shadow
  43792. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43793. the mouse (anywhere)
  43794. */
  43795. void show (const String& title,
  43796. int width,
  43797. int height,
  43798. int minimumTimeToDisplayFor,
  43799. bool useDropShadow,
  43800. bool removeOnMouseClick = true);
  43801. /** @internal */
  43802. void paint (Graphics& g);
  43803. /** @internal */
  43804. void timerCallback();
  43805. juce_UseDebuggingNewOperator
  43806. private:
  43807. Image backgroundImage;
  43808. Time earliestTimeToDelete;
  43809. int originalClickCounter;
  43810. SplashScreen (const SplashScreen&);
  43811. SplashScreen& operator= (const SplashScreen&);
  43812. };
  43813. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  43814. /*** End of inlined file: juce_SplashScreen.h ***/
  43815. #endif
  43816. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43817. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  43818. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43819. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43820. /**
  43821. A thread that automatically pops up a modal dialog box with a progress bar
  43822. and cancel button while it's busy running.
  43823. These are handy for performing some sort of task while giving the user feedback
  43824. about how long there is to go, etc.
  43825. E.g. @code
  43826. class MyTask : public ThreadWithProgressWindow
  43827. {
  43828. public:
  43829. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  43830. {
  43831. }
  43832. ~MyTask()
  43833. {
  43834. }
  43835. void run()
  43836. {
  43837. for (int i = 0; i < thingsToDo; ++i)
  43838. {
  43839. // must check this as often as possible, because this is
  43840. // how we know if the user's pressed 'cancel'
  43841. if (threadShouldExit())
  43842. break;
  43843. // this will update the progress bar on the dialog box
  43844. setProgress (i / (double) thingsToDo);
  43845. // ... do the business here...
  43846. }
  43847. }
  43848. };
  43849. void doTheTask()
  43850. {
  43851. MyTask m;
  43852. if (m.runThread())
  43853. {
  43854. // thread finished normally..
  43855. }
  43856. else
  43857. {
  43858. // user pressed the cancel button..
  43859. }
  43860. }
  43861. @endcode
  43862. @see Thread, AlertWindow
  43863. */
  43864. class JUCE_API ThreadWithProgressWindow : public Thread,
  43865. private Timer
  43866. {
  43867. public:
  43868. /** Creates the thread.
  43869. Initially, the dialog box won't be visible, it'll only appear when the
  43870. runThread() method is called.
  43871. @param windowTitle the title to go at the top of the dialog box
  43872. @param hasProgressBar whether the dialog box should have a progress bar (see
  43873. setProgress() )
  43874. @param hasCancelButton whether the dialog box should have a cancel button
  43875. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  43876. the thread to stop before killing it forcibly (see
  43877. Thread::stopThread() )
  43878. @param cancelButtonText the text that should be shown in the cancel button
  43879. (if it has one)
  43880. */
  43881. ThreadWithProgressWindow (const String& windowTitle,
  43882. bool hasProgressBar,
  43883. bool hasCancelButton,
  43884. int timeOutMsWhenCancelling = 10000,
  43885. const String& cancelButtonText = "Cancel");
  43886. /** Destructor. */
  43887. ~ThreadWithProgressWindow();
  43888. /** Starts the thread and waits for it to finish.
  43889. This will start the thread, make the dialog box appear, and wait until either
  43890. the thread finishes normally, or until the cancel button is pressed.
  43891. Before returning, the dialog box will be hidden.
  43892. @param threadPriority the priority to use when starting the thread - see
  43893. Thread::startThread() for values
  43894. @returns true if the thread finished normally; false if the user pressed cancel
  43895. */
  43896. bool runThread (int threadPriority = 5);
  43897. /** The thread should call this periodically to update the position of the progress bar.
  43898. @param newProgress the progress, from 0.0 to 1.0
  43899. @see setStatusMessage
  43900. */
  43901. void setProgress (double newProgress);
  43902. /** The thread can call this to change the message that's displayed in the dialog box.
  43903. */
  43904. void setStatusMessage (const String& newStatusMessage);
  43905. /** Returns the AlertWindow that is being used.
  43906. */
  43907. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  43908. juce_UseDebuggingNewOperator
  43909. private:
  43910. void timerCallback();
  43911. double progress;
  43912. ScopedPointer <AlertWindow> alertWindow;
  43913. String message;
  43914. CriticalSection messageLock;
  43915. const int timeOutMsWhenCancelling;
  43916. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  43917. ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  43918. };
  43919. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43920. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  43921. #endif
  43922. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  43923. #endif
  43924. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  43925. #endif
  43926. #ifndef __JUCE_COLOUR_JUCEHEADER__
  43927. #endif
  43928. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  43929. #endif
  43930. #ifndef __JUCE_COLOURS_JUCEHEADER__
  43931. #endif
  43932. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  43933. #endif
  43934. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43935. /*** Start of inlined file: juce_EdgeTable.h ***/
  43936. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43937. #define __JUCE_EDGETABLE_JUCEHEADER__
  43938. class Path;
  43939. class Image;
  43940. /**
  43941. A table of horizontal scan-line segments - used for rasterising Paths.
  43942. @see Path, Graphics
  43943. */
  43944. class JUCE_API EdgeTable
  43945. {
  43946. public:
  43947. /** Creates an edge table containing a path.
  43948. A table is created with a fixed vertical range, and only sections of the path
  43949. which lie within this range will be added to the table.
  43950. @param clipLimits only the region of the path that lies within this area will be added
  43951. @param pathToAdd the path to add to the table
  43952. @param transform a transform to apply to the path being added
  43953. */
  43954. EdgeTable (const Rectangle<int>& clipLimits,
  43955. const Path& pathToAdd,
  43956. const AffineTransform& transform);
  43957. /** Creates an edge table containing a rectangle.
  43958. */
  43959. EdgeTable (const Rectangle<int>& rectangleToAdd);
  43960. /** Creates an edge table containing a rectangle list.
  43961. */
  43962. EdgeTable (const RectangleList& rectanglesToAdd);
  43963. /** Creates an edge table containing a rectangle.
  43964. */
  43965. EdgeTable (const Rectangle<float>& rectangleToAdd);
  43966. /** Creates a copy of another edge table. */
  43967. EdgeTable (const EdgeTable& other);
  43968. /** Copies from another edge table. */
  43969. EdgeTable& operator= (const EdgeTable& other);
  43970. /** Destructor. */
  43971. ~EdgeTable();
  43972. void clipToRectangle (const Rectangle<int>& r) throw();
  43973. void excludeRectangle (const Rectangle<int>& r) throw();
  43974. void clipToEdgeTable (const EdgeTable& other);
  43975. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw();
  43976. bool isEmpty() throw();
  43977. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  43978. void translate (float dx, int dy) throw();
  43979. /** Reduces the amount of space the table has allocated.
  43980. This will shrink the table down to use as little memory as possible - useful for
  43981. read-only tables that get stored and re-used for rendering.
  43982. */
  43983. void optimiseTable() throw();
  43984. /** Iterates the lines in the table, for rendering.
  43985. This function will iterate each line in the table, and call a user-defined class
  43986. to render each pixel or continuous line of pixels that the table contains.
  43987. @param iterationCallback this templated class must contain the following methods:
  43988. @code
  43989. inline void setEdgeTableYPos (int y);
  43990. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  43991. inline void handleEdgeTablePixelFull (int x) const;
  43992. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  43993. inline void handleEdgeTableLineFull (int x, int width) const;
  43994. @endcode
  43995. (these don't necessarily have to be 'const', but it might help it go faster)
  43996. */
  43997. template <class EdgeTableIterationCallback>
  43998. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  43999. {
  44000. const int* lineStart = table;
  44001. for (int y = 0; y < bounds.getHeight(); ++y)
  44002. {
  44003. const int* line = lineStart;
  44004. lineStart += lineStrideElements;
  44005. int numPoints = line[0];
  44006. if (--numPoints > 0)
  44007. {
  44008. int x = *++line;
  44009. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  44010. int levelAccumulator = 0;
  44011. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  44012. while (--numPoints >= 0)
  44013. {
  44014. const int level = *++line;
  44015. jassert (((unsigned int) level) < (unsigned int) 256);
  44016. const int endX = *++line;
  44017. jassert (endX >= x);
  44018. const int endOfRun = (endX >> 8);
  44019. if (endOfRun == (x >> 8))
  44020. {
  44021. // small segment within the same pixel, so just save it for the next
  44022. // time round..
  44023. levelAccumulator += (endX - x) * level;
  44024. }
  44025. else
  44026. {
  44027. // plot the fist pixel of this segment, including any accumulated
  44028. // levels from smaller segments that haven't been drawn yet
  44029. levelAccumulator += (0xff - (x & 0xff)) * level;
  44030. levelAccumulator >>= 8;
  44031. x >>= 8;
  44032. if (levelAccumulator > 0)
  44033. {
  44034. if (levelAccumulator >> 8)
  44035. iterationCallback.handleEdgeTablePixelFull (x);
  44036. else
  44037. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  44038. }
  44039. // if there's a run of similar pixels, do it all in one go..
  44040. if (level > 0)
  44041. {
  44042. jassert (endOfRun <= bounds.getRight());
  44043. const int numPix = endOfRun - ++x;
  44044. if (numPix > 0)
  44045. iterationCallback.handleEdgeTableLine (x, numPix, level);
  44046. }
  44047. // save the bit at the end to be drawn next time round the loop.
  44048. levelAccumulator = (endX & 0xff) * level;
  44049. }
  44050. x = endX;
  44051. }
  44052. levelAccumulator >>= 8;
  44053. if (levelAccumulator > 0)
  44054. {
  44055. x >>= 8;
  44056. jassert (x >= bounds.getX() && x < bounds.getRight());
  44057. if (levelAccumulator >> 8)
  44058. iterationCallback.handleEdgeTablePixelFull (x);
  44059. else
  44060. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  44061. }
  44062. }
  44063. }
  44064. }
  44065. juce_UseDebuggingNewOperator
  44066. private:
  44067. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  44068. HeapBlock<int> table;
  44069. Rectangle<int> bounds;
  44070. int maxEdgesPerLine, lineStrideElements;
  44071. bool needToCheckEmptinesss;
  44072. void addEdgePoint (int x, int y, int winding) throw();
  44073. void remapTableForNumEdges (int newNumEdgesPerLine) throw();
  44074. void intersectWithEdgeTableLine (int y, const int* otherLine) throw();
  44075. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  44076. void sanitiseLevels (bool useNonZeroWinding) throw();
  44077. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  44078. };
  44079. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  44080. /*** End of inlined file: juce_EdgeTable.h ***/
  44081. #endif
  44082. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  44083. /*** Start of inlined file: juce_FillType.h ***/
  44084. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  44085. #define __JUCE_FILLTYPE_JUCEHEADER__
  44086. /**
  44087. Represents a colour or fill pattern to use for rendering paths.
  44088. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  44089. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  44090. @see Graphics::setFillType, DrawablePath::setFill
  44091. */
  44092. class JUCE_API FillType
  44093. {
  44094. public:
  44095. /** Creates a default fill type, of solid black. */
  44096. FillType() throw();
  44097. /** Creates a fill type of a solid colour.
  44098. @see setColour
  44099. */
  44100. FillType (const Colour& colour) throw();
  44101. /** Creates a gradient fill type.
  44102. @see setGradient
  44103. */
  44104. FillType (const ColourGradient& gradient);
  44105. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  44106. and rotation of the pattern.
  44107. @see setTiledImage
  44108. */
  44109. FillType (const Image& image, const AffineTransform& transform) throw();
  44110. /** Creates a copy of another FillType. */
  44111. FillType (const FillType& other);
  44112. /** Makes a copy of another FillType. */
  44113. FillType& operator= (const FillType& other);
  44114. /** Destructor. */
  44115. ~FillType() throw();
  44116. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  44117. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  44118. /** Returns true if this is a gradient fill. */
  44119. bool isGradient() const throw() { return gradient != 0; }
  44120. /** Returns true if this is a tiled image pattern fill. */
  44121. bool isTiledImage() const throw() { return image.isValid(); }
  44122. /** Turns this object into a solid colour fill.
  44123. If the object was an image or gradient, those fields will no longer be valid. */
  44124. void setColour (const Colour& newColour) throw();
  44125. /** Turns this object into a gradient fill. */
  44126. void setGradient (const ColourGradient& newGradient);
  44127. /** Turns this object into a tiled image fill type. The transform allows you to set
  44128. the scaling, offset and rotation of the pattern.
  44129. */
  44130. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  44131. /** Changes the opacity that should be used.
  44132. If the fill is a solid colour, this just changes the opacity of that colour. For
  44133. gradients and image tiles, it changes the opacity that will be used for them.
  44134. */
  44135. void setOpacity (float newOpacity) throw();
  44136. /** Returns the current opacity to be applied to the colour, gradient, or image.
  44137. @see setOpacity
  44138. */
  44139. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  44140. /** Returns true if this fill type is completely transparent. */
  44141. bool isInvisible() const throw();
  44142. bool operator== (const FillType& other) const;
  44143. bool operator!= (const FillType& other) const;
  44144. /** The solid colour being used.
  44145. If the fill type is not a solid colour, the alpha channel of this colour indicates
  44146. the opacity that should be used for the fill, and the RGB channels are ignored.
  44147. */
  44148. Colour colour;
  44149. /** Returns the gradient that should be used for filling.
  44150. This will be zero if the object is some other type of fill.
  44151. If a gradient is active, the overall opacity with which it should be applied
  44152. is indicated by the alpha channel of the colour variable.
  44153. */
  44154. ScopedPointer <ColourGradient> gradient;
  44155. /** The image that should be used for tiling.
  44156. If an image fill is active, the overall opacity with which it should be applied
  44157. is indicated by the alpha channel of the colour variable.
  44158. */
  44159. Image image;
  44160. /** The transform that should be applied to the image or gradient that's being drawn.
  44161. */
  44162. AffineTransform transform;
  44163. juce_UseDebuggingNewOperator
  44164. };
  44165. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  44166. /*** End of inlined file: juce_FillType.h ***/
  44167. #endif
  44168. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  44169. #endif
  44170. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  44171. #endif
  44172. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44173. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  44174. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44175. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44176. /**
  44177. Interface class for graphics context objects, used internally by the Graphics class.
  44178. Users are not supposed to create instances of this class directly - do your drawing
  44179. via the Graphics object instead.
  44180. It's a base class for different types of graphics context, that may perform software-based
  44181. or OS-accelerated rendering.
  44182. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  44183. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  44184. context.
  44185. */
  44186. class JUCE_API LowLevelGraphicsContext
  44187. {
  44188. protected:
  44189. LowLevelGraphicsContext();
  44190. public:
  44191. virtual ~LowLevelGraphicsContext();
  44192. /** Returns true if this device is vector-based, e.g. a printer. */
  44193. virtual bool isVectorDevice() const = 0;
  44194. /** Moves the origin to a new position.
  44195. The co-ords are relative to the current origin, and indicate the new position
  44196. of (0, 0).
  44197. */
  44198. virtual void setOrigin (int x, int y) = 0;
  44199. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  44200. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  44201. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  44202. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  44203. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform) = 0;
  44204. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  44205. virtual const Rectangle<int> getClipBounds() const = 0;
  44206. virtual bool isClipEmpty() const = 0;
  44207. virtual void saveState() = 0;
  44208. virtual void restoreState() = 0;
  44209. virtual void setFill (const FillType& fillType) = 0;
  44210. virtual void setOpacity (float newOpacity) = 0;
  44211. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  44212. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  44213. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  44214. virtual void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  44215. const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  44216. virtual void drawLine (const Line <float>& line) = 0;
  44217. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  44218. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  44219. virtual void setFont (const Font& newFont) = 0;
  44220. virtual const Font getFont() = 0;
  44221. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  44222. };
  44223. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44224. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  44225. #endif
  44226. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44227. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  44228. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44229. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44230. /**
  44231. An implementation of LowLevelGraphicsContext that turns the drawing operations
  44232. into a PostScript document.
  44233. */
  44234. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  44235. {
  44236. public:
  44237. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  44238. const String& documentTitle,
  44239. int totalWidth,
  44240. int totalHeight);
  44241. ~LowLevelGraphicsPostScriptRenderer();
  44242. bool isVectorDevice() const;
  44243. void setOrigin (int x, int y);
  44244. bool clipToRectangle (const Rectangle<int>& r);
  44245. bool clipToRectangleList (const RectangleList& clipRegion);
  44246. void excludeClipRectangle (const Rectangle<int>& r);
  44247. void clipToPath (const Path& path, const AffineTransform& transform);
  44248. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  44249. void saveState();
  44250. void restoreState();
  44251. bool clipRegionIntersects (const Rectangle<int>& r);
  44252. const Rectangle<int> getClipBounds() const;
  44253. bool isClipEmpty() const;
  44254. void setFill (const FillType& fillType);
  44255. void setOpacity (float opacity);
  44256. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  44257. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  44258. void fillPath (const Path& path, const AffineTransform& transform);
  44259. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  44260. const AffineTransform& transform, bool fillEntireClipAsTiles);
  44261. void drawLine (const Line <float>& line);
  44262. void drawVerticalLine (int x, float top, float bottom);
  44263. void drawHorizontalLine (int x, float top, float bottom);
  44264. const Font getFont();
  44265. void setFont (const Font& newFont);
  44266. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  44267. juce_UseDebuggingNewOperator
  44268. protected:
  44269. OutputStream& out;
  44270. int totalWidth, totalHeight;
  44271. bool needToClip;
  44272. Colour lastColour;
  44273. struct SavedState
  44274. {
  44275. SavedState();
  44276. ~SavedState();
  44277. RectangleList clip;
  44278. int xOffset, yOffset;
  44279. FillType fillType;
  44280. Font font;
  44281. private:
  44282. SavedState& operator= (const SavedState&);
  44283. };
  44284. OwnedArray <SavedState> stateStack;
  44285. void writeClip();
  44286. void writeColour (const Colour& colour);
  44287. void writePath (const Path& path) const;
  44288. void writeXY (float x, float y) const;
  44289. void writeTransform (const AffineTransform& trans) const;
  44290. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  44291. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  44292. LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  44293. };
  44294. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44295. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  44296. #endif
  44297. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44298. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  44299. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44300. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44301. /**
  44302. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  44303. its rendering in memory.
  44304. User code is not supposed to create instances of this class directly - do all your
  44305. rendering via the Graphics class instead.
  44306. */
  44307. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  44308. {
  44309. public:
  44310. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  44311. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  44312. ~LowLevelGraphicsSoftwareRenderer();
  44313. bool isVectorDevice() const;
  44314. void setOrigin (int x, int y);
  44315. bool clipToRectangle (const Rectangle<int>& r);
  44316. bool clipToRectangleList (const RectangleList& clipRegion);
  44317. void excludeClipRectangle (const Rectangle<int>& r);
  44318. void clipToPath (const Path& path, const AffineTransform& transform);
  44319. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  44320. bool clipRegionIntersects (const Rectangle<int>& r);
  44321. const Rectangle<int> getClipBounds() const;
  44322. bool isClipEmpty() const;
  44323. void saveState();
  44324. void restoreState();
  44325. void setFill (const FillType& fillType);
  44326. void setOpacity (float opacity);
  44327. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  44328. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  44329. void fillPath (const Path& path, const AffineTransform& transform);
  44330. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  44331. const AffineTransform& transform, bool fillEntireClipAsTiles);
  44332. void drawLine (const Line <float>& line);
  44333. void drawVerticalLine (int x, float top, float bottom);
  44334. void drawHorizontalLine (int x, float top, float bottom);
  44335. void setFont (const Font& newFont);
  44336. const Font getFont();
  44337. void drawGlyph (int glyphNumber, float x, float y);
  44338. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  44339. juce_UseDebuggingNewOperator
  44340. protected:
  44341. Image image;
  44342. class GlyphCache;
  44343. class CachedGlyph;
  44344. class SavedState;
  44345. friend class ScopedPointer <SavedState>;
  44346. friend class OwnedArray <SavedState>;
  44347. friend class OwnedArray <CachedGlyph>;
  44348. ScopedPointer <SavedState> currentState;
  44349. OwnedArray <SavedState> stateStack;
  44350. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  44351. LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  44352. };
  44353. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44354. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  44355. #endif
  44356. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  44357. #endif
  44358. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  44359. #endif
  44360. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44361. /*** Start of inlined file: juce_DrawableComposite.h ***/
  44362. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44363. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44364. /**
  44365. A drawable object which acts as a container for a set of other Drawables.
  44366. @see Drawable
  44367. */
  44368. class JUCE_API DrawableComposite : public Drawable,
  44369. public RelativeCoordinate::NamedCoordinateFinder
  44370. {
  44371. public:
  44372. /** Creates a composite Drawable. */
  44373. DrawableComposite();
  44374. /** Creates a copy of a DrawableComposite. */
  44375. DrawableComposite (const DrawableComposite& other);
  44376. /** Destructor. */
  44377. ~DrawableComposite();
  44378. /** Adds a new sub-drawable to this one.
  44379. This passes in a Drawable pointer for this object to look after. To add a copy
  44380. of a drawable, use the form of this method that takes a Drawable reference instead.
  44381. @param drawable the object to add - this will be deleted automatically
  44382. when no longer needed, so the caller mustn't keep any
  44383. pointers to it.
  44384. @param index where to insert it in the list of drawables. 0 is the back,
  44385. -1 is the front, or any value from 0 and getNumDrawables()
  44386. can be used
  44387. @see removeDrawable
  44388. */
  44389. void insertDrawable (Drawable* drawable, int index = -1);
  44390. /** Adds a new sub-drawable to this one.
  44391. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  44392. for this object to look after, use the form of this method that takes a Drawable
  44393. pointer instead.
  44394. @param drawable the object to add - an internal copy will be made of this object
  44395. @param index where to insert it in the list of drawables. 0 is the back,
  44396. -1 is the front, or any value from 0 and getNumDrawables()
  44397. can be used
  44398. @see removeDrawable
  44399. */
  44400. void insertDrawable (const Drawable& drawable, int index = -1);
  44401. /** Deletes one of the Drawable objects.
  44402. @param index the index of the drawable to delete, between 0
  44403. and (getNumDrawables() - 1).
  44404. @param deleteDrawable if this is true, the drawable that is removed will also
  44405. be deleted. If false, it'll just be removed.
  44406. @see insertDrawable, getNumDrawables
  44407. */
  44408. void removeDrawable (int index, bool deleteDrawable = true);
  44409. /** Returns the number of drawables contained inside this one.
  44410. @see getDrawable
  44411. */
  44412. int getNumDrawables() const throw() { return drawables.size(); }
  44413. /** Returns one of the drawables that are contained in this one.
  44414. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  44415. to find it.
  44416. The pointer returned is managed by this object and will be deleted when no longer
  44417. needed, so be careful what you do with it.
  44418. @see getNumDrawables
  44419. */
  44420. Drawable* getDrawable (int index) const throw() { return drawables [index]; }
  44421. /** Looks for a child drawable with the specified name. */
  44422. Drawable* getDrawableWithName (const String& name) const throw();
  44423. /** Brings one of the Drawables to the front.
  44424. @param index the index of the drawable to move, between 0
  44425. and (getNumDrawables() - 1).
  44426. @see insertDrawable, getNumDrawables
  44427. */
  44428. void bringToFront (int index);
  44429. /** Changes the main content area.
  44430. The content area is actually defined by the markers named "left", "right", "top" and
  44431. "bottom", but this method is a shortcut that sets them all at once.
  44432. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44433. */
  44434. const RelativeRectangle getContentArea() const;
  44435. /** Returns the main content rectangle.
  44436. The content area is actually defined by the markers named "left", "right", "top" and
  44437. "bottom", but this method is a shortcut that returns them all at once.
  44438. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44439. */
  44440. void setContentArea (const RelativeRectangle& newArea);
  44441. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44442. @see setContentArea
  44443. */
  44444. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  44445. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44446. @see setBoundingBox
  44447. */
  44448. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44449. /** Changes the bounding box transform to match the content area, so that any sub-items will
  44450. be drawn at their untransformed positions.
  44451. */
  44452. void resetBoundingBoxToContentArea();
  44453. /** Resets the content area and the bounding transform to fit around the area occupied
  44454. by the child components (ignoring any markers).
  44455. */
  44456. void resetContentAreaAndBoundingBoxToFitChildren();
  44457. /** Represents a named marker position.
  44458. @see DrawableComposite::getMarker
  44459. */
  44460. struct Marker
  44461. {
  44462. Marker (const Marker&);
  44463. Marker (const String& name, const RelativeCoordinate& position);
  44464. bool operator!= (const Marker&) const throw();
  44465. String name;
  44466. RelativeCoordinate position;
  44467. };
  44468. int getNumMarkers (bool xAxis) const throw();
  44469. const Marker* getMarker (bool xAxis, int index) const throw();
  44470. void setMarker (const String& name, bool xAxis, const RelativeCoordinate& position);
  44471. void removeMarker (bool xAxis, int index);
  44472. /** The name of the marker that defines the left edge of the content area. */
  44473. static const char* const contentLeftMarkerName;
  44474. /** The name of the marker that defines the right edge of the content area. */
  44475. static const char* const contentRightMarkerName;
  44476. /** The name of the marker that defines the top edge of the content area. */
  44477. static const char* const contentTopMarkerName;
  44478. /** The name of the marker that defines the bottom edge of the content area. */
  44479. static const char* const contentBottomMarkerName;
  44480. /** @internal */
  44481. void render (const Drawable::RenderingContext& context) const;
  44482. /** @internal */
  44483. const Rectangle<float> getBounds() const;
  44484. /** @internal */
  44485. bool hitTest (float x, float y) const;
  44486. /** @internal */
  44487. Drawable* createCopy() const;
  44488. /** @internal */
  44489. void invalidatePoints();
  44490. /** @internal */
  44491. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44492. /** @internal */
  44493. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44494. /** @internal */
  44495. static const Identifier valueTreeType;
  44496. /** @internal */
  44497. const Identifier getValueTreeType() const { return valueTreeType; }
  44498. /** @internal */
  44499. const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const;
  44500. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  44501. class ValueTreeWrapper : public ValueTreeWrapperBase
  44502. {
  44503. public:
  44504. ValueTreeWrapper (const ValueTree& state);
  44505. int getNumDrawables() const;
  44506. ValueTree getDrawableState (int index) const;
  44507. ValueTree getDrawableWithId (const String& objectId, bool recursive) const;
  44508. int indexOfDrawable (const ValueTree& item) const;
  44509. void addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager);
  44510. void moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager);
  44511. void removeDrawable (const ValueTree& child, UndoManager* undoManager);
  44512. const RelativeParallelogram getBoundingBox() const;
  44513. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44514. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  44515. const RelativeRectangle getContentArea() const;
  44516. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  44517. int getNumMarkers (bool xAxis) const;
  44518. const ValueTree getMarkerState (bool xAxis, int index) const;
  44519. const ValueTree getMarkerState (bool xAxis, const String& name) const;
  44520. bool containsMarker (bool xAxis, const ValueTree& state) const;
  44521. const Marker getMarker (bool xAxis, const ValueTree& state) const;
  44522. void setMarker (bool xAxis, const Marker& marker, UndoManager* undoManager);
  44523. void removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager);
  44524. static const Identifier nameProperty, posProperty;
  44525. private:
  44526. static const Identifier topLeft, topRight, bottomLeft, childGroupTag, markerGroupTagX,
  44527. markerGroupTagY, markerTag;
  44528. ValueTree getChildList() const;
  44529. ValueTree getChildListCreating (UndoManager* undoManager);
  44530. ValueTree getMarkerList (bool xAxis) const;
  44531. ValueTree getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  44532. };
  44533. juce_UseDebuggingNewOperator
  44534. private:
  44535. OwnedArray <Drawable> drawables;
  44536. RelativeParallelogram bounds;
  44537. OwnedArray <Marker> markersX, markersY;
  44538. const Rectangle<float> getUntransformedBounds (bool includeMarkers) const;
  44539. const AffineTransform calculateTransform() const;
  44540. DrawableComposite& operator= (const DrawableComposite&);
  44541. };
  44542. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44543. /*** End of inlined file: juce_DrawableComposite.h ***/
  44544. #endif
  44545. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44546. /*** Start of inlined file: juce_DrawableImage.h ***/
  44547. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44548. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44549. /**
  44550. A drawable object which is a bitmap image.
  44551. @see Drawable
  44552. */
  44553. class JUCE_API DrawableImage : public Drawable
  44554. {
  44555. public:
  44556. DrawableImage();
  44557. DrawableImage (const DrawableImage& other);
  44558. /** Destructor. */
  44559. ~DrawableImage();
  44560. /** Sets the image that this drawable will render. */
  44561. void setImage (const Image& imageToUse);
  44562. /** Returns the current image. */
  44563. const Image getImage() const { return image; }
  44564. /** Sets the opacity to use when drawing the image. */
  44565. void setOpacity (float newOpacity);
  44566. /** Returns the image's opacity. */
  44567. float getOpacity() const throw() { return opacity; }
  44568. /** Sets a colour to draw over the image's alpha channel.
  44569. By default this is transparent so isn't drawn, but if you set a non-transparent
  44570. colour here, then it will be overlaid on the image, using the image's alpha
  44571. channel as a mask.
  44572. This is handy for doing things like darkening or lightening an image by overlaying
  44573. it with semi-transparent black or white.
  44574. */
  44575. void setOverlayColour (const Colour& newOverlayColour);
  44576. /** Returns the overlay colour. */
  44577. const Colour& getOverlayColour() const throw() { return overlayColour; }
  44578. /** Sets the bounding box within which the image should be displayed. */
  44579. void setBoundingBox (const RelativeParallelogram& newBounds);
  44580. /** Returns the position to which the image's top-left corner should be remapped in the target
  44581. coordinate space when rendering this object.
  44582. @see setTransform
  44583. */
  44584. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44585. /** @internal */
  44586. void render (const Drawable::RenderingContext& context) const;
  44587. /** @internal */
  44588. const Rectangle<float> getBounds() const;
  44589. /** @internal */
  44590. bool hitTest (float x, float y) const;
  44591. /** @internal */
  44592. Drawable* createCopy() const;
  44593. /** @internal */
  44594. void invalidatePoints();
  44595. /** @internal */
  44596. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44597. /** @internal */
  44598. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44599. /** @internal */
  44600. static const Identifier valueTreeType;
  44601. /** @internal */
  44602. const Identifier getValueTreeType() const { return valueTreeType; }
  44603. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  44604. class ValueTreeWrapper : public ValueTreeWrapperBase
  44605. {
  44606. public:
  44607. ValueTreeWrapper (const ValueTree& state);
  44608. const var getImageIdentifier() const;
  44609. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  44610. Value getImageIdentifierValue (UndoManager* undoManager);
  44611. float getOpacity() const;
  44612. void setOpacity (float newOpacity, UndoManager* undoManager);
  44613. Value getOpacityValue (UndoManager* undoManager);
  44614. const Colour getOverlayColour() const;
  44615. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  44616. Value getOverlayColourValue (UndoManager* undoManager);
  44617. const RelativeParallelogram getBoundingBox() const;
  44618. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44619. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  44620. };
  44621. juce_UseDebuggingNewOperator
  44622. private:
  44623. Image image;
  44624. float opacity;
  44625. Colour overlayColour;
  44626. RelativeParallelogram bounds;
  44627. const AffineTransform calculateTransform() const;
  44628. DrawableImage& operator= (const DrawableImage&);
  44629. };
  44630. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44631. /*** End of inlined file: juce_DrawableImage.h ***/
  44632. #endif
  44633. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44634. /*** Start of inlined file: juce_DrawablePath.h ***/
  44635. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44636. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  44637. /**
  44638. A drawable object which renders a filled or outlined shape.
  44639. @see Drawable
  44640. */
  44641. class JUCE_API DrawablePath : public Drawable
  44642. {
  44643. public:
  44644. /** Creates a DrawablePath. */
  44645. DrawablePath();
  44646. DrawablePath (const DrawablePath& other);
  44647. /** Destructor. */
  44648. ~DrawablePath();
  44649. /** Changes the path that will be drawn.
  44650. @see setFillColour, setStrokeType
  44651. */
  44652. void setPath (const Path& newPath);
  44653. /** Sets a fill type for the path.
  44654. This colour is used to fill the path - if you don't want the path to be
  44655. filled (e.g. if you're just drawing an outline), set this to a transparent
  44656. colour.
  44657. @see setPath, setStrokeFill
  44658. */
  44659. void setFill (const FillType& newFill);
  44660. /** Returns the current fill type.
  44661. @see setFill
  44662. */
  44663. const FillType& getFill() const throw() { return mainFill; }
  44664. /** Sets the fill type with which the outline will be drawn.
  44665. @see setFill
  44666. */
  44667. void setStrokeFill (const FillType& newStrokeFill);
  44668. /** Returns the current stroke fill.
  44669. @see setStrokeFill
  44670. */
  44671. const FillType& getStrokeFill() const throw() { return strokeFill; }
  44672. /** Changes the properties of the outline that will be drawn around the path.
  44673. If the stroke has 0 thickness, no stroke will be drawn.
  44674. @see setStrokeThickness, setStrokeColour
  44675. */
  44676. void setStrokeType (const PathStrokeType& newStrokeType);
  44677. /** Changes the stroke thickness.
  44678. This is a shortcut for calling setStrokeType.
  44679. */
  44680. void setStrokeThickness (float newThickness);
  44681. /** Returns the current outline style. */
  44682. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  44683. /** Returns the current path. */
  44684. const Path& getPath() const;
  44685. /** Returns the current path for the outline. */
  44686. const Path& getStrokePath() const;
  44687. /** @internal */
  44688. void render (const Drawable::RenderingContext& context) const;
  44689. /** @internal */
  44690. const Rectangle<float> getBounds() const;
  44691. /** @internal */
  44692. bool hitTest (float x, float y) const;
  44693. /** @internal */
  44694. Drawable* createCopy() const;
  44695. /** @internal */
  44696. void invalidatePoints();
  44697. /** @internal */
  44698. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44699. /** @internal */
  44700. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44701. /** @internal */
  44702. static const Identifier valueTreeType;
  44703. /** @internal */
  44704. const Identifier getValueTreeType() const { return valueTreeType; }
  44705. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  44706. class ValueTreeWrapper : public ValueTreeWrapperBase
  44707. {
  44708. public:
  44709. ValueTreeWrapper (const ValueTree& state);
  44710. const FillType getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44711. ImageProvider* imageProvider) const;
  44712. ValueTree getMainFillState();
  44713. void setMainFill (const FillType& newFill, const RelativePoint* gradientPoint1,
  44714. const RelativePoint* gradientPoint2, const RelativePoint* gradientPoint3,
  44715. ImageProvider* imageProvider, UndoManager* undoManager);
  44716. const FillType getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44717. ImageProvider* imageProvider) const;
  44718. ValueTree getStrokeFillState();
  44719. void setStrokeFill (const FillType& newFill, const RelativePoint* gradientPoint1,
  44720. const RelativePoint* gradientPoint2, const RelativePoint* gradientPoint3,
  44721. ImageProvider* imageProvider, UndoManager* undoManager);
  44722. const PathStrokeType getStrokeType() const;
  44723. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager);
  44724. bool usesNonZeroWinding() const;
  44725. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  44726. class Element
  44727. {
  44728. public:
  44729. explicit Element (const ValueTree& state);
  44730. ~Element();
  44731. const Identifier getType() const throw() { return state.getType(); }
  44732. int getNumControlPoints() const throw();
  44733. const RelativePoint getControlPoint (int index) const;
  44734. Value getControlPointValue (int index, UndoManager* undoManager) const;
  44735. const RelativePoint getStartPoint() const;
  44736. const RelativePoint getEndPoint() const;
  44737. void setControlPoint (int index, const RelativePoint& point, UndoManager* undoManager);
  44738. float getLength (RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  44739. ValueTreeWrapper getParent() const;
  44740. Element getPreviousElement() const;
  44741. const String getModeOfEndPoint() const;
  44742. void setModeOfEndPoint (const String& newMode, UndoManager* undoManager);
  44743. void convertToLine (UndoManager* undoManager);
  44744. void convertToCubic (RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager);
  44745. void convertToPathBreak (UndoManager* undoManager);
  44746. ValueTree insertPoint (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager);
  44747. void removePoint (UndoManager* undoManager);
  44748. float findProportionAlongLine (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  44749. static const Identifier mode, startSubPathElement, closeSubPathElement,
  44750. lineToElement, quadraticToElement, cubicToElement;
  44751. static const char* cornerMode;
  44752. static const char* roundedMode;
  44753. static const char* symmetricMode;
  44754. ValueTree state;
  44755. };
  44756. ValueTree getPathState();
  44757. static const Identifier fill, stroke, path, jointStyle, capStyle, strokeWidth,
  44758. nonZeroWinding, point1, point2, point3;
  44759. };
  44760. juce_UseDebuggingNewOperator
  44761. private:
  44762. FillType mainFill, strokeFill;
  44763. PathStrokeType strokeType;
  44764. ScopedPointer<RelativePointPath> relativePath;
  44765. mutable Path path, stroke;
  44766. mutable bool pathNeedsUpdating, strokeNeedsUpdating;
  44767. void updatePath() const;
  44768. void updateStroke() const;
  44769. bool isStrokeVisible() const throw();
  44770. DrawablePath& operator= (const DrawablePath&);
  44771. };
  44772. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  44773. /*** End of inlined file: juce_DrawablePath.h ***/
  44774. #endif
  44775. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44776. /*** Start of inlined file: juce_DrawableText.h ***/
  44777. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44778. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  44779. /**
  44780. A drawable object which renders a line of text.
  44781. @see Drawable
  44782. */
  44783. class JUCE_API DrawableText : public Drawable
  44784. {
  44785. public:
  44786. /** Creates a DrawableText object. */
  44787. DrawableText();
  44788. DrawableText (const DrawableText& other);
  44789. /** Destructor. */
  44790. ~DrawableText();
  44791. /** Sets the text to display.*/
  44792. void setText (const String& newText);
  44793. /** Sets the colour of the text. */
  44794. void setColour (const Colour& newColour);
  44795. /** Returns the current text colour. */
  44796. const Colour& getColour() const throw() { return colour; }
  44797. /** Sets the font to use.
  44798. Note that the font height and horizontal scale are actually based upon the position
  44799. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  44800. the height and scale control point will be moved to match the dimensions of the font supplied;
  44801. if it is false, then the new font's height and scale are ignored.
  44802. */
  44803. void setFont (const Font& newFont, bool applySizeAndScale);
  44804. /** Changes the justification of the text within the bounding box. */
  44805. void setJustification (const Justification& newJustification);
  44806. /** Returns the parallelogram that defines the text bounding box. */
  44807. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44808. /** Sets the bounding box that contains the text. */
  44809. void setBoundingBox (const RelativeParallelogram& newBounds);
  44810. /** Returns the point within the bounds that defines the font's size and scale. */
  44811. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  44812. /** Sets the control point that defines the font's height and horizontal scale.
  44813. This position is a point within the bounding box parallelogram, whose Y position (relative
  44814. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  44815. and its X defines the font's horizontal scale.
  44816. */
  44817. void setFontSizeControlPoint (const RelativePoint& newPoint);
  44818. /** @internal */
  44819. void render (const Drawable::RenderingContext& context) const;
  44820. /** @internal */
  44821. const Rectangle<float> getBounds() const;
  44822. /** @internal */
  44823. bool hitTest (float x, float y) const;
  44824. /** @internal */
  44825. Drawable* createCopy() const;
  44826. /** @internal */
  44827. void invalidatePoints();
  44828. /** @internal */
  44829. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44830. /** @internal */
  44831. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44832. /** @internal */
  44833. static const Identifier valueTreeType;
  44834. /** @internal */
  44835. const Identifier getValueTreeType() const { return valueTreeType; }
  44836. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  44837. class ValueTreeWrapper : public ValueTreeWrapperBase
  44838. {
  44839. public:
  44840. ValueTreeWrapper (const ValueTree& state);
  44841. const String getText() const;
  44842. void setText (const String& newText, UndoManager* undoManager);
  44843. Value getTextValue (UndoManager* undoManager);
  44844. const Colour getColour() const;
  44845. void setColour (const Colour& newColour, UndoManager* undoManager);
  44846. const Justification getJustification() const;
  44847. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  44848. const Font getFont() const;
  44849. void setFont (const Font& newFont, UndoManager* undoManager);
  44850. Value getFontValue (UndoManager* undoManager);
  44851. const RelativeParallelogram getBoundingBox() const;
  44852. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44853. const RelativePoint getFontSizeControlPoint() const;
  44854. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  44855. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  44856. };
  44857. juce_UseDebuggingNewOperator
  44858. private:
  44859. RelativeParallelogram bounds;
  44860. RelativePoint fontSizeControlPoint;
  44861. Font font;
  44862. String text;
  44863. Colour colour;
  44864. Justification justification;
  44865. DrawableText& operator= (const DrawableText&);
  44866. };
  44867. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  44868. /*** End of inlined file: juce_DrawableText.h ***/
  44869. #endif
  44870. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  44871. #endif
  44872. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44873. /*** Start of inlined file: juce_GlowEffect.h ***/
  44874. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44875. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  44876. /**
  44877. A component effect that adds a coloured blur around the component's contents.
  44878. (This will only work on non-opaque components).
  44879. @see Component::setComponentEffect, DropShadowEffect
  44880. */
  44881. class JUCE_API GlowEffect : public ImageEffectFilter
  44882. {
  44883. public:
  44884. /** Creates a default 'glow' effect.
  44885. To customise its appearance, use the setGlowProperties() method.
  44886. */
  44887. GlowEffect();
  44888. /** Destructor. */
  44889. ~GlowEffect();
  44890. /** Sets the glow's radius and colour.
  44891. The radius is how large the blur should be, and the colour is
  44892. used to render it (for a less intense glow, lower the colour's
  44893. opacity).
  44894. */
  44895. void setGlowProperties (float newRadius,
  44896. const Colour& newColour);
  44897. /** @internal */
  44898. void applyEffect (Image& sourceImage, Graphics& destContext);
  44899. juce_UseDebuggingNewOperator
  44900. private:
  44901. float radius;
  44902. Colour colour;
  44903. };
  44904. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  44905. /*** End of inlined file: juce_GlowEffect.h ***/
  44906. #endif
  44907. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  44908. #endif
  44909. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44910. /*** Start of inlined file: juce_ReduceOpacityEffect.h ***/
  44911. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44912. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44913. /**
  44914. An effect filter that reduces the image's opacity.
  44915. This can be used to make a component (and its child components) more
  44916. transparent.
  44917. @see Component::setComponentEffect
  44918. */
  44919. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  44920. {
  44921. public:
  44922. /** Creates the effect object.
  44923. The opacity of the component to which the effect is applied will be
  44924. scaled by the given factor (in the range 0 to 1.0f).
  44925. */
  44926. ReduceOpacityEffect (float opacity = 1.0f);
  44927. /** Destructor. */
  44928. ~ReduceOpacityEffect();
  44929. /** Sets how much to scale the component's opacity.
  44930. @param newOpacity should be between 0 and 1.0f
  44931. */
  44932. void setOpacity (float newOpacity);
  44933. /** @internal */
  44934. void applyEffect (Image& sourceImage, Graphics& destContext);
  44935. juce_UseDebuggingNewOperator
  44936. private:
  44937. float opacity;
  44938. };
  44939. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44940. /*** End of inlined file: juce_ReduceOpacityEffect.h ***/
  44941. #endif
  44942. #ifndef __JUCE_FONT_JUCEHEADER__
  44943. #endif
  44944. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  44945. #endif
  44946. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  44947. #endif
  44948. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  44949. #endif
  44950. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  44951. #endif
  44952. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  44953. #endif
  44954. #ifndef __JUCE_LINE_JUCEHEADER__
  44955. #endif
  44956. #ifndef __JUCE_PATH_JUCEHEADER__
  44957. #endif
  44958. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  44959. /*** Start of inlined file: juce_PathIterator.h ***/
  44960. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  44961. #define __JUCE_PATHITERATOR_JUCEHEADER__
  44962. /**
  44963. Flattens a Path object into a series of straight-line sections.
  44964. Use one of these to iterate through a Path object, and it will convert
  44965. all the curves into line sections so it's easy to render or perform
  44966. geometric operations on.
  44967. @see Path
  44968. */
  44969. class JUCE_API PathFlatteningIterator
  44970. {
  44971. public:
  44972. /** Creates a PathFlatteningIterator.
  44973. After creation, use the next() method to initialise the fields in the
  44974. object with the first line's position.
  44975. @param path the path to iterate along
  44976. @param transform a transform to apply to each point in the path being iterated
  44977. @param tolerence the amount by which the curves are allowed to deviate from the
  44978. lines into which they are being broken down - a higher tolerence
  44979. is a bit faster, but less smooth.
  44980. */
  44981. PathFlatteningIterator (const Path& path,
  44982. const AffineTransform& transform = AffineTransform::identity,
  44983. float tolerence = 6.0f);
  44984. /** Destructor. */
  44985. ~PathFlatteningIterator();
  44986. /** Fetches the next line segment from the path.
  44987. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  44988. so that they describe the new line segment.
  44989. @returns false when there are no more lines to fetch.
  44990. */
  44991. bool next();
  44992. float x1; /**< The x position of the start of the current line segment. */
  44993. float y1; /**< The y position of the start of the current line segment. */
  44994. float x2; /**< The x position of the end of the current line segment. */
  44995. float y2; /**< The y position of the end of the current line segment. */
  44996. /** Indicates whether the current line segment is closing a sub-path.
  44997. If the current line is the one that connects the end of a sub-path
  44998. back to the start again, this will be true.
  44999. */
  45000. bool closesSubPath;
  45001. /** The index of the current line within the current sub-path.
  45002. E.g. you can use this to see whether the line is the first one in the
  45003. subpath by seeing if it's 0.
  45004. */
  45005. int subPathIndex;
  45006. /** Returns true if the current segment is the last in the current sub-path. */
  45007. bool isLastInSubpath() const throw() { return stackPos == stackBase.getData()
  45008. && (index >= path.numElements || points [index] == Path::moveMarker); }
  45009. juce_UseDebuggingNewOperator
  45010. private:
  45011. const Path& path;
  45012. const AffineTransform transform;
  45013. float* points;
  45014. float tolerence, subPathCloseX, subPathCloseY;
  45015. const bool isIdentityTransform;
  45016. HeapBlock <float> stackBase;
  45017. float* stackPos;
  45018. size_t index, stackSize;
  45019. PathFlatteningIterator (const PathFlatteningIterator&);
  45020. PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  45021. };
  45022. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  45023. /*** End of inlined file: juce_PathIterator.h ***/
  45024. #endif
  45025. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  45026. #endif
  45027. #ifndef __JUCE_POINT_JUCEHEADER__
  45028. #endif
  45029. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45030. /*** Start of inlined file: juce_PositionedRectangle.h ***/
  45031. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45032. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45033. /**
  45034. A rectangle whose co-ordinates can be defined in terms of absolute or
  45035. proportional distances.
  45036. Designed mainly for storing component positions, this gives you a lot of
  45037. control over how each co-ordinate is stored, either as an absolute position,
  45038. or as a proportion of the size of a parent rectangle.
  45039. It also allows you to define the anchor points by which the rectangle is
  45040. positioned, so for example you could specify that the top right of the
  45041. rectangle should be an absolute distance from its parent's bottom-right corner.
  45042. This object can be stored as a string, which takes the form "x y w h", including
  45043. symbols like '%' and letters to indicate the anchor point. See its toString()
  45044. method for more info.
  45045. Example usage:
  45046. @code
  45047. class MyComponent
  45048. {
  45049. void resized()
  45050. {
  45051. // this will set the child component's x to be 20% of our width, its y
  45052. // to be 30, its width to be 150, and its height to be 50% of our
  45053. // height..
  45054. const PositionedRectangle pos1 ("20% 30 150 50%");
  45055. pos1.applyToComponent (*myChildComponent1);
  45056. // this will inset the child component with a gap of 10 pixels
  45057. // around each of its edges..
  45058. const PositionedRectangle pos2 ("10 10 20M 20M");
  45059. pos2.applyToComponent (*myChildComponent2);
  45060. }
  45061. };
  45062. @endcode
  45063. */
  45064. class JUCE_API PositionedRectangle
  45065. {
  45066. public:
  45067. /** Creates an empty rectangle with all co-ordinates set to zero.
  45068. The default anchor point is top-left; the default
  45069. */
  45070. PositionedRectangle() throw();
  45071. /** Initialises a PositionedRectangle from a saved string version.
  45072. The string must be in the format generated by toString().
  45073. */
  45074. PositionedRectangle (const String& stringVersion) throw();
  45075. /** Creates a copy of another PositionedRectangle. */
  45076. PositionedRectangle (const PositionedRectangle& other) throw();
  45077. /** Copies another PositionedRectangle. */
  45078. PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  45079. /** Destructor. */
  45080. ~PositionedRectangle() throw();
  45081. /** Returns a string version of this position, from which it can later be
  45082. re-generated.
  45083. The format is four co-ordinates, "x y w h".
  45084. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  45085. - If a co-ordinate is proportional to its parent's width or height, it is stored
  45086. as a percentage, e.g. "80%".
  45087. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  45088. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  45089. the parent's right-hand edge.
  45090. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  45091. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  45092. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  45093. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  45094. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  45095. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  45096. has "c" appended to it. So "-50Rc" would mean that this component's
  45097. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  45098. this component's centre should be placed 40% across the parent's width.
  45099. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  45100. the number has "M" appended to it.
  45101. To reload a stored string, use the constructor that takes a string parameter.
  45102. */
  45103. const String toString() const throw();
  45104. /** Calculates the absolute position, given the size of the space that
  45105. it should go in.
  45106. This will work out any proportional distances and sizes relative to the
  45107. target rectangle, and will return the absolute position.
  45108. @see applyToComponent
  45109. */
  45110. const Rectangle<int> getRectangle (const Rectangle<int>& targetSpaceToBeRelativeTo) const throw();
  45111. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  45112. */
  45113. void getRectangleDouble (const Rectangle<int>& targetSpaceToBeRelativeTo,
  45114. double& x,
  45115. double& y,
  45116. double& width,
  45117. double& height) const throw();
  45118. /** This sets the bounds of the given component to this position.
  45119. This is equivalent to writing:
  45120. @code
  45121. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  45122. @endcode
  45123. @see getRectangle, updateFromComponent
  45124. */
  45125. void applyToComponent (Component& comp) const throw();
  45126. /** Updates this object's co-ordinates to match the given rectangle.
  45127. This will set all co-ordinates based on the given rectangle, re-calculating
  45128. any proportional distances, and using the current anchor points.
  45129. So for example if the x co-ordinate mode is currently proportional, this will
  45130. re-calculate x based on the rectangle's relative position within the target
  45131. rectangle's width.
  45132. If the target rectangle's width or height are zero then it may not be possible
  45133. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  45134. will not be changed.
  45135. */
  45136. void updateFrom (const Rectangle<int>& newPosition,
  45137. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45138. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  45139. */
  45140. void updateFromDouble (double x, double y, double width, double height,
  45141. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45142. /** Updates this object's co-ordinates to match the bounds of this component.
  45143. This is equivalent to calling updateFrom() with the component's bounds and
  45144. it parent size.
  45145. If the component doesn't currently have a parent, then proportional co-ordinates
  45146. might not be updated because it would need to know the parent's size to do the
  45147. maths for this.
  45148. */
  45149. void updateFromComponent (const Component& comp) throw();
  45150. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  45151. enum AnchorPoint
  45152. {
  45153. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  45154. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  45155. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  45156. };
  45157. /** Specifies how an x or y co-ordinate should be interpreted. */
  45158. enum PositionMode
  45159. {
  45160. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  45161. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  45162. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  45163. 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. */
  45164. };
  45165. /** Specifies how the width or height should be interpreted. */
  45166. enum SizeMode
  45167. {
  45168. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  45169. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  45170. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  45171. };
  45172. /** Sets all options for all co-ordinates.
  45173. This requires a reference rectangle to be specified, because if you're changing any
  45174. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  45175. the co-ordinates, and will need to know the parent size so it can calculate this.
  45176. */
  45177. void setModes (const AnchorPoint xAnchorMode,
  45178. const PositionMode xPositionMode,
  45179. const AnchorPoint yAnchorMode,
  45180. const PositionMode yPositionMode,
  45181. const SizeMode widthMode,
  45182. const SizeMode heightMode,
  45183. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45184. /** Returns the anchoring mode for the x co-ordinate.
  45185. To change any of the modes, use setModes().
  45186. */
  45187. AnchorPoint getAnchorPointX() const throw();
  45188. /** Returns the positioning mode for the x co-ordinate.
  45189. To change any of the modes, use setModes().
  45190. */
  45191. PositionMode getPositionModeX() const throw();
  45192. /** Returns the raw x co-ordinate.
  45193. If the x position mode is absolute, then this will be the absolute value. If it's
  45194. proportional, then this will be a fractional proportion, where 1.0 means the full
  45195. width of the parent space.
  45196. */
  45197. double getX() const throw() { return x; }
  45198. /** Sets the raw value of the x co-ordinate.
  45199. See getX() for the meaning of this value.
  45200. */
  45201. void setX (const double newX) throw() { x = newX; }
  45202. /** Returns the anchoring mode for the y co-ordinate.
  45203. To change any of the modes, use setModes().
  45204. */
  45205. AnchorPoint getAnchorPointY() const throw();
  45206. /** Returns the positioning mode for the y co-ordinate.
  45207. To change any of the modes, use setModes().
  45208. */
  45209. PositionMode getPositionModeY() const throw();
  45210. /** Returns the raw y co-ordinate.
  45211. If the y position mode is absolute, then this will be the absolute value. If it's
  45212. proportional, then this will be a fractional proportion, where 1.0 means the full
  45213. height of the parent space.
  45214. */
  45215. double getY() const throw() { return y; }
  45216. /** Sets the raw value of the y co-ordinate.
  45217. See getY() for the meaning of this value.
  45218. */
  45219. void setY (const double newY) throw() { y = newY; }
  45220. /** Returns the mode used to calculate the width.
  45221. To change any of the modes, use setModes().
  45222. */
  45223. SizeMode getWidthMode() const throw();
  45224. /** Returns the raw width value.
  45225. If the width mode is absolute, then this will be the absolute value. If the mode is
  45226. proportional, then this will be a fractional proportion, where 1.0 means the full
  45227. width of the parent space.
  45228. */
  45229. double getWidth() const throw() { return w; }
  45230. /** Sets the raw width value.
  45231. See getWidth() for the details about what this value means.
  45232. */
  45233. void setWidth (const double newWidth) throw() { w = newWidth; }
  45234. /** Returns the mode used to calculate the height.
  45235. To change any of the modes, use setModes().
  45236. */
  45237. SizeMode getHeightMode() const throw();
  45238. /** Returns the raw height value.
  45239. If the height mode is absolute, then this will be the absolute value. If the mode is
  45240. proportional, then this will be a fractional proportion, where 1.0 means the full
  45241. height of the parent space.
  45242. */
  45243. double getHeight() const throw() { return h; }
  45244. /** Sets the raw height value.
  45245. See getHeight() for the details about what this value means.
  45246. */
  45247. void setHeight (const double newHeight) throw() { h = newHeight; }
  45248. /** If the size and position are constance, and wouldn't be affected by changes
  45249. in the parent's size, then this will return true.
  45250. */
  45251. bool isPositionAbsolute() const throw();
  45252. /** Compares two objects. */
  45253. bool operator== (const PositionedRectangle& other) const throw();
  45254. /** Compares two objects. */
  45255. bool operator!= (const PositionedRectangle& other) const throw();
  45256. juce_UseDebuggingNewOperator
  45257. private:
  45258. double x, y, w, h;
  45259. uint8 xMode, yMode, wMode, hMode;
  45260. void addPosDescription (String& result, uint8 mode, double value) const throw();
  45261. void addSizeDescription (String& result, uint8 mode, double value) const throw();
  45262. void decodePosString (const String& s, uint8& mode, double& value) throw();
  45263. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  45264. void applyPosAndSize (double& xOut, double& wOut, double x, double w,
  45265. uint8 xMode, uint8 wMode,
  45266. int parentPos, int parentSize) const throw();
  45267. void updatePosAndSize (double& xOut, double& wOut, double x, double w,
  45268. uint8 xMode, uint8 wMode,
  45269. int parentPos, int parentSize) const throw();
  45270. };
  45271. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45272. /*** End of inlined file: juce_PositionedRectangle.h ***/
  45273. #endif
  45274. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  45275. #endif
  45276. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  45277. #endif
  45278. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  45279. #endif
  45280. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  45281. /*** Start of inlined file: juce_CameraDevice.h ***/
  45282. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  45283. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  45284. #if JUCE_USE_CAMERA || DOXYGEN
  45285. /**
  45286. Receives callbacks with images from a CameraDevice.
  45287. @see CameraDevice::addListener
  45288. */
  45289. class CameraImageListener
  45290. {
  45291. public:
  45292. CameraImageListener() {}
  45293. virtual ~CameraImageListener() {}
  45294. /** This method is called when a new image arrives.
  45295. This may be called by any thread, so be careful about thread-safety,
  45296. and make sure that you process the data as quickly as possible to
  45297. avoid glitching!
  45298. */
  45299. virtual void imageReceived (const Image& image) = 0;
  45300. };
  45301. /**
  45302. Controls any camera capture devices that might be available.
  45303. Use getAvailableDevices() to list the devices that are attached to the
  45304. system, then call openDevice to open one for use. Once you have a CameraDevice
  45305. object, you can get a viewer component from it, and use its methods to
  45306. stream to a file or capture still-frames.
  45307. */
  45308. class JUCE_API CameraDevice
  45309. {
  45310. public:
  45311. /** Destructor. */
  45312. virtual ~CameraDevice();
  45313. /** Returns a list of the available cameras on this machine.
  45314. You can open one of these devices by calling openDevice().
  45315. */
  45316. static const StringArray getAvailableDevices();
  45317. /** Opens a camera device.
  45318. The index parameter indicates which of the items returned by getAvailableDevices()
  45319. to open.
  45320. The size constraints allow the method to choose between different resolutions if
  45321. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  45322. then these will be ignored.
  45323. */
  45324. static CameraDevice* openDevice (int deviceIndex,
  45325. int minWidth = 128, int minHeight = 64,
  45326. int maxWidth = 1024, int maxHeight = 768);
  45327. /** Returns the name of this device */
  45328. const String getName() const { return name; }
  45329. /** Creates a component that can be used to display a preview of the
  45330. video from this camera.
  45331. */
  45332. Component* createViewerComponent();
  45333. /** Starts recording video to the specified file.
  45334. You should use getFileExtension() to find out the correct extension to
  45335. use for your filename.
  45336. If the file exists, it will be deleted before the recording starts.
  45337. This method may not start recording instantly, so if you need to know the
  45338. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  45339. after the recording has finished.
  45340. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  45341. or may not be used, depending on the driver.
  45342. */
  45343. void startRecordingToFile (const File& file, int quality = 2);
  45344. /** Stops recording, after a call to startRecordingToFile().
  45345. */
  45346. void stopRecording();
  45347. /** Returns the file extension that should be used for the files
  45348. that you pass to startRecordingToFile().
  45349. This may be platform-specific, e.g. ".mov" or ".avi".
  45350. */
  45351. static const String getFileExtension();
  45352. /** After calling stopRecording(), this method can be called to return the timestamp
  45353. of the first frame that was written to the file.
  45354. */
  45355. const Time getTimeOfFirstRecordedFrame() const;
  45356. /** Adds a listener to receive images from the camera.
  45357. Be very careful not to delete the listener without first removing it by calling
  45358. removeListener().
  45359. */
  45360. void addListener (CameraImageListener* listenerToAdd);
  45361. /** Removes a listener that was previously added with addListener().
  45362. */
  45363. void removeListener (CameraImageListener* listenerToRemove);
  45364. juce_UseDebuggingNewOperator
  45365. protected:
  45366. /** @internal */
  45367. CameraDevice (const String& name, int index);
  45368. private:
  45369. void* internal;
  45370. bool isRecording;
  45371. String name;
  45372. CameraDevice (const CameraDevice&);
  45373. CameraDevice& operator= (const CameraDevice&);
  45374. };
  45375. #endif
  45376. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  45377. /*** End of inlined file: juce_CameraDevice.h ***/
  45378. #endif
  45379. #ifndef __JUCE_IMAGE_JUCEHEADER__
  45380. #endif
  45381. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  45382. /*** Start of inlined file: juce_ImageCache.h ***/
  45383. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  45384. #define __JUCE_IMAGECACHE_JUCEHEADER__
  45385. /**
  45386. A global cache of images that have been loaded from files or memory.
  45387. If you're loading an image and may need to use the image in more than one
  45388. place, this is used to allow the same image to be shared rather than loading
  45389. multiple copies into memory.
  45390. Another advantage is that after images are released, they will be kept in
  45391. memory for a few seconds before it is actually deleted, so if you're repeatedly
  45392. loading/deleting the same image, it'll reduce the chances of having to reload it
  45393. each time.
  45394. @see Image, ImageFileFormat
  45395. */
  45396. class JUCE_API ImageCache
  45397. {
  45398. public:
  45399. /** Loads an image from a file, (or just returns the image if it's already cached).
  45400. If the cache already contains an image that was loaded from this file,
  45401. that image will be returned. Otherwise, this method will try to load the
  45402. file, add it to the cache, and return it.
  45403. Remember that the image returned is shared, so drawing into it might
  45404. affect other things that are using it! If you want to draw on it, first
  45405. call Image::duplicateIfShared()
  45406. @param file the file to try to load
  45407. @returns the image, or null if it there was an error loading it
  45408. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  45409. */
  45410. static const Image getFromFile (const File& file);
  45411. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  45412. If the cache already contains an image that was loaded from this block of memory,
  45413. that image will be returned. Otherwise, this method will try to load the
  45414. file, add it to the cache, and return it.
  45415. Remember that the image returned is shared, so drawing into it might
  45416. affect other things that are using it! If you want to draw on it, first
  45417. call Image::duplicateIfShared()
  45418. @param imageData the block of memory containing the image data
  45419. @param dataSize the data size in bytes
  45420. @returns the image, or an invalid image if it there was an error loading it
  45421. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  45422. */
  45423. static const Image getFromMemory (const void* imageData, int dataSize);
  45424. /** Checks the cache for an image with a particular hashcode.
  45425. If there's an image in the cache with this hashcode, it will be returned,
  45426. otherwise it will return an invalid image.
  45427. @param hashCode the hash code that was associated with the image by addImageToCache()
  45428. @see addImageToCache
  45429. */
  45430. static const Image getFromHashCode (int64 hashCode);
  45431. /** Adds an image to the cache with a user-defined hash-code.
  45432. The image passed-in will be referenced (not copied) by the cache, so it's probably
  45433. a good idea not to draw into it after adding it, otherwise this will affect all
  45434. instances of it that may be in use.
  45435. @param image the image to add
  45436. @param hashCode the hash-code to associate with it
  45437. @see getFromHashCode
  45438. */
  45439. static void addImageToCache (const Image& image, int64 hashCode);
  45440. /** Changes the amount of time before an unused image will be removed from the cache.
  45441. By default this is about 5 seconds.
  45442. */
  45443. static void setCacheTimeout (int millisecs);
  45444. juce_UseDebuggingNewOperator
  45445. private:
  45446. class Pimpl;
  45447. ImageCache();
  45448. ImageCache (const ImageCache&);
  45449. ImageCache& operator= (const ImageCache&);
  45450. ~ImageCache();
  45451. };
  45452. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  45453. /*** End of inlined file: juce_ImageCache.h ***/
  45454. #endif
  45455. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45456. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  45457. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45458. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45459. /**
  45460. Represents a filter kernel to use in convoluting an image.
  45461. @see Image::applyConvolution
  45462. */
  45463. class JUCE_API ImageConvolutionKernel
  45464. {
  45465. public:
  45466. /** Creates an empty convulution kernel.
  45467. @param size the length of each dimension of the kernel, so e.g. if the size
  45468. is 5, it will create a 5x5 kernel
  45469. */
  45470. ImageConvolutionKernel (int size);
  45471. /** Destructor. */
  45472. ~ImageConvolutionKernel();
  45473. /** Resets all values in the kernel to zero. */
  45474. void clear();
  45475. /** Returns one of the kernel values. */
  45476. float getKernelValue (int x, int y) const throw();
  45477. /** Sets the value of a specific cell in the kernel.
  45478. The x and y parameters must be in the range 0 < x < getKernelSize().
  45479. @see setOverallSum
  45480. */
  45481. void setKernelValue (int x, int y, float value) throw();
  45482. /** Rescales all values in the kernel to make the total add up to a fixed value.
  45483. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  45484. */
  45485. void setOverallSum (float desiredTotalSum);
  45486. /** Multiplies all values in the kernel by a value. */
  45487. void rescaleAllValues (float multiplier);
  45488. /** Intialises the kernel for a gaussian blur.
  45489. @param blurRadius this may be larger or smaller than the kernel's actual
  45490. size but this will obviously be wasteful or clip at the
  45491. edges. Ideally the kernel should be just larger than
  45492. (blurRadius * 2).
  45493. */
  45494. void createGaussianBlur (float blurRadius);
  45495. /** Returns the size of the kernel.
  45496. E.g. if it's a 3x3 kernel, this returns 3.
  45497. */
  45498. int getKernelSize() const { return size; }
  45499. /** Applies the kernel to an image.
  45500. @param destImage the image that will receive the resultant convoluted pixels.
  45501. @param sourceImage the source image to read from - this can be the same image as
  45502. the destination, but if different, it must be exactly the same
  45503. size and format.
  45504. @param destinationArea the region of the image to apply the filter to
  45505. */
  45506. void applyToImage (Image& destImage,
  45507. const Image& sourceImage,
  45508. const Rectangle<int>& destinationArea) const;
  45509. juce_UseDebuggingNewOperator
  45510. private:
  45511. HeapBlock <float> values;
  45512. const int size;
  45513. // no reason not to implement these one day..
  45514. ImageConvolutionKernel (const ImageConvolutionKernel&);
  45515. ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  45516. };
  45517. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45518. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  45519. #endif
  45520. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45521. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  45522. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45523. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45524. /**
  45525. Base-class for codecs that can read and write image file formats such
  45526. as PNG, JPEG, etc.
  45527. This class also contains static methods to make it easy to load images
  45528. from files, streams or from memory.
  45529. @see Image, ImageCache
  45530. */
  45531. class JUCE_API ImageFileFormat
  45532. {
  45533. protected:
  45534. /** Creates an ImageFormat. */
  45535. ImageFileFormat() {}
  45536. public:
  45537. /** Destructor. */
  45538. virtual ~ImageFileFormat() {}
  45539. /** Returns a description of this file format.
  45540. E.g. "JPEG", "PNG"
  45541. */
  45542. virtual const String getFormatName() = 0;
  45543. /** Returns true if the given stream seems to contain data that this format
  45544. understands.
  45545. The format class should only read the first few bytes of the stream and sniff
  45546. for header bytes that it understands.
  45547. @see decodeImage
  45548. */
  45549. virtual bool canUnderstand (InputStream& input) = 0;
  45550. /** Tries to decode and return an image from the given stream.
  45551. This will be called for an image format after calling its canUnderStand() method
  45552. to see if it can handle the stream.
  45553. @param input the stream to read the data from. The stream will be positioned
  45554. at the start of the image data (but this may not necessarily
  45555. be position 0)
  45556. @returns the image that was decoded, or an invalid image if it fails.
  45557. @see loadFrom
  45558. */
  45559. virtual const Image decodeImage (InputStream& input) = 0;
  45560. /** Attempts to write an image to a stream.
  45561. To specify extra information like encoding quality, there will be appropriate parameters
  45562. in the subclasses of the specific file types.
  45563. @returns true if it nothing went wrong.
  45564. */
  45565. virtual bool writeImageToStream (const Image& sourceImage,
  45566. OutputStream& destStream) = 0;
  45567. /** Tries the built-in decoders to see if it can find one to read this stream.
  45568. There are currently built-in decoders for PNG, JPEG and GIF formats.
  45569. The object that is returned should not be deleted by the caller.
  45570. @see canUnderstand, decodeImage, loadFrom
  45571. */
  45572. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  45573. /** Tries to load an image from a stream.
  45574. This will use the findImageFormatForStream() method to locate a suitable
  45575. codec, and use that to load the image.
  45576. @returns the image that was decoded, or an invalid image if it fails.
  45577. */
  45578. static const Image loadFrom (InputStream& input);
  45579. /** Tries to load an image from a file.
  45580. This will use the findImageFormatForStream() method to locate a suitable
  45581. codec, and use that to load the image.
  45582. @returns the image that was decoded, or an invalid image if it fails.
  45583. */
  45584. static const Image loadFrom (const File& file);
  45585. /** Tries to load an image from a block of raw image data.
  45586. This will use the findImageFormatForStream() method to locate a suitable
  45587. codec, and use that to load the image.
  45588. @returns the image that was decoded, or an invalid image if it fails.
  45589. */
  45590. static const Image loadFrom (const void* rawData,
  45591. const int numBytesOfData);
  45592. };
  45593. /**
  45594. A type of ImageFileFormat for reading and writing PNG files.
  45595. @see ImageFileFormat, JPEGImageFormat
  45596. */
  45597. class JUCE_API PNGImageFormat : public ImageFileFormat
  45598. {
  45599. public:
  45600. PNGImageFormat();
  45601. ~PNGImageFormat();
  45602. const String getFormatName();
  45603. bool canUnderstand (InputStream& input);
  45604. const Image decodeImage (InputStream& input);
  45605. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45606. };
  45607. /**
  45608. A type of ImageFileFormat for reading and writing JPEG files.
  45609. @see ImageFileFormat, PNGImageFormat
  45610. */
  45611. class JUCE_API JPEGImageFormat : public ImageFileFormat
  45612. {
  45613. public:
  45614. JPEGImageFormat();
  45615. ~JPEGImageFormat();
  45616. /** Specifies the quality to be used when writing a JPEG file.
  45617. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  45618. any negative value is "default" quality
  45619. */
  45620. void setQuality (const float newQuality);
  45621. const String getFormatName();
  45622. bool canUnderstand (InputStream& input);
  45623. const Image decodeImage (InputStream& input);
  45624. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45625. private:
  45626. float quality;
  45627. };
  45628. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45629. /*** End of inlined file: juce_ImageFileFormat.h ***/
  45630. #endif
  45631. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  45632. #endif
  45633. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45634. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  45635. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45636. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45637. /**
  45638. A class to take care of the logic involved with the loading/saving of some kind
  45639. of document.
  45640. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  45641. functions you need for documents that get saved to a file, so this class attempts
  45642. to abstract most of the boring stuff.
  45643. Your subclass should just implement all the pure virtual methods, and you can
  45644. then use the higher-level public methods to do the load/save dialogs, to warn the user
  45645. about overwriting files, etc.
  45646. The document object keeps track of whether it has changed since it was last saved or
  45647. loaded, so when you change something, call its changed() method. This will set a
  45648. flag so it knows it needs saving, and will also broadcast a change message using the
  45649. ChangeBroadcaster base class.
  45650. @see ChangeBroadcaster
  45651. */
  45652. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  45653. {
  45654. public:
  45655. /** Creates a FileBasedDocument.
  45656. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  45657. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  45658. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  45659. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  45660. */
  45661. FileBasedDocument (const String& fileExtension,
  45662. const String& fileWildCard,
  45663. const String& openFileDialogTitle,
  45664. const String& saveFileDialogTitle);
  45665. /** Destructor. */
  45666. virtual ~FileBasedDocument();
  45667. /** Returns true if the changed() method has been called since the file was
  45668. last saved or loaded.
  45669. @see resetChangedFlag, changed
  45670. */
  45671. bool hasChangedSinceSaved() const { return changedSinceSave; }
  45672. /** Called to indicate that the document has changed and needs saving.
  45673. This method will also trigger a change message to be sent out using the
  45674. ChangeBroadcaster base class.
  45675. After calling the method, the hasChangedSinceSaved() method will return true, until
  45676. it is reset either by saving to a file or using the resetChangedFlag() method.
  45677. @see hasChangedSinceSaved, resetChangedFlag
  45678. */
  45679. virtual void changed();
  45680. /** Sets the state of the 'changed' flag.
  45681. The 'changed' flag is set to true when the changed() method is called - use this method
  45682. to reset it or to set it without also broadcasting a change message.
  45683. @see changed, hasChangedSinceSaved
  45684. */
  45685. void setChangedFlag (bool hasChanged);
  45686. /** Tries to open a file.
  45687. If the file opens correctly, the document's file (see the getFile() method) is set
  45688. to this new one; if it fails, the document's file is left unchanged, and optionally
  45689. a message box is shown telling the user there was an error.
  45690. @returns true if the new file loaded successfully
  45691. @see loadDocument, loadFromUserSpecifiedFile
  45692. */
  45693. bool loadFrom (const File& fileToLoadFrom,
  45694. bool showMessageOnFailure);
  45695. /** Asks the user for a file and tries to load it.
  45696. This will pop up a dialog box using the title, file extension and
  45697. wildcard specified in the document's constructor, and asks the user
  45698. for a file. If they pick one, the loadFrom() method is used to
  45699. try to load it, optionally showing a message if it fails.
  45700. @returns true if a file was loaded; false if the user cancelled or if they
  45701. picked a file which failed to load correctly
  45702. @see loadFrom
  45703. */
  45704. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  45705. /** A set of possible outcomes of one of the save() methods
  45706. */
  45707. enum SaveResult
  45708. {
  45709. savedOk = 0, /**< indicates that a file was saved successfully. */
  45710. userCancelledSave, /**< indicates that the user aborted the save operation. */
  45711. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  45712. };
  45713. /** Tries to save the document to the last file it was saved or loaded from.
  45714. This will always try to write to the file, even if the document isn't flagged as
  45715. having changed.
  45716. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  45717. true, it will prompt the user to pick a file, as if
  45718. saveAsInteractive() was called.
  45719. @param showMessageOnFailure if true it will show a warning message when if the
  45720. save operation fails
  45721. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  45722. */
  45723. SaveResult save (bool askUserForFileIfNotSpecified,
  45724. bool showMessageOnFailure);
  45725. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  45726. it if they say yes.
  45727. If you've got a document open and want to close it (e.g. to quit the app), this is the
  45728. method to call.
  45729. If the document doesn't need saving it'll return the value savedOk so
  45730. you can go ahead and delete the document.
  45731. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  45732. return savedOk, so again, you can safely delete the document.
  45733. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  45734. close-document operation.
  45735. And if they click "save changes", it'll try to save and either return savedOk, or
  45736. failedToWriteToFile if there was a problem.
  45737. @see save, saveAs, saveAsInteractive
  45738. */
  45739. SaveResult saveIfNeededAndUserAgrees();
  45740. /** Tries to save the document to a specified file.
  45741. If this succeeds, it'll also change the document's internal file (as returned by
  45742. the getFile() method). If it fails, the file will be left unchanged.
  45743. @param newFile the file to try to write to
  45744. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45745. the user first if they want to overwrite it
  45746. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  45747. use the saveAsInteractive() method to ask the user for a
  45748. filename
  45749. @param showMessageOnFailure if true and the write operation fails, it'll show
  45750. a message box to warn the user
  45751. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  45752. */
  45753. SaveResult saveAs (const File& newFile,
  45754. bool warnAboutOverwritingExistingFiles,
  45755. bool askUserForFileIfNotSpecified,
  45756. bool showMessageOnFailure);
  45757. /** Prompts the user for a filename and tries to save to it.
  45758. This will pop up a dialog box using the title, file extension and
  45759. wildcard specified in the document's constructor, and asks the user
  45760. for a file. If they pick one, the saveAs() method is used to try to save
  45761. to this file.
  45762. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45763. the user first if they want to overwrite it
  45764. @see saveIfNeededAndUserAgrees, save, saveAs
  45765. */
  45766. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  45767. /** Returns the file that this document was last successfully saved or loaded from.
  45768. When the document object is created, this will be set to File::nonexistent.
  45769. It is changed when one of the load or save methods is used, or when setFile()
  45770. is used to explicitly set it.
  45771. */
  45772. const File getFile() const { return documentFile; }
  45773. /** Sets the file that this document thinks it was loaded from.
  45774. This won't actually load anything - it just changes the file stored internally.
  45775. @see getFile
  45776. */
  45777. void setFile (const File& newFile);
  45778. protected:
  45779. /** Overload this to return the title of the document.
  45780. This is used in message boxes, filenames and file choosers, so it should be
  45781. something sensible.
  45782. */
  45783. virtual const String getDocumentTitle() = 0;
  45784. /** This method should try to load your document from the given file.
  45785. If it fails, it should return an error message. If it succeeds, it should return
  45786. an empty string.
  45787. */
  45788. virtual const String loadDocument (const File& file) = 0;
  45789. /** This method should try to write your document to the given file.
  45790. If it fails, it should return an error message. If it succeeds, it should return
  45791. an empty string.
  45792. */
  45793. virtual const String saveDocument (const File& file) = 0;
  45794. /** This is used for dialog boxes to make them open at the last folder you
  45795. were using.
  45796. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45797. the last document that was used - you might want to store this value
  45798. in a static variable, or even in your application's properties. It should
  45799. be a global setting rather than a property of this object.
  45800. This method works very well in conjunction with a RecentlyOpenedFilesList
  45801. object to manage your recent-files list.
  45802. As a default value, it's ok to return File::nonexistent, and the document
  45803. object will use a sensible one instead.
  45804. @see RecentlyOpenedFilesList
  45805. */
  45806. virtual const File getLastDocumentOpened() = 0;
  45807. /** This is used for dialog boxes to make them open at the last folder you
  45808. were using.
  45809. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45810. the last document that was used - you might want to store this value
  45811. in a static variable, or even in your application's properties. It should
  45812. be a global setting rather than a property of this object.
  45813. This method works very well in conjunction with a RecentlyOpenedFilesList
  45814. object to manage your recent-files list.
  45815. @see RecentlyOpenedFilesList
  45816. */
  45817. virtual void setLastDocumentOpened (const File& file) = 0;
  45818. public:
  45819. juce_UseDebuggingNewOperator
  45820. private:
  45821. File documentFile;
  45822. bool changedSinceSave;
  45823. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  45824. FileBasedDocument (const FileBasedDocument&);
  45825. FileBasedDocument& operator= (const FileBasedDocument&);
  45826. };
  45827. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45828. /*** End of inlined file: juce_FileBasedDocument.h ***/
  45829. #endif
  45830. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  45831. #endif
  45832. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45833. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45834. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45835. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45836. /**
  45837. Manages a set of files for use as a list of recently-opened documents.
  45838. This is a handy class for holding your list of recently-opened documents, with
  45839. helpful methods for things like purging any non-existent files, automatically
  45840. adding them to a menu, and making persistence easy.
  45841. @see File, FileBasedDocument
  45842. */
  45843. class JUCE_API RecentlyOpenedFilesList
  45844. {
  45845. public:
  45846. /** Creates an empty list.
  45847. */
  45848. RecentlyOpenedFilesList();
  45849. /** Destructor. */
  45850. ~RecentlyOpenedFilesList();
  45851. /** Sets a limit for the number of files that will be stored in the list.
  45852. When addFile() is called, then if there is no more space in the list, the
  45853. least-recently added file will be dropped.
  45854. @see getMaxNumberOfItems
  45855. */
  45856. void setMaxNumberOfItems (int newMaxNumber);
  45857. /** Returns the number of items that this list will store.
  45858. @see setMaxNumberOfItems
  45859. */
  45860. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  45861. /** Returns the number of files in the list.
  45862. The most recently added file is always at index 0.
  45863. */
  45864. int getNumFiles() const;
  45865. /** Returns one of the files in the list.
  45866. The most recently added file is always at index 0.
  45867. */
  45868. const File getFile (int index) const;
  45869. /** Returns an array of all the absolute pathnames in the list.
  45870. */
  45871. const StringArray& getAllFilenames() const throw() { return files; }
  45872. /** Clears all the files from the list. */
  45873. void clear();
  45874. /** Adds a file to the list.
  45875. The file will be added at index 0. If this file is already in the list, it will
  45876. be moved up to index 0, but a file can only appear once in the list.
  45877. If the list already contains the maximum number of items that is permitted, the
  45878. least-recently added file will be dropped from the end.
  45879. */
  45880. void addFile (const File& file);
  45881. /** Checks each of the files in the list, removing any that don't exist.
  45882. You might want to call this after reloading a list of files, or before putting them
  45883. on a menu.
  45884. */
  45885. void removeNonExistentFiles();
  45886. /** Adds entries to a menu, representing each of the files in the list.
  45887. This is handy for creating an "open recent file..." menu in your app. The
  45888. menu items are numbered consecutively starting with the baseItemId value,
  45889. and can either be added as complete pathnames, or just the last part of the
  45890. filename.
  45891. If dontAddNonExistentFiles is true, then each file will be checked and only those
  45892. that exist will be added.
  45893. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  45894. pointers to file objects. Any files that appear in this list will not be added to the
  45895. menu - the reason for this is that you might have a number of files already open, so
  45896. might not want these to be shown in the menu.
  45897. It returns the number of items that were added.
  45898. */
  45899. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  45900. int baseItemId,
  45901. bool showFullPaths,
  45902. bool dontAddNonExistentFiles,
  45903. const File** filesToAvoid = 0);
  45904. /** Returns a string that encapsulates all the files in the list.
  45905. The string that is returned can later be passed into restoreFromString() in
  45906. order to recreate the list. This is handy for persisting your list, e.g. in
  45907. a PropertiesFile object.
  45908. @see restoreFromString
  45909. */
  45910. const String toString() const;
  45911. /** Restores the list from a previously stringified version of the list.
  45912. Pass in a stringified version created with toString() in order to persist/restore
  45913. your list.
  45914. @see toString
  45915. */
  45916. void restoreFromString (const String& stringifiedVersion);
  45917. juce_UseDebuggingNewOperator
  45918. private:
  45919. StringArray files;
  45920. int maxNumberOfItems;
  45921. };
  45922. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45923. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45924. #endif
  45925. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45926. #endif
  45927. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45928. /*** Start of inlined file: juce_SystemClipboard.h ***/
  45929. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45930. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45931. /**
  45932. Handles reading/writing to the system's clipboard.
  45933. */
  45934. class JUCE_API SystemClipboard
  45935. {
  45936. public:
  45937. /** Copies a string of text onto the clipboard */
  45938. static void copyTextToClipboard (const String& text);
  45939. /** Gets the current clipboard's contents.
  45940. Obviously this might have come from another app, so could contain
  45941. anything..
  45942. */
  45943. static const String getTextFromClipboard();
  45944. };
  45945. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45946. /*** End of inlined file: juce_SystemClipboard.h ***/
  45947. #endif
  45948. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  45949. #endif
  45950. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  45951. #endif
  45952. #endif
  45953. /*** End of inlined file: juce_app_includes.h ***/
  45954. #endif
  45955. #if JUCE_MSVC
  45956. #pragma warning (pop)
  45957. #pragma pack (pop)
  45958. #endif
  45959. END_JUCE_NAMESPACE
  45960. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  45961. #ifdef JUCE_NAMESPACE
  45962. // this will obviously save a lot of typing, but can be disabled by
  45963. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  45964. using namespace JUCE_NAMESPACE;
  45965. /* On the Mac, these symbols are defined in the Mac libraries, so
  45966. these macros make it easier to reference them without writing out
  45967. the namespace every time.
  45968. If you run into difficulties where these macros interfere with the contents
  45969. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  45970. the comments in that file for more information.
  45971. */
  45972. #if (JUCE_MAC || JUCE_IPHONE) && ! JUCE_DONT_DEFINE_MACROS
  45973. #define Component JUCE_NAMESPACE::Component
  45974. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  45975. #define Point JUCE_NAMESPACE::Point
  45976. #define Button JUCE_NAMESPACE::Button
  45977. #endif
  45978. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  45979. it easier to use the juce version explicitly.
  45980. If you run into difficulties where this macro interferes with other 3rd party header
  45981. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  45982. file for more information.
  45983. */
  45984. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  45985. #define Rectangle JUCE_NAMESPACE::Rectangle
  45986. #endif
  45987. #endif
  45988. #endif
  45989. /* Easy autolinking to the right JUCE libraries under win32.
  45990. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  45991. including this header file.
  45992. */
  45993. #if JUCE_MSVC
  45994. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  45995. /** If you want your application to link to Juce as a DLL instead of
  45996. a static library (on win32), just define the JUCE_DLL macro before
  45997. including juce.h
  45998. */
  45999. #ifdef JUCE_DLL
  46000. #if JUCE_DEBUG
  46001. #define AUTOLINKEDLIB "JUCE_debug.lib"
  46002. #else
  46003. #define AUTOLINKEDLIB "JUCE.lib"
  46004. #endif
  46005. #else
  46006. #if JUCE_DEBUG
  46007. #ifdef _WIN64
  46008. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  46009. #else
  46010. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  46011. #endif
  46012. #else
  46013. #ifdef _WIN64
  46014. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  46015. #else
  46016. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  46017. #endif
  46018. #endif
  46019. #endif
  46020. #pragma comment(lib, AUTOLINKEDLIB)
  46021. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  46022. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  46023. #endif
  46024. // Auto-link the other win32 libs that are needed by library calls..
  46025. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  46026. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  46027. // Auto-links to various win32 libs that are needed by library calls..
  46028. #pragma comment(lib, "kernel32.lib")
  46029. #pragma comment(lib, "user32.lib")
  46030. #pragma comment(lib, "shell32.lib")
  46031. #pragma comment(lib, "gdi32.lib")
  46032. #pragma comment(lib, "vfw32.lib")
  46033. #pragma comment(lib, "comdlg32.lib")
  46034. #pragma comment(lib, "winmm.lib")
  46035. #pragma comment(lib, "wininet.lib")
  46036. #pragma comment(lib, "ole32.lib")
  46037. #pragma comment(lib, "oleaut32.lib")
  46038. #pragma comment(lib, "advapi32.lib")
  46039. #pragma comment(lib, "ws2_32.lib")
  46040. #pragma comment(lib, "comsupp.lib")
  46041. #pragma comment(lib, "version.lib")
  46042. #if JUCE_OPENGL
  46043. #pragma comment(lib, "OpenGL32.Lib")
  46044. #pragma comment(lib, "GlU32.Lib")
  46045. #endif
  46046. #if JUCE_QUICKTIME
  46047. #pragma comment (lib, "QTMLClient.lib")
  46048. #endif
  46049. #if JUCE_USE_CAMERA
  46050. #pragma comment (lib, "Strmiids.lib")
  46051. #pragma comment (lib, "wmvcore.lib")
  46052. #endif
  46053. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  46054. #endif
  46055. #endif
  46056. #endif
  46057. /*
  46058. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  46059. AppSubClass is the name of a class derived from JUCEApplication.
  46060. See the JUCEApplication class documentation (juce_Application.h) for more details.
  46061. */
  46062. #if defined (JUCE_GCC) || defined (__MWERKS__)
  46063. #define START_JUCE_APPLICATION(AppClass) \
  46064. int main (int argc, char* argv[]) \
  46065. { \
  46066. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv, new AppClass()); \
  46067. }
  46068. #elif JUCE_WINDOWS
  46069. #ifdef _CONSOLE
  46070. #define START_JUCE_APPLICATION(AppClass) \
  46071. int main (int, char* argv[]) \
  46072. { \
  46073. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  46074. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  46075. }
  46076. #elif ! defined (_AFXDLL)
  46077. #ifdef _WINDOWS_
  46078. #define START_JUCE_APPLICATION(AppClass) \
  46079. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  46080. { \
  46081. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  46082. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  46083. }
  46084. #else
  46085. #define START_JUCE_APPLICATION(AppClass) \
  46086. int __stdcall WinMain (int, int, const char*, int) \
  46087. { \
  46088. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  46089. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  46090. }
  46091. #endif
  46092. #endif
  46093. #endif
  46094. #endif // __JUCE_JUCEHEADER__
  46095. /*** End of inlined file: juce.h ***/
  46096. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__