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.

60335 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 6
  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. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  484. object so they can be logged by the application if it wants to.
  485. */
  486. #define JUCE_CATCH_EXCEPTION \
  487. catch (const std::exception& e) \
  488. { \
  489. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  490. } \
  491. catch (...) \
  492. { \
  493. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  494. }
  495. #define JUCE_CATCH_ALL catch (...) {}
  496. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  497. #else
  498. #define JUCE_TRY
  499. #define JUCE_CATCH_EXCEPTION
  500. #define JUCE_CATCH_ALL
  501. #define JUCE_CATCH_ALL_ASSERT
  502. #endif
  503. // Macros for inlining.
  504. #if JUCE_MSVC
  505. /** A platform-independent way of forcing an inline function.
  506. Use the syntax: @code
  507. forcedinline void myfunction (int x)
  508. @endcode
  509. */
  510. #ifndef JUCE_DEBUG
  511. #define forcedinline __forceinline
  512. #else
  513. #define forcedinline inline
  514. #endif
  515. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  516. #else
  517. /** A platform-independent way of forcing an inline function.
  518. Use the syntax: @code
  519. forcedinline void myfunction (int x)
  520. @endcode
  521. */
  522. #ifndef JUCE_DEBUG
  523. #define forcedinline inline __attribute__((always_inline))
  524. #else
  525. #define forcedinline inline
  526. #endif
  527. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  528. #endif
  529. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  530. /*** End of inlined file: juce_PlatformDefs.h ***/
  531. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  532. #if JUCE_MSVC
  533. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  534. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  535. #endif
  536. #pragma warning (push)
  537. #pragma warning (disable: 4514 4245 4100)
  538. #endif
  539. #include <cstdlib>
  540. #include <cstdarg>
  541. #include <climits>
  542. #include <limits>
  543. #include <cmath>
  544. #include <cwchar>
  545. #include <stdexcept>
  546. #include <typeinfo>
  547. #include <cstring>
  548. #include <cstdio>
  549. #include <iostream>
  550. #if JUCE_USE_INTRINSICS
  551. #include <intrin.h>
  552. #endif
  553. #if JUCE_MAC || JUCE_IPHONE
  554. #include <libkern/OSAtomic.h>
  555. #endif
  556. #if JUCE_LINUX
  557. #include <signal.h>
  558. #if __INTEL_COMPILER
  559. #if __ia64__
  560. #include <ia64intrin.h>
  561. #else
  562. #include <ia32intrin.h>
  563. #endif
  564. #endif
  565. #endif
  566. #if JUCE_MSVC && JUCE_DEBUG
  567. #include <crtdbg.h>
  568. #endif
  569. #if JUCE_MSVC
  570. #include <malloc.h>
  571. #pragma warning (pop)
  572. #if ! JUCE_PUBLIC_INCLUDES
  573. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  574. #endif
  575. #endif
  576. // DLL building settings on Win32
  577. #if JUCE_MSVC
  578. #ifdef JUCE_DLL_BUILD
  579. #define JUCE_API __declspec (dllexport)
  580. #pragma warning (disable: 4251)
  581. #elif defined (JUCE_DLL)
  582. #define JUCE_API __declspec (dllimport)
  583. #pragma warning (disable: 4251)
  584. #endif
  585. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  586. #ifdef JUCE_DLL_BUILD
  587. #define JUCE_API __attribute__ ((visibility("default")))
  588. #endif
  589. #endif
  590. #ifndef JUCE_API
  591. /** This macro is added to all juce public class declarations. */
  592. #define JUCE_API
  593. #endif
  594. /** This macro is added to all juce public function declarations. */
  595. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  596. // Now include some basics that are needed by most of the Juce classes...
  597. BEGIN_JUCE_NAMESPACE
  598. extern bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger();
  599. #if JUCE_LOG_ASSERTIONS
  600. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  601. #endif
  602. /*** Start of inlined file: juce_Memory.h ***/
  603. #ifndef __JUCE_MEMORY_JUCEHEADER__
  604. #define __JUCE_MEMORY_JUCEHEADER__
  605. /*
  606. This file defines the various juce_malloc(), juce_free() macros that should be used in
  607. preference to the standard calls.
  608. */
  609. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  610. #ifndef JUCE_DLL
  611. // Win32 debug non-DLL versions..
  612. /** This should be used instead of calling malloc directly.
  613. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  614. */
  615. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  616. /** This should be used instead of calling calloc directly.
  617. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  618. */
  619. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  620. /** This should be used instead of calling realloc directly.
  621. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  622. */
  623. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  624. /** This should be used instead of calling free directly.
  625. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  626. */
  627. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  628. #else
  629. // Win32 debug DLL versions..
  630. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  631. // way all juce calls in the DLL and in the host API will all use the same allocator.
  632. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  633. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  634. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  635. extern JUCE_API void juce_DebugFree (void* const block);
  636. /** This should be used instead of calling malloc directly.
  637. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  638. */
  639. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  640. /** This should be used instead of calling calloc directly.
  641. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  642. */
  643. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  644. /** This should be used instead of calling realloc directly.
  645. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  646. */
  647. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  648. /** This should be used instead of calling free directly.
  649. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  650. */
  651. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  652. #endif
  653. #if ! defined (_AFXDLL)
  654. /** This macro can be added to classes to add extra debugging information to the memory
  655. allocated for them, so you can see the type of objects involved when there's a dump
  656. of leaked objects at program shutdown. (Only works on win32 at the moment).
  657. */
  658. #define juce_UseDebuggingNewOperator \
  659. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  660. static void* operator new (size_t, void* p) { return p; } \
  661. static void operator delete (void* p) { juce_free (p); } \
  662. static void operator delete (void*, void*) { }
  663. #endif
  664. #elif defined (JUCE_DLL)
  665. // Win32 DLL (release) versions..
  666. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  667. // way all juce calls in the DLL and in the host API will all use the same allocator.
  668. extern JUCE_API void* juce_Malloc (const int size);
  669. extern JUCE_API void* juce_Calloc (const int size);
  670. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  671. extern JUCE_API void juce_Free (void* const block);
  672. /** This should be used instead of calling malloc directly.
  673. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  674. */
  675. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  676. /** This should be used instead of calling calloc directly.
  677. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  678. */
  679. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  680. /** This should be used instead of calling realloc directly.
  681. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  682. */
  683. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  684. /** This should be used instead of calling free directly.
  685. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  686. */
  687. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  688. #define juce_UseDebuggingNewOperator \
  689. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  690. static void* operator new (size_t, void* p) { return p; } \
  691. static void operator delete (void* p) { juce_free (p); } \
  692. static void operator delete (void*, void*) { }
  693. #else
  694. // Mac, Linux and Win32 (release) versions..
  695. /** This should be used instead of calling malloc directly.
  696. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  697. */
  698. #define juce_malloc(numBytes) malloc (numBytes)
  699. /** This should be used instead of calling calloc directly.
  700. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  701. */
  702. #define juce_calloc(numBytes) calloc (1, numBytes)
  703. /** This should be used instead of calling realloc directly.
  704. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  705. */
  706. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  707. /** This should be used instead of calling free directly.
  708. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  709. */
  710. #define juce_free(location) free (location)
  711. #endif
  712. /** This macro can be added to classes to add extra debugging information to the memory
  713. allocated for them, so you can see the type of objects involved when there's a dump
  714. of leaked objects at program shutdown. (Only works on win32 at the moment).
  715. Note that if you create a class that inherits from a class that uses this macro,
  716. your class must also use the macro, otherwise you'll probably get compile errors
  717. because of ambiguous new operators.
  718. Most of the JUCE classes use it, so see these for examples of where it should go.
  719. */
  720. #ifndef juce_UseDebuggingNewOperator
  721. #define juce_UseDebuggingNewOperator
  722. #endif
  723. #if JUCE_MSVC
  724. /** This is a compiler-independent way of declaring a variable as being thread-local.
  725. E.g.
  726. @code
  727. juce_ThreadLocal int myVariable;
  728. @endcode
  729. */
  730. #define juce_ThreadLocal __declspec(thread)
  731. #else
  732. #define juce_ThreadLocal __thread
  733. #endif
  734. #if JUCE_MINGW
  735. /** This allocator is not defined in mingw gcc. */
  736. #define alloca __builtin_alloca
  737. #endif
  738. /** Clears a block of memory. */
  739. inline void zeromem (void* memory, size_t numBytes) { memset (memory, 0, numBytes); }
  740. /** Clears a reference to a local structure. */
  741. template <typename Type>
  742. inline void zerostruct (Type& structure) { memset (&structure, 0, sizeof (structure)); }
  743. /** A handy function that calls delete on a pointer if it's non-zero, and then sets
  744. the pointer to null.
  745. */
  746. template <typename Type>
  747. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  748. #endif // __JUCE_MEMORY_JUCEHEADER__
  749. /*** End of inlined file: juce_Memory.h ***/
  750. /*** Start of inlined file: juce_MathsFunctions.h ***/
  751. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  752. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  753. /*
  754. This file sets up some handy mathematical typdefs and functions.
  755. */
  756. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  757. /** A platform-independent 8-bit signed integer type. */
  758. typedef signed char int8;
  759. /** A platform-independent 8-bit unsigned integer type. */
  760. typedef unsigned char uint8;
  761. /** A platform-independent 16-bit signed integer type. */
  762. typedef signed short int16;
  763. /** A platform-independent 16-bit unsigned integer type. */
  764. typedef unsigned short uint16;
  765. /** A platform-independent 32-bit signed integer type. */
  766. typedef signed int int32;
  767. /** A platform-independent 32-bit unsigned integer type. */
  768. typedef unsigned int uint32;
  769. #if JUCE_MSVC
  770. /** A platform-independent 64-bit integer type. */
  771. typedef __int64 int64;
  772. /** A platform-independent 64-bit unsigned integer type. */
  773. typedef unsigned __int64 uint64;
  774. /** A platform-independent macro for writing 64-bit literals, needed because
  775. different compilers have different syntaxes for this.
  776. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  777. GCC, or 0x1000000000 for MSVC.
  778. */
  779. #define literal64bit(longLiteral) ((__int64) longLiteral)
  780. #else
  781. /** A platform-independent 64-bit integer type. */
  782. typedef long long int64;
  783. /** A platform-independent 64-bit unsigned integer type. */
  784. typedef unsigned long long uint64;
  785. /** A platform-independent macro for writing 64-bit literals, needed because
  786. different compilers have different syntaxes for this.
  787. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  788. GCC, or 0x1000000000 for MSVC.
  789. */
  790. #define literal64bit(longLiteral) (longLiteral##LL)
  791. #endif
  792. #if JUCE_64BIT
  793. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  794. typedef int64 pointer_sized_int;
  795. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  796. typedef uint64 pointer_sized_uint;
  797. #elif _MSC_VER >= 1300
  798. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  799. typedef _W64 int pointer_sized_int;
  800. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  801. typedef _W64 unsigned int pointer_sized_uint;
  802. #else
  803. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  804. typedef int pointer_sized_int;
  805. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  806. typedef unsigned int pointer_sized_uint;
  807. #endif
  808. /** A platform-independent unicode character type. */
  809. typedef wchar_t juce_wchar;
  810. // Some indispensible min/max functions
  811. /** Returns the larger of two values. */
  812. template <typename Type>
  813. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  814. /** Returns the larger of three values. */
  815. template <typename Type>
  816. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  817. /** Returns the larger of four values. */
  818. template <typename Type>
  819. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  820. /** Returns the smaller of two values. */
  821. template <typename Type>
  822. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  823. /** Returns the smaller of three values. */
  824. template <typename Type>
  825. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  826. /** Returns the smaller of four values. */
  827. template <typename Type>
  828. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  829. /** Constrains a value to keep it within a given range.
  830. This will check that the specified value lies between the lower and upper bounds
  831. specified, and if not, will return the nearest value that would be in-range. Effectively,
  832. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  833. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  834. the results will be unpredictable.
  835. @param lowerLimit the minimum value to return
  836. @param upperLimit the maximum value to return
  837. @param valueToConstrain the value to try to return
  838. @returns the closest value to valueToConstrain which lies between lowerLimit
  839. and upperLimit (inclusive)
  840. @see jlimit0To, jmin, jmax
  841. */
  842. template <typename Type>
  843. inline Type jlimit (const Type lowerLimit,
  844. const Type upperLimit,
  845. const Type valueToConstrain) throw()
  846. {
  847. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  848. return (valueToConstrain < lowerLimit) ? lowerLimit
  849. : ((upperLimit < valueToConstrain) ? upperLimit
  850. : valueToConstrain);
  851. }
  852. /** Handy function to swap two values over.
  853. */
  854. template <typename Type>
  855. inline void swapVariables (Type& variable1, Type& variable2)
  856. {
  857. const Type tempVal = variable1;
  858. variable1 = variable2;
  859. variable2 = tempVal;
  860. }
  861. /** Handy function for getting the number of elements in a simple const C array.
  862. E.g.
  863. @code
  864. static int myArray[] = { 1, 2, 3 };
  865. int numElements = numElementsInArray (myArray) // returns 3
  866. @endcode
  867. */
  868. template <typename Type>
  869. inline int numElementsInArray (Type& array) { return static_cast<int> (sizeof (array) / sizeof (array[0])); }
  870. // Some useful maths functions that aren't always present with all compilers and build settings.
  871. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  872. versions of these functions of various platforms and compilers. */
  873. inline double juce_hypot (double a, double b)
  874. {
  875. #if JUCE_WINDOWS
  876. return _hypot (a, b);
  877. #else
  878. return hypot (a, b);
  879. #endif
  880. }
  881. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  882. versions of these functions of various platforms and compilers. */
  883. inline float juce_hypotf (float a, float b) throw()
  884. {
  885. #if JUCE_WINDOWS
  886. return (float) _hypot (a, b);
  887. #else
  888. return hypotf (a, b);
  889. #endif
  890. }
  891. /** 64-bit abs function. */
  892. inline int64 abs64 (const int64 n) throw()
  893. {
  894. return (n >= 0) ? n : -n;
  895. }
  896. /** This templated negate function will negate pointers as well as integers */
  897. template <typename Type>
  898. inline Type juce_negate (Type n) throw()
  899. {
  900. return sizeof (Type) == 1 ? (Type) -(char) n
  901. : (sizeof (Type) == 2 ? (Type) -(short) n
  902. : (sizeof (Type) == 4 ? (Type) -(int) n
  903. : ((Type) -(int64) n)));
  904. }
  905. /** This templated negate function will negate pointers as well as integers */
  906. template <typename Type>
  907. inline Type* juce_negate (Type* n) throw()
  908. {
  909. return (Type*) -(pointer_sized_int) n;
  910. }
  911. /** A predefined value for Pi, at double-precision.
  912. @see float_Pi
  913. */
  914. const double double_Pi = 3.1415926535897932384626433832795;
  915. /** A predefined value for Pi, at sngle-precision.
  916. @see double_Pi
  917. */
  918. const float float_Pi = 3.14159265358979323846f;
  919. /** The isfinite() method seems to vary between platforms, so this is a
  920. platform-independent function for it.
  921. */
  922. template <typename FloatingPointType>
  923. inline bool juce_isfinite (FloatingPointType value)
  924. {
  925. #if JUCE_WINDOWS
  926. return _finite (value);
  927. #else
  928. return std::isfinite (value);
  929. #endif
  930. }
  931. /** Fast floating-point-to-integer conversion.
  932. This is faster than using the normal c++ cast to convert a float to an int, and
  933. it will round the value to the nearest integer, rather than rounding it down
  934. like the normal cast does.
  935. Note that this routine gets its speed at the expense of some accuracy, and when
  936. rounding values whose floating point component is exactly 0.5, odd numbers and
  937. even numbers will be rounded up or down differently.
  938. */
  939. template <typename FloatType>
  940. inline int roundToInt (const FloatType value) throw()
  941. {
  942. union { int asInt[2]; double asDouble; } n;
  943. n.asDouble = ((double) value) + 6755399441055744.0;
  944. #if JUCE_BIG_ENDIAN
  945. return n.asInt [1];
  946. #else
  947. return n.asInt [0];
  948. #endif
  949. }
  950. /** Fast floating-point-to-integer conversion.
  951. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  952. fine for values above zero, but negative numbers are rounded the wrong way.
  953. */
  954. inline int roundToIntAccurate (const double value) throw()
  955. {
  956. return roundToInt (value + 1.5e-8);
  957. }
  958. /** Fast floating-point-to-integer conversion.
  959. This is faster than using the normal c++ cast to convert a double to an int, and
  960. it will round the value to the nearest integer, rather than rounding it down
  961. like the normal cast does.
  962. Note that this routine gets its speed at the expense of some accuracy, and when
  963. rounding values whose floating point component is exactly 0.5, odd numbers and
  964. even numbers will be rounded up or down differently. For a more accurate conversion,
  965. see roundDoubleToIntAccurate().
  966. */
  967. inline int roundDoubleToInt (const double value) throw()
  968. {
  969. return roundToInt (value);
  970. }
  971. /** Fast floating-point-to-integer conversion.
  972. This is faster than using the normal c++ cast to convert a float to an int, and
  973. it will round the value to the nearest integer, rather than rounding it down
  974. like the normal cast does.
  975. Note that this routine gets its speed at the expense of some accuracy, and when
  976. rounding values whose floating point component is exactly 0.5, odd numbers and
  977. even numbers will be rounded up or down differently.
  978. */
  979. inline int roundFloatToInt (const float value) throw()
  980. {
  981. return roundToInt (value);
  982. }
  983. /** This namespace contains a few template classes for helping work out class type variations.
  984. */
  985. namespace TypeHelpers
  986. {
  987. /** The ParameterType struct is used to find the best type to use when passing some kind
  988. of object as a parameter.
  989. Of course, this is only likely to be useful in certain esoteric template situations.
  990. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  991. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  992. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  993. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  994. pass-by-value, but passing objects as a const reference, to avoid copying.
  995. */
  996. #if defined (_MSC_VER) && _MSC_VER <= 1400
  997. #define PARAMETER_TYPE(a) a
  998. #else
  999. template <typename Type> struct ParameterType { typedef const Type& type; };
  1000. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1001. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1002. template <> struct ParameterType <char> { typedef char type; };
  1003. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1004. template <> struct ParameterType <short> { typedef short type; };
  1005. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1006. template <> struct ParameterType <int> { typedef int type; };
  1007. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1008. template <> struct ParameterType <long> { typedef long type; };
  1009. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1010. template <> struct ParameterType <int64> { typedef int64 type; };
  1011. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1012. template <> struct ParameterType <bool> { typedef bool type; };
  1013. template <> struct ParameterType <float> { typedef float type; };
  1014. template <> struct ParameterType <double> { typedef double type; };
  1015. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1016. #endif
  1017. }
  1018. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1019. /*** End of inlined file: juce_MathsFunctions.h ***/
  1020. /*** Start of inlined file: juce_ByteOrder.h ***/
  1021. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1022. #define __JUCE_BYTEORDER_JUCEHEADER__
  1023. /** Contains static methods for converting the byte order between different
  1024. endiannesses.
  1025. */
  1026. class JUCE_API ByteOrder
  1027. {
  1028. public:
  1029. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1030. static uint16 swap (uint16 value);
  1031. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1032. static uint32 swap (uint32 value);
  1033. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1034. static uint64 swap (uint64 value);
  1035. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1036. static uint16 swapIfBigEndian (uint16 value);
  1037. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1038. static uint32 swapIfBigEndian (uint32 value);
  1039. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1040. static uint64 swapIfBigEndian (uint64 value);
  1041. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1042. static uint16 swapIfLittleEndian (uint16 value);
  1043. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1044. static uint32 swapIfLittleEndian (uint32 value);
  1045. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1046. static uint64 swapIfLittleEndian (uint64 value);
  1047. /** Turns 4 bytes into a little-endian integer. */
  1048. static uint32 littleEndianInt (const void* bytes);
  1049. /** Turns 2 bytes into a little-endian integer. */
  1050. static uint16 littleEndianShort (const void* bytes);
  1051. /** Turns 4 bytes into a big-endian integer. */
  1052. static uint32 bigEndianInt (const void* bytes);
  1053. /** Turns 2 bytes into a big-endian integer. */
  1054. static uint16 bigEndianShort (const void* bytes);
  1055. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1056. static int littleEndian24Bit (const char* bytes);
  1057. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1058. static int bigEndian24Bit (const char* bytes);
  1059. /** Copies a 24-bit number to 3 little-endian bytes. */
  1060. static void littleEndian24BitToChars (int value, char* destBytes);
  1061. /** Copies a 24-bit number to 3 big-endian bytes. */
  1062. static void bigEndian24BitToChars (int value, char* destBytes);
  1063. /** Returns true if the current CPU is big-endian. */
  1064. static bool isBigEndian();
  1065. private:
  1066. ByteOrder();
  1067. ByteOrder (const ByteOrder&);
  1068. ByteOrder& operator= (const ByteOrder&);
  1069. };
  1070. #if JUCE_USE_INTRINSICS
  1071. #pragma intrinsic (_byteswap_ulong)
  1072. #endif
  1073. inline uint16 ByteOrder::swap (uint16 n)
  1074. {
  1075. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1076. return static_cast <uint16> (_byteswap_ushort (n));
  1077. #else
  1078. return static_cast <uint16> ((n << 8) | (n >> 8));
  1079. #endif
  1080. }
  1081. inline uint32 ByteOrder::swap (uint32 n)
  1082. {
  1083. #if JUCE_MAC || JUCE_IPHONE
  1084. return OSSwapInt32 (n);
  1085. #elif JUCE_GCC
  1086. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1087. return n;
  1088. #elif JUCE_USE_INTRINSICS
  1089. return _byteswap_ulong (n);
  1090. #else
  1091. __asm {
  1092. mov eax, n
  1093. bswap eax
  1094. mov n, eax
  1095. }
  1096. return n;
  1097. #endif
  1098. }
  1099. inline uint64 ByteOrder::swap (uint64 value)
  1100. {
  1101. #if JUCE_MAC || JUCE_IPHONE
  1102. return OSSwapInt64 (value);
  1103. #elif JUCE_USE_INTRINSICS
  1104. return _byteswap_uint64 (value);
  1105. #else
  1106. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1107. #endif
  1108. }
  1109. #if JUCE_LITTLE_ENDIAN
  1110. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1111. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1112. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1113. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1114. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1115. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1116. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1117. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1118. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1119. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1120. inline bool ByteOrder::isBigEndian() { return false; }
  1121. #else
  1122. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1123. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1124. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1125. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1126. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1127. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1128. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1129. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1130. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1131. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1132. inline bool ByteOrder::isBigEndian() { return true; }
  1133. #endif
  1134. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1135. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1136. 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); }
  1137. 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); }
  1138. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1139. /*** End of inlined file: juce_ByteOrder.h ***/
  1140. /*** Start of inlined file: juce_Logger.h ***/
  1141. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1142. #define __JUCE_LOGGER_JUCEHEADER__
  1143. /*** Start of inlined file: juce_String.h ***/
  1144. #ifndef __JUCE_STRING_JUCEHEADER__
  1145. #define __JUCE_STRING_JUCEHEADER__
  1146. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1147. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1148. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1149. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1150. typedef juce_wchar tchar;
  1151. #if ! JUCE_DONT_DEFINE_MACROS
  1152. /** The 'T' macro allows a literal string to be compiled as unicode.
  1153. If you write your string literals in the form T("xyz"), it will be compiled as L"xyz"
  1154. or "xyz", depending on which representation is best for the String class to work with.
  1155. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1156. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1157. the juce/src directory) to avoid defining this macro. See the comments in
  1158. juce_withoutMacros.h for more info.
  1159. */
  1160. #define T(stringLiteral) JUCE_T(stringLiteral)
  1161. #endif
  1162. /**
  1163. A set of methods for manipulating characters and character strings, with
  1164. duplicate methods to handle 8-bit and unicode characters.
  1165. These are defined as wrappers around the basic C string handlers, to provide
  1166. a clean, cross-platform layer, (because various platforms differ in the
  1167. range of C library calls that they provide).
  1168. @see String
  1169. */
  1170. class JUCE_API CharacterFunctions
  1171. {
  1172. public:
  1173. static int length (const char* const s) throw();
  1174. static int length (const juce_wchar* const s) throw();
  1175. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1176. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1177. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1178. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1179. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1180. static void append (char* dest, const char* src) throw();
  1181. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1182. static int compare (const char* const s1, const char* const s2) throw();
  1183. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1184. static int compare (const juce_wchar* s1, const char* s2) throw();
  1185. static int compare (const char* s1, const juce_wchar* s2) throw();
  1186. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1187. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1188. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1189. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1190. static int compareIgnoreCase (const juce_wchar* s1, const char* s2) throw();
  1191. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1192. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1193. static const char* find (const char* const haystack, const char* const needle) throw();
  1194. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1195. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1196. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1197. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1198. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1199. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1200. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1201. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1202. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1203. static int getIntValue (const char* const s) throw();
  1204. static int getIntValue (const juce_wchar* s) throw();
  1205. static int64 getInt64Value (const char* s) throw();
  1206. static int64 getInt64Value (const juce_wchar* s) throw();
  1207. static double getDoubleValue (const char* const s) throw();
  1208. static double getDoubleValue (const juce_wchar* const s) throw();
  1209. static char toUpperCase (const char character) throw();
  1210. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1211. static void toUpperCase (char* s) throw();
  1212. static void toUpperCase (juce_wchar* s) throw();
  1213. static bool isUpperCase (const char character) throw();
  1214. static bool isUpperCase (const juce_wchar character) throw();
  1215. static char toLowerCase (const char character) throw();
  1216. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1217. static void toLowerCase (char* s) throw();
  1218. static void toLowerCase (juce_wchar* s) throw();
  1219. static bool isLowerCase (const char character) throw();
  1220. static bool isLowerCase (const juce_wchar character) throw();
  1221. static bool isWhitespace (const char character) throw();
  1222. static bool isWhitespace (const juce_wchar character) throw();
  1223. static bool isDigit (const char character) throw();
  1224. static bool isDigit (const juce_wchar character) throw();
  1225. static bool isLetter (const char character) throw();
  1226. static bool isLetter (const juce_wchar character) throw();
  1227. static bool isLetterOrDigit (const char character) throw();
  1228. static bool isLetterOrDigit (const juce_wchar character) throw();
  1229. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1230. hex digit.
  1231. */
  1232. static int getHexDigitValue (const juce_wchar digit) throw();
  1233. };
  1234. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1235. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1236. class OutputStream;
  1237. /**
  1238. The JUCE String class!
  1239. Using a reference-counted internal representation, these strings are fast
  1240. and efficient, and there are methods to do just about any operation you'll ever
  1241. dream of.
  1242. @see StringArray, StringPairArray
  1243. */
  1244. class JUCE_API String
  1245. {
  1246. public:
  1247. /** Creates an empty string.
  1248. @see empty
  1249. */
  1250. String() throw();
  1251. /** Creates a copy of another string. */
  1252. String (const String& other) throw();
  1253. /** Creates a string from a zero-terminated text string.
  1254. The string is assumed to be stored in the default system encoding.
  1255. */
  1256. String (const char* text);
  1257. /** Creates a string from an string of characters.
  1258. This will use up the the first maxChars characters of the string (or
  1259. less if the string is actually shorter)
  1260. */
  1261. String (const char* text, size_t maxChars);
  1262. /** Creates a string from a zero-terminated unicode text string. */
  1263. String (const juce_wchar* unicodeText);
  1264. /** Creates a string from a unicode text string.
  1265. This will use up the the first maxChars characters of the string (or
  1266. less if the string is actually shorter)
  1267. */
  1268. String (const juce_wchar* unicodeText, size_t maxChars);
  1269. /** Creates a string from a single character. */
  1270. static const String charToString (juce_wchar character);
  1271. /** Destructor. */
  1272. ~String() throw();
  1273. /** This is an empty string that can be used whenever one is needed.
  1274. It's better to use this than String() because it explains what's going on
  1275. and is more efficient.
  1276. */
  1277. static const String empty;
  1278. /** Generates a probably-unique 32-bit hashcode from this string. */
  1279. int hashCode() const throw();
  1280. /** Generates a probably-unique 64-bit hashcode from this string. */
  1281. int64 hashCode64() const throw();
  1282. /** Returns the number of characters in the string. */
  1283. int length() const throw();
  1284. // Assignment and concatenation operators..
  1285. /** Replaces this string's contents with another string. */
  1286. String& operator= (const String& other) throw();
  1287. /** Appends another string at the end of this one. */
  1288. String& operator+= (const juce_wchar* textToAppend);
  1289. /** Appends another string at the end of this one. */
  1290. String& operator+= (const String& stringToAppend);
  1291. /** Appends a character at the end of this string. */
  1292. String& operator+= (char characterToAppend);
  1293. /** Appends a character at the end of this string. */
  1294. String& operator+= (juce_wchar characterToAppend);
  1295. /** Appends a decimal number at the end of this string. */
  1296. String& operator+= (int numberToAppend);
  1297. /** Appends a decimal number at the end of this string. */
  1298. String& operator+= (unsigned int numberToAppend);
  1299. /** Appends a string at the end of this one.
  1300. @param textToAppend the string to add
  1301. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1302. */
  1303. void append (const juce_wchar* textToAppend, int maxCharsToTake);
  1304. // Comparison methods..
  1305. /** Returns true if the string contains no characters.
  1306. Note that there's also an isNotEmpty() method to help write readable code.
  1307. @see containsNonWhitespaceChars()
  1308. */
  1309. inline bool isEmpty() const throw() { return text[0] == 0; }
  1310. /** Returns true if the string contains at least one character.
  1311. Note that there's also an isEmpty() method to help write readable code.
  1312. @see containsNonWhitespaceChars()
  1313. */
  1314. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  1315. /** Case-insensitive comparison with another string. */
  1316. bool equalsIgnoreCase (const String& other) const throw();
  1317. /** Case-insensitive comparison with another string. */
  1318. bool equalsIgnoreCase (const juce_wchar* other) const throw();
  1319. /** Case-insensitive comparison with another string. */
  1320. bool equalsIgnoreCase (const char* other) const throw();
  1321. /** Case-sensitive comparison with another string.
  1322. @returns 0 if the two strings are identical; negative if this string
  1323. comes before the other one alphabetically, or positive if it
  1324. comes after it.
  1325. */
  1326. int compare (const String& other) const throw();
  1327. /** Case-sensitive comparison with another string.
  1328. @returns 0 if the two strings are identical; negative if this string
  1329. comes before the other one alphabetically, or positive if it
  1330. comes after it.
  1331. */
  1332. int compare (const char* other) const throw();
  1333. /** Case-sensitive comparison with another string.
  1334. @returns 0 if the two strings are identical; negative if this string
  1335. comes before the other one alphabetically, or positive if it
  1336. comes after it.
  1337. */
  1338. int compare (const juce_wchar* other) const throw();
  1339. /** Case-insensitive comparison with another string.
  1340. @returns 0 if the two strings are identical; negative if this string
  1341. comes before the other one alphabetically, or positive if it
  1342. comes after it.
  1343. */
  1344. int compareIgnoreCase (const String& other) const throw();
  1345. /** Lexicographic comparison with another string.
  1346. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1347. characters, making it good for sorting human-readable strings.
  1348. @returns 0 if the two strings are identical; negative if this string
  1349. comes before the other one alphabetically, or positive if it
  1350. comes after it.
  1351. */
  1352. int compareLexicographically (const String& other) const throw();
  1353. /** Tests whether the string begins with another string.
  1354. Uses a case-sensitive comparison.
  1355. */
  1356. bool startsWith (const String& text) const throw();
  1357. /** Tests whether the string begins with a particular character.
  1358. Uses a case-sensitive comparison.
  1359. */
  1360. bool startsWithChar (juce_wchar character) const throw();
  1361. /** Tests whether the string begins with another string.
  1362. Uses a case-insensitive comparison.
  1363. */
  1364. bool startsWithIgnoreCase (const String& text) const throw();
  1365. /** Tests whether the string ends with another string.
  1366. Uses a case-sensitive comparison.
  1367. */
  1368. bool endsWith (const String& text) const throw();
  1369. /** Tests whether the string ends with a particular character.
  1370. Uses a case-sensitive comparison.
  1371. */
  1372. bool endsWithChar (juce_wchar character) const throw();
  1373. /** Tests whether the string ends with another string.
  1374. Uses a case-insensitive comparison.
  1375. */
  1376. bool endsWithIgnoreCase (const String& text) const throw();
  1377. /** Tests whether the string contains another substring.
  1378. Uses a case-sensitive comparison.
  1379. */
  1380. bool contains (const String& text) const throw();
  1381. /** Tests whether the string contains a particular character.
  1382. Uses a case-sensitive comparison.
  1383. */
  1384. bool containsChar (juce_wchar character) const throw();
  1385. /** Tests whether the string contains another substring.
  1386. Uses a case-insensitive comparison.
  1387. */
  1388. bool containsIgnoreCase (const String& text) const throw();
  1389. /** Tests whether the string contains another substring as a distict word.
  1390. @returns true if the string contains this word, surrounded by
  1391. non-alphanumeric characters
  1392. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1393. */
  1394. bool containsWholeWord (const String& wordToLookFor) const throw();
  1395. /** Tests whether the string contains another substring as a distict word.
  1396. @returns true if the string contains this word, surrounded by
  1397. non-alphanumeric characters
  1398. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1399. */
  1400. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1401. /** Finds an instance of another substring if it exists as a distict word.
  1402. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1403. then this will return the index of the start of the substring. If it isn't
  1404. found, then it will return -1
  1405. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1406. */
  1407. int indexOfWholeWord (const String& wordToLookFor) const throw();
  1408. /** Finds an instance of another substring if it exists as a distict word.
  1409. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1410. then this will return the index of the start of the substring. If it isn't
  1411. found, then it will return -1
  1412. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1413. */
  1414. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1415. /** Looks for any of a set of characters in the string.
  1416. Uses a case-sensitive comparison.
  1417. @returns true if the string contains any of the characters from
  1418. the string that is passed in.
  1419. */
  1420. bool containsAnyOf (const String& charactersItMightContain) const throw();
  1421. /** Looks for a set of characters in the string.
  1422. Uses a case-sensitive comparison.
  1423. @returns true if the all the characters in the string are also found in the
  1424. string that is passed in.
  1425. */
  1426. bool containsOnly (const String& charactersItMightContain) const throw();
  1427. /** Returns true if this string contains any non-whitespace characters.
  1428. This will return false if the string contains only whitespace characters, or
  1429. if it's empty.
  1430. It is equivalent to calling "myString.trim().isNotEmpty()".
  1431. */
  1432. bool containsNonWhitespaceChars() const throw();
  1433. /** Returns true if the string matches this simple wildcard expression.
  1434. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1435. This isn't a full-blown regex though! The only wildcard characters supported
  1436. are "*" and "?". It's mainly intended for filename pattern matching.
  1437. */
  1438. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  1439. // Substring location methods..
  1440. /** Searches for a character inside this string.
  1441. Uses a case-sensitive comparison.
  1442. @returns the index of the first occurrence of the character in this
  1443. string, or -1 if it's not found.
  1444. */
  1445. int indexOfChar (juce_wchar characterToLookFor) const throw();
  1446. /** Searches for a character inside this string.
  1447. Uses a case-sensitive comparison.
  1448. @param startIndex the index from which the search should proceed
  1449. @param characterToLookFor the character to look for
  1450. @returns the index of the first occurrence of the character in this
  1451. string, or -1 if it's not found.
  1452. */
  1453. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  1454. /** Returns the index of the first character that matches one of the characters
  1455. passed-in to this method.
  1456. This scans the string, beginning from the startIndex supplied, and if it finds
  1457. a character that appears in the string charactersToLookFor, it returns its index.
  1458. If none of these characters are found, it returns -1.
  1459. If ignoreCase is true, the comparison will be case-insensitive.
  1460. @see indexOfChar, lastIndexOfAnyOf
  1461. */
  1462. int indexOfAnyOf (const String& charactersToLookFor,
  1463. int startIndex = 0,
  1464. bool ignoreCase = false) const throw();
  1465. /** Searches for a substring within this string.
  1466. Uses a case-sensitive comparison.
  1467. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1468. */
  1469. int indexOf (const String& text) const throw();
  1470. /** Searches for a substring within this string.
  1471. Uses a case-sensitive comparison.
  1472. @param startIndex the index from which the search should proceed
  1473. @param textToLookFor the string to search for
  1474. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1475. */
  1476. int indexOf (int startIndex,
  1477. const String& textToLookFor) const throw();
  1478. /** Searches for a substring within this string.
  1479. Uses a case-insensitive comparison.
  1480. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1481. */
  1482. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  1483. /** Searches for a substring within this string.
  1484. Uses a case-insensitive 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 indexOfIgnoreCase (int startIndex,
  1490. const String& textToLookFor) const throw();
  1491. /** Searches for a character inside this string (working backwards from the end of the string).
  1492. Uses a case-sensitive comparison.
  1493. @returns the index of the last occurrence of the character in this
  1494. string, or -1 if it's not found.
  1495. */
  1496. int lastIndexOfChar (juce_wchar character) const throw();
  1497. /** Searches for a substring inside this string (working backwards from the end of the string).
  1498. Uses a case-sensitive comparison.
  1499. @returns the index of the start of the last occurrence of the
  1500. substring within this string, or -1 if it's not found.
  1501. */
  1502. int lastIndexOf (const String& textToLookFor) const throw();
  1503. /** Searches for a substring inside this string (working backwards from the end of the string).
  1504. Uses a case-insensitive comparison.
  1505. @returns the index of the start of the last occurrence of the
  1506. substring within this string, or -1 if it's not found.
  1507. */
  1508. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  1509. /** Returns the index of the last character in this string that matches one of the
  1510. characters passed-in to this method.
  1511. This scans the string backwards, starting from its end, and if it finds
  1512. a character that appears in the string charactersToLookFor, it returns its index.
  1513. If none of these characters are found, it returns -1.
  1514. If ignoreCase is true, the comparison will be case-insensitive.
  1515. @see lastIndexOf, indexOfAnyOf
  1516. */
  1517. int lastIndexOfAnyOf (const String& charactersToLookFor,
  1518. bool ignoreCase = false) const throw();
  1519. // Substring extraction and manipulation methods..
  1520. /** Returns the character at this index in the string.
  1521. No checks are made to see if the index is within a valid range, so be careful!
  1522. */
  1523. inline const juce_wchar& operator[] (int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text [index]; }
  1524. /** Returns a character from the string such that it can also be altered.
  1525. This can be used as a way of easily changing characters in the string.
  1526. Note that the index passed-in is not checked to see whether it's in-range, so
  1527. be careful when using this.
  1528. */
  1529. juce_wchar& operator[] (int index);
  1530. /** Returns the final character of the string.
  1531. If the string is empty this will return 0.
  1532. */
  1533. juce_wchar getLastCharacter() const throw();
  1534. /** Returns a subsection of the string.
  1535. If the range specified is beyond the limits of the string, as much as
  1536. possible is returned.
  1537. @param startIndex the index of the start of the substring needed
  1538. @param endIndex all characters from startIndex up to (but not including)
  1539. this index are returned
  1540. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1541. */
  1542. const String substring (int startIndex, int endIndex) const;
  1543. /** Returns a section of the string, starting from a given position.
  1544. @param startIndex the first character to include. If this is beyond the end
  1545. of the string, an empty string is returned. If it is zero or
  1546. less, the whole string is returned.
  1547. @returns the substring from startIndex up to the end of the string
  1548. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1549. */
  1550. const String substring (int startIndex) const;
  1551. /** Returns a version of this string with a number of characters removed
  1552. from the end.
  1553. @param numberToDrop the number of characters to drop from the end of the
  1554. string. If this is greater than the length of the string,
  1555. an empty string will be returned. If zero or less, the
  1556. original string will be returned.
  1557. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1558. */
  1559. const String dropLastCharacters (int numberToDrop) const;
  1560. /** Returns a number of characters from the end of the string.
  1561. This returns the last numCharacters characters from the end of the string. If the
  1562. string is shorter than numCharacters, the whole string is returned.
  1563. @see substring, dropLastCharacters, getLastCharacter
  1564. */
  1565. const String getLastCharacters (int numCharacters) const;
  1566. /** Returns a section of the string starting from a given substring.
  1567. This will search for the first occurrence of the given substring, and
  1568. return the section of the string starting from the point where this is
  1569. found (optionally not including the substring itself).
  1570. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1571. fromFirstOccurrenceOf ("34", false) would return "56".
  1572. If the substring isn't found, the method will return an empty string.
  1573. If ignoreCase is true, the comparison will be case-insensitive.
  1574. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1575. */
  1576. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  1577. bool includeSubStringInResult,
  1578. bool ignoreCase) const;
  1579. /** Returns a section of the string starting from the last occurrence of a given substring.
  1580. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1581. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1582. return the whole of the original string.
  1583. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1584. */
  1585. const String fromLastOccurrenceOf (const String& substringToFind,
  1586. bool includeSubStringInResult,
  1587. bool ignoreCase) const;
  1588. /** Returns the start of this string, up to the first occurrence of a substring.
  1589. This will search for the first occurrence of a given substring, and then
  1590. return a copy of the string, up to the position of this substring,
  1591. optionally including or excluding the substring itself in the result.
  1592. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1593. upTo ("34", true) would return "1234".
  1594. If the substring isn't found, this will return the whole of the original string.
  1595. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1596. */
  1597. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  1598. bool includeSubStringInResult,
  1599. bool ignoreCase) const;
  1600. /** Returns the start of this string, up to the last occurrence of a substring.
  1601. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1602. If the substring isn't found, this will return an empty string.
  1603. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1604. */
  1605. const String upToLastOccurrenceOf (const String& substringToFind,
  1606. bool includeSubStringInResult,
  1607. bool ignoreCase) const;
  1608. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1609. const String trim() const;
  1610. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1611. const String trimStart() const;
  1612. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1613. const String trimEnd() const;
  1614. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1615. Characters are removed from the start of the string until it finds one that is not in the
  1616. specified set, and then it stops.
  1617. @param charactersToTrim the set of characters to remove.
  1618. @see trim, trimStart, trimCharactersAtEnd
  1619. */
  1620. const String trimCharactersAtStart (const String& charactersToTrim) const;
  1621. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1622. Characters are removed from the end of the string until it finds one that is not in the
  1623. specified set, and then it stops.
  1624. @param charactersToTrim the set of characters to remove.
  1625. @see trim, trimEnd, trimCharactersAtStart
  1626. */
  1627. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  1628. /** Returns an upper-case version of this string. */
  1629. const String toUpperCase() const;
  1630. /** Returns an lower-case version of this string. */
  1631. const String toLowerCase() const;
  1632. /** Replaces a sub-section of the string with another string.
  1633. This will return a copy of this string, with a set of characters
  1634. from startIndex to startIndex + numCharsToReplace removed, and with
  1635. a new string inserted in their place.
  1636. Note that this is a const method, and won't alter the string itself.
  1637. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1638. it will be constrained to a valid range.
  1639. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1640. characters will be taken out.
  1641. @param stringToInsert the new string to insert at startIndex after the characters have been
  1642. removed.
  1643. */
  1644. const String replaceSection (int startIndex,
  1645. int numCharactersToReplace,
  1646. const String& stringToInsert) const;
  1647. /** Replaces all occurrences of a substring with another string.
  1648. Returns a copy of this string, with any occurrences of stringToReplace
  1649. swapped for stringToInsertInstead.
  1650. Note that this is a const method, and won't alter the string itself.
  1651. */
  1652. const String replace (const String& stringToReplace,
  1653. const String& stringToInsertInstead,
  1654. bool ignoreCase = false) const;
  1655. /** Returns a string with all occurrences of a character replaced with a different one. */
  1656. const String replaceCharacter (juce_wchar characterToReplace,
  1657. juce_wchar characterToInsertInstead) const;
  1658. /** Replaces a set of characters with another set.
  1659. Returns a string in which each character from charactersToReplace has been replaced
  1660. by the character at the equivalent position in newCharacters (so the two strings
  1661. passed in must be the same length).
  1662. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1663. Note that this is a const method, and won't affect the string itself.
  1664. */
  1665. const String replaceCharacters (const String& charactersToReplace,
  1666. const String& charactersToInsertInstead) const;
  1667. /** Returns a version of this string that only retains a fixed set of characters.
  1668. This will return a copy of this string, omitting any characters which are not
  1669. found in the string passed-in.
  1670. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1671. Note that this is a const method, and won't alter the string itself.
  1672. */
  1673. const String retainCharacters (const String& charactersToRetain) const;
  1674. /** Returns a version of this string with a set of characters removed.
  1675. This will return a copy of this string, omitting any characters which are
  1676. found in the string passed-in.
  1677. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1678. Note that this is a const method, and won't alter the string itself.
  1679. */
  1680. const String removeCharacters (const String& charactersToRemove) const;
  1681. /** Returns a section from the start of the string that only contains a certain set of characters.
  1682. This returns the leftmost section of the string, up to (and not including) the
  1683. first character that doesn't appear in the string passed in.
  1684. */
  1685. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  1686. /** Returns a section from the start of the string that only contains a certain set of characters.
  1687. This returns the leftmost section of the string, up to (and not including) the
  1688. first character that occurs in the string passed in.
  1689. */
  1690. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  1691. /** Checks whether the string might be in quotation marks.
  1692. @returns true if the string begins with a quote character (either a double or single quote).
  1693. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1694. @see unquoted, quoted
  1695. */
  1696. bool isQuotedString() const;
  1697. /** Removes quotation marks from around the string, (if there are any).
  1698. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1699. at the ends of the string are not affected. If there aren't any quotes, the original string
  1700. is returned.
  1701. Note that this is a const method, and won't alter the string itself.
  1702. @see isQuotedString, quoted
  1703. */
  1704. const String unquoted() const;
  1705. /** Adds quotation marks around a string.
  1706. This will return a copy of the string with a quote at the start and end, (but won't
  1707. add the quote if there's already one there, so it's safe to call this on strings that
  1708. may already have quotes around them).
  1709. Note that this is a const method, and won't alter the string itself.
  1710. @param quoteCharacter the character to add at the start and end
  1711. @see isQuotedString, unquoted
  1712. */
  1713. const String quoted (juce_wchar quoteCharacter = '"') const;
  1714. /** Creates a string which is a version of a string repeated and joined together.
  1715. @param stringToRepeat the string to repeat
  1716. @param numberOfTimesToRepeat how many times to repeat it
  1717. */
  1718. static const String repeatedString (const String& stringToRepeat,
  1719. int numberOfTimesToRepeat);
  1720. /** Returns a copy of this string with the specified character repeatedly added to its
  1721. beginning until the total length is at least the minimum length specified.
  1722. */
  1723. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  1724. /** Returns a copy of this string with the specified character repeatedly added to its
  1725. end until the total length is at least the minimum length specified.
  1726. */
  1727. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  1728. /** Creates a string from data in an unknown format.
  1729. This looks at some binary data and tries to guess whether it's Unicode
  1730. or 8-bit characters, then returns a string that represents it correctly.
  1731. Should be able to handle Unicode endianness correctly, by looking at
  1732. the first two bytes.
  1733. */
  1734. static const String createStringFromData (const void* data, int size);
  1735. /** Creates a String from a printf-style parameter list.
  1736. I don't like this method. I don't use it myself, and I recommend avoiding it and
  1737. using the operator<< methods or pretty much anything else instead. It's only provided
  1738. here because of the popular unrest that was stirred-up when I tried to remove it...
  1739. If you're really determined to use it, at least make sure that you never, ever,
  1740. pass any String objects to it as parameters.
  1741. */
  1742. static const String formatted (const juce_wchar* formatString, ... );
  1743. // Numeric conversions..
  1744. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1745. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1746. */
  1747. explicit String (int decimalInteger);
  1748. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1749. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1750. */
  1751. explicit String (unsigned int decimalInteger);
  1752. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1753. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1754. */
  1755. explicit String (short decimalInteger);
  1756. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1757. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1758. */
  1759. explicit String (unsigned short decimalInteger);
  1760. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1761. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1762. */
  1763. explicit String (int64 largeIntegerValue);
  1764. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1765. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1766. */
  1767. explicit String (uint64 largeIntegerValue);
  1768. /** Creates a string representing this floating-point number.
  1769. @param floatValue the value to convert to a string
  1770. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1771. decimal places, and will not use exponent notation. If 0 or
  1772. less, it will use exponent notation if necessary.
  1773. @see getDoubleValue, getIntValue
  1774. */
  1775. explicit String (float floatValue,
  1776. int numberOfDecimalPlaces = 0);
  1777. /** Creates a string representing this floating-point number.
  1778. @param doubleValue the value to convert to a string
  1779. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1780. decimal places, and will not use exponent notation. If 0 or
  1781. less, it will use exponent notation if necessary.
  1782. @see getFloatValue, getIntValue
  1783. */
  1784. explicit String (double doubleValue,
  1785. int numberOfDecimalPlaces = 0);
  1786. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1787. @returns the value of the string as a 32 bit signed base-10 integer.
  1788. @see getTrailingIntValue, getHexValue32, getHexValue64
  1789. */
  1790. int getIntValue() const throw();
  1791. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1792. @returns the value of the string as a 64 bit signed base-10 integer.
  1793. */
  1794. int64 getLargeIntValue() const throw();
  1795. /** Parses a decimal number from the end of the string.
  1796. This will look for a value at the end of the string.
  1797. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1798. Negative numbers are not handled, so "xyz-5" returns 5.
  1799. @see getIntValue
  1800. */
  1801. int getTrailingIntValue() const throw();
  1802. /** Parses this string as a floating point number.
  1803. @returns the value of the string as a 32-bit floating point value.
  1804. @see getDoubleValue
  1805. */
  1806. float getFloatValue() const throw();
  1807. /** Parses this string as a floating point number.
  1808. @returns the value of the string as a 64-bit floating point value.
  1809. @see getFloatValue
  1810. */
  1811. double getDoubleValue() const throw();
  1812. /** Parses the string as a hexadecimal number.
  1813. Non-hexadecimal characters in the string are ignored.
  1814. If the string contains too many characters, then the lowest significant
  1815. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1816. @returns a 32-bit number which is the value of the string in hex.
  1817. */
  1818. int getHexValue32() const throw();
  1819. /** Parses the string as a hexadecimal number.
  1820. Non-hexadecimal characters in the string are ignored.
  1821. If the string contains too many characters, then the lowest significant
  1822. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1823. @returns a 64-bit number which is the value of the string in hex.
  1824. */
  1825. int64 getHexValue64() const throw();
  1826. /** Creates a string representing this 32-bit value in hexadecimal. */
  1827. static const String toHexString (int number);
  1828. /** Creates a string representing this 64-bit value in hexadecimal. */
  1829. static const String toHexString (int64 number);
  1830. /** Creates a string representing this 16-bit value in hexadecimal. */
  1831. static const String toHexString (short number);
  1832. /** Creates a string containing a hex dump of a block of binary data.
  1833. @param data the binary data to use as input
  1834. @param size how many bytes of data to use
  1835. @param groupSize how many bytes are grouped together before inserting a
  1836. space into the output. e.g. group size 0 has no spaces,
  1837. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1838. like "bea1 c2ff".
  1839. */
  1840. static const String toHexString (const unsigned char* data,
  1841. int size,
  1842. int groupSize = 1);
  1843. /** Returns a unicode version of this string.
  1844. Because it returns a reference to the string's internal data, the pointer
  1845. that is returned must not be stored anywhere, as it can become invalid whenever
  1846. any string methods (even some const ones!) are called.
  1847. */
  1848. inline operator const juce_wchar*() const throw() { return text; }
  1849. /** Returns a unicode version of this string.
  1850. Because it returns a reference to the string's internal data, the pointer
  1851. that is returned must not be stored anywhere, as it can become invalid whenever
  1852. any string methods (even some const ones!) are called.
  1853. */
  1854. inline operator juce_wchar*() throw() { return text; }
  1855. /** Returns a pointer to a UTF-8 version of this string.
  1856. Because it returns a reference to the string's internal data, the pointer
  1857. that is returned must not be stored anywhere, as it can be deleted whenever the
  1858. string changes.
  1859. @see getNumBytesAsUTF8, fromUTF8, copyToUTF8, toCString
  1860. */
  1861. const char* toUTF8() const;
  1862. /** Creates a String from a UTF-8 encoded buffer.
  1863. If the size is < 0, it'll keep reading until it hits a zero.
  1864. */
  1865. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  1866. /** Returns the number of bytes required to represent this string as UTF8.
  1867. The number returned does NOT include the trailing zero.
  1868. @see toUTF8, copyToUTF8
  1869. */
  1870. int getNumBytesAsUTF8() const throw();
  1871. /** Copies the string to a buffer as UTF-8 characters.
  1872. Returns the number of bytes copied to the buffer, including the terminating null
  1873. character.
  1874. @param destBuffer the place to copy it to; if this is a null pointer,
  1875. the method just returns the number of bytes required
  1876. (including the terminating null character).
  1877. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1878. string won't fit, it'll put in as many as it can while
  1879. still allowing for a terminating null char at the end, and
  1880. will return the number of bytes that were actually used.
  1881. */
  1882. int copyToUTF8 (char* destBuffer, int maxBufferSizeBytes) const throw();
  1883. /** Returns a version of this string using the default 8-bit multi-byte system encoding.
  1884. Because it returns a reference to the string's internal data, the pointer
  1885. that is returned must not be stored anywhere, as it can be deleted whenever the
  1886. string changes.
  1887. @see getNumBytesAsCString, copyToCString, toUTF8
  1888. */
  1889. const char* toCString() const;
  1890. /** Returns the number of bytes
  1891. */
  1892. int getNumBytesAsCString() const throw();
  1893. /** Copies the string to a buffer.
  1894. @param destBuffer the place to copy it to; if this is a null pointer,
  1895. the method just returns the number of bytes required
  1896. (including the terminating null character).
  1897. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1898. string won't fit, it'll put in as many as it can while
  1899. still allowing for a terminating null char at the end, and
  1900. will return the number of bytes that were actually used.
  1901. */
  1902. int copyToCString (char* destBuffer, int maxBufferSizeBytes) const throw();
  1903. /** Copies the string to a unicode buffer.
  1904. @param destBuffer the place to copy it to
  1905. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1906. not including the tailing zero, so this shouldn't be
  1907. larger than the size of your destination buffer - 1
  1908. */
  1909. void copyToUnicode (juce_wchar* destBuffer, int maxCharsToCopy) const throw();
  1910. /** Increases the string's internally allocated storage.
  1911. Although the string's contents won't be affected by this call, it will
  1912. increase the amount of memory allocated internally for the string to grow into.
  1913. If you're about to make a large number of calls to methods such
  1914. as += or <<, it's more efficient to preallocate enough extra space
  1915. beforehand, so that these methods won't have to keep resizing the string
  1916. to append the extra characters.
  1917. @param numCharsNeeded the number of characters to allocate storage for. If this
  1918. value is less than the currently allocated size, it will
  1919. have no effect.
  1920. */
  1921. void preallocateStorage (size_t numCharsNeeded);
  1922. /** Swaps the contents of this string with another one.
  1923. This is a very fast operation, as no allocation or copying needs to be done.
  1924. */
  1925. void swapWith (String& other) throw();
  1926. /** A helper class to improve performance when concatenating many large strings
  1927. together.
  1928. Because appending one string to another involves measuring the length of
  1929. both strings, repeatedly doing this for many long strings will become
  1930. an exponentially slow operation. This class uses some internal state to
  1931. avoid that, so that each append operation only needs to measure the length
  1932. of the appended string.
  1933. */
  1934. class JUCE_API Concatenator
  1935. {
  1936. public:
  1937. Concatenator (String& stringToAppendTo);
  1938. ~Concatenator();
  1939. void append (const String& s);
  1940. private:
  1941. String& result;
  1942. int nextIndex;
  1943. Concatenator (const Concatenator&);
  1944. Concatenator& operator= (const Concatenator&);
  1945. };
  1946. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1947. private:
  1948. juce_wchar* text;
  1949. // internal constructor that preallocates a certain amount of memory
  1950. String (size_t numChars, int dummyVariable);
  1951. String (const String& stringToCopy, size_t charsToAllocate);
  1952. void createInternal (const juce_wchar* text, size_t numChars);
  1953. void appendInternal (const juce_wchar* text, int numExtraChars);
  1954. };
  1955. /** Concatenates two strings. */
  1956. const String JUCE_CALLTYPE operator+ (const char* string1, const String& string2);
  1957. /** Concatenates two strings. */
  1958. const String JUCE_CALLTYPE operator+ (const juce_wchar* string1, const String& string2);
  1959. /** Concatenates two strings. */
  1960. const String JUCE_CALLTYPE operator+ (char string1, const String& string2);
  1961. /** Concatenates two strings. */
  1962. const String JUCE_CALLTYPE operator+ (juce_wchar string1, const String& string2);
  1963. /** Concatenates two strings. */
  1964. const String JUCE_CALLTYPE operator+ (String string1, const String& string2);
  1965. /** Concatenates two strings. */
  1966. const String JUCE_CALLTYPE operator+ (String string1, const char* string2);
  1967. /** Concatenates two strings. */
  1968. const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* string2);
  1969. /** Concatenates two strings. */
  1970. const String JUCE_CALLTYPE operator+ (String string1, char characterToAppend);
  1971. /** Concatenates two strings. */
  1972. const String JUCE_CALLTYPE operator+ (String string1, juce_wchar characterToAppend);
  1973. /** Appends a character at the end of a string. */
  1974. String& JUCE_CALLTYPE operator<< (String& string1, char characterToAppend);
  1975. /** Appends a character at the end of a string. */
  1976. String& JUCE_CALLTYPE operator<< (String& string1, juce_wchar characterToAppend);
  1977. /** Appends a string to the end of the first one. */
  1978. String& JUCE_CALLTYPE operator<< (String& string1, const char* string2);
  1979. /** Appends a string to the end of the first one. */
  1980. String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* string2);
  1981. /** Appends a string to the end of the first one. */
  1982. String& JUCE_CALLTYPE operator<< (String& string1, const String& string2);
  1983. /** Appends a decimal number at the end of a string. */
  1984. String& JUCE_CALLTYPE operator<< (String& string1, short number);
  1985. /** Appends a decimal number at the end of a string. */
  1986. String& JUCE_CALLTYPE operator<< (String& string1, int number);
  1987. /** Appends a decimal number at the end of a string. */
  1988. String& JUCE_CALLTYPE operator<< (String& string1, unsigned int number);
  1989. /** Appends a decimal number at the end of a string. */
  1990. String& JUCE_CALLTYPE operator<< (String& string1, long number);
  1991. /** Appends a decimal number at the end of a string. */
  1992. String& JUCE_CALLTYPE operator<< (String& string1, unsigned long number);
  1993. /** Appends a decimal number at the end of a string. */
  1994. String& JUCE_CALLTYPE operator<< (String& string1, float number);
  1995. /** Appends a decimal number at the end of a string. */
  1996. String& JUCE_CALLTYPE operator<< (String& string1, double number);
  1997. /** Case-sensitive comparison of two strings. */
  1998. bool JUCE_CALLTYPE operator== (const String& string1, const String& string2) throw();
  1999. /** Case-sensitive comparison of two strings. */
  2000. bool JUCE_CALLTYPE operator== (const String& string1, const char* string2) throw();
  2001. /** Case-sensitive comparison of two strings. */
  2002. bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw();
  2003. /** Case-sensitive comparison of two strings. */
  2004. bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw();
  2005. /** Case-sensitive comparison of two strings. */
  2006. bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw();
  2007. /** Case-sensitive comparison of two strings. */
  2008. bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw();
  2009. /** Case-sensitive comparison of two strings. */
  2010. bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw();
  2011. /** Case-sensitive comparison of two strings. */
  2012. bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw();
  2013. /** Case-sensitive comparison of two strings. */
  2014. bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw();
  2015. /** Case-sensitive comparison of two strings. */
  2016. bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw();
  2017. /** This streaming override allows you to pass a juce String directly into std output streams.
  2018. This is very handy for writing strings to std::cout, std::cerr, etc.
  2019. */
  2020. template <class charT, class traits>
  2021. std::basic_ostream <charT, traits>& JUCE_CALLTYPE operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  2022. {
  2023. return stream << stringToWrite.toUTF8();
  2024. }
  2025. /** Writes a string to an OutputStream as UTF8. */
  2026. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text);
  2027. #endif // __JUCE_STRING_JUCEHEADER__
  2028. /*** End of inlined file: juce_String.h ***/
  2029. /**
  2030. Acts as an application-wide logging class.
  2031. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  2032. method and this will then be used by all calls to writeToLog.
  2033. The logger class also contains methods for writing messages to the debugger's
  2034. output stream.
  2035. @see FileLogger
  2036. */
  2037. class JUCE_API Logger
  2038. {
  2039. public:
  2040. /** Destructor. */
  2041. virtual ~Logger();
  2042. /** Sets the current logging class to use.
  2043. Note that the object passed in won't be deleted when no longer needed.
  2044. A null pointer can be passed-in to disable any logging.
  2045. If deleteOldLogger is set to true, the existing logger will be
  2046. deleted (if there is one).
  2047. */
  2048. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  2049. const bool deleteOldLogger = false);
  2050. /** Writes a string to the current logger.
  2051. This will pass the string to the logger's logMessage() method if a logger
  2052. has been set.
  2053. @see logMessage
  2054. */
  2055. static void JUCE_CALLTYPE writeToLog (const String& message);
  2056. /** Writes a message to the standard error stream.
  2057. This can be called directly, or by using the DBG() macro in
  2058. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2059. */
  2060. static void JUCE_CALLTYPE outputDebugString (const String& text);
  2061. protected:
  2062. Logger();
  2063. /** This is overloaded by subclasses to implement custom logging behaviour.
  2064. @see setCurrentLogger
  2065. */
  2066. virtual void logMessage (const String& message) = 0;
  2067. };
  2068. #endif // __JUCE_LOGGER_JUCEHEADER__
  2069. /*** End of inlined file: juce_Logger.h ***/
  2070. END_JUCE_NAMESPACE
  2071. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2072. /*** End of inlined file: juce_StandardHeader.h ***/
  2073. BEGIN_JUCE_NAMESPACE
  2074. #if JUCE_MSVC
  2075. // this is set explicitly in case the app is using a different packing size.
  2076. #pragma pack (push, 8)
  2077. #pragma warning (push)
  2078. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2079. #endif
  2080. // this is where all the class header files get brought in..
  2081. /*** Start of inlined file: juce_core_includes.h ***/
  2082. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2083. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2084. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2085. /*** Start of inlined file: juce_Array.h ***/
  2086. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2087. #define __JUCE_ARRAY_JUCEHEADER__
  2088. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  2089. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2090. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2091. /*** Start of inlined file: juce_HeapBlock.h ***/
  2092. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  2093. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  2094. /**
  2095. Very simple container class to hold a pointer to some data on the heap.
  2096. When you need to allocate some heap storage for something, always try to use
  2097. this class instead of allocating the memory directly using malloc/free.
  2098. A HeapBlock<char> object can be treated in pretty much exactly the same way
  2099. as an char*, but as long as you allocate it on the stack or as a class member,
  2100. it's almost impossible for it to leak memory.
  2101. It also makes your code much more concise and readable than doing the same thing
  2102. using direct allocations,
  2103. E.g. instead of this:
  2104. @code
  2105. int* temp = (int*) juce_malloc (1024 * sizeof (int));
  2106. memcpy (temp, xyz, 1024 * sizeof (int));
  2107. juce_free (temp);
  2108. temp = (int*) juce_calloc (2048 * sizeof (int));
  2109. temp[0] = 1234;
  2110. memcpy (foobar, temp, 2048 * sizeof (int));
  2111. juce_free (temp);
  2112. @endcode
  2113. ..you could just write this:
  2114. @code
  2115. HeapBlock <int> temp (1024);
  2116. memcpy (temp, xyz, 1024 * sizeof (int));
  2117. temp.calloc (2048);
  2118. temp[0] = 1234;
  2119. memcpy (foobar, temp, 2048 * sizeof (int));
  2120. @endcode
  2121. The class is extremely lightweight, containing only a pointer to the
  2122. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  2123. as their less object-oriented counterparts. Despite adding safety, you probably
  2124. won't sacrifice any performance by using this in place of normal pointers.
  2125. @see Array, OwnedArray, MemoryBlock
  2126. */
  2127. template <class ElementType>
  2128. class HeapBlock
  2129. {
  2130. public:
  2131. /** Creates a HeapBlock which is initially just a null pointer.
  2132. After creation, you can resize the array using the malloc(), calloc(),
  2133. or realloc() methods.
  2134. */
  2135. HeapBlock() throw() : data (0)
  2136. {
  2137. }
  2138. /** Creates a HeapBlock containing a number of elements.
  2139. The contents of the block are undefined, as it will have been created by a
  2140. malloc call.
  2141. If you want an array of zero values, you can use the calloc() method instead.
  2142. */
  2143. explicit HeapBlock (const size_t numElements)
  2144. : data (static_cast <ElementType*> (::juce_malloc (numElements * sizeof (ElementType))))
  2145. {
  2146. }
  2147. /** Destructor.
  2148. This will free the data, if any has been allocated.
  2149. */
  2150. ~HeapBlock()
  2151. {
  2152. ::juce_free (data);
  2153. }
  2154. /** Returns a raw pointer to the allocated data.
  2155. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2156. freed by calling the free() method.
  2157. */
  2158. inline operator ElementType*() const throw() { return data; }
  2159. /** Returns a raw pointer to the allocated data.
  2160. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2161. freed by calling the free() method.
  2162. */
  2163. inline ElementType* getData() const throw() { return data; }
  2164. /** Returns a void pointer to the allocated data.
  2165. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2166. freed by calling the free() method.
  2167. */
  2168. inline operator void*() const throw() { return static_cast <void*> (data); }
  2169. /** Lets you use indirect calls to the first element in the array.
  2170. Obviously this will cause problems if the array hasn't been initialised, because it'll
  2171. be referencing a null pointer.
  2172. */
  2173. inline ElementType* operator->() const throw() { return data; }
  2174. /** Returns a reference to one of the data elements.
  2175. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  2176. has no idea of the size it currently has allocated.
  2177. */
  2178. template <typename IndexType>
  2179. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  2180. /** Returns a pointer to a data element at an offset from the start of the array.
  2181. This is the same as doing pointer arithmetic on the raw pointer itself.
  2182. */
  2183. template <typename IndexType>
  2184. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  2185. /** Returns a reference to the raw data pointer.
  2186. Beware that the pointer returned here will become invalid as soon as you call
  2187. any of the allocator methods on this object!
  2188. */
  2189. inline ElementType* const* operator&() const throw() { return static_cast <ElementType* const*> (&data); }
  2190. /** Returns a reference to the raw data pointer.
  2191. Beware that the pointer returned here will become invalid as soon as you call
  2192. any of the allocator methods on this object!
  2193. */
  2194. inline ElementType** operator&() throw() { return static_cast <ElementType**> (&data); }
  2195. /** Compares the pointer with another pointer.
  2196. This can be handy for checking whether this is a null pointer.
  2197. */
  2198. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  2199. /** Compares the pointer with another pointer.
  2200. This can be handy for checking whether this is a null pointer.
  2201. */
  2202. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  2203. /** Allocates a specified amount of memory.
  2204. This uses the normal malloc to allocate an amount of memory for this object.
  2205. Any previously allocated memory will be freed by this method.
  2206. The number of bytes allocated will be (newNumElements * elementSize). Normally
  2207. you wouldn't need to specify the second parameter, but it can be handy if you need
  2208. to allocate a size in bytes rather than in terms of the number of elements.
  2209. The data that is allocated will be freed when this object is deleted, or when you
  2210. call free() or any of the allocation methods.
  2211. */
  2212. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2213. {
  2214. ::juce_free (data);
  2215. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2216. }
  2217. /** Allocates a specified amount of memory and clears it.
  2218. This does the same job as the malloc() method, but clears the memory that it allocates.
  2219. */
  2220. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2221. {
  2222. ::juce_free (data);
  2223. data = static_cast <ElementType*> (::juce_calloc (newNumElements * elementSize));
  2224. }
  2225. /** Allocates a specified amount of memory and optionally clears it.
  2226. This does the same job as either malloc() or calloc(), depending on the
  2227. initialiseToZero parameter.
  2228. */
  2229. void allocate (const size_t newNumElements, const bool initialiseToZero)
  2230. {
  2231. ::juce_free (data);
  2232. if (initialiseToZero)
  2233. data = static_cast <ElementType*> (::juce_calloc (newNumElements * sizeof (ElementType)));
  2234. else
  2235. data = static_cast <ElementType*> (::juce_malloc (newNumElements * sizeof (ElementType)));
  2236. }
  2237. /** Re-allocates a specified amount of memory.
  2238. The semantics of this method are the same as malloc() and calloc(), but it
  2239. uses realloc() to keep as much of the existing data as possible.
  2240. */
  2241. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2242. {
  2243. if (data == 0)
  2244. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2245. else
  2246. data = static_cast <ElementType*> (::juce_realloc (data, newNumElements * elementSize));
  2247. }
  2248. /** Frees any currently-allocated data.
  2249. This will free the data and reset this object to be a null pointer.
  2250. */
  2251. void free()
  2252. {
  2253. ::juce_free (data);
  2254. data = 0;
  2255. }
  2256. /** Swaps this object's data with the data of another HeapBlock.
  2257. The two objects simply exchange their data pointers.
  2258. */
  2259. void swapWith (HeapBlock <ElementType>& other) throw()
  2260. {
  2261. swapVariables (data, other.data);
  2262. }
  2263. private:
  2264. ElementType* data;
  2265. HeapBlock (const HeapBlock&);
  2266. HeapBlock& operator= (const HeapBlock&);
  2267. };
  2268. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  2269. /*** End of inlined file: juce_HeapBlock.h ***/
  2270. /**
  2271. Implements some basic array storage allocation functions.
  2272. This class isn't really for public use - it's used by the other
  2273. array classes, but might come in handy for some purposes.
  2274. It inherits from a critical section class to allow the arrays to use
  2275. the "empty base class optimisation" pattern to reduce their footprint.
  2276. @see Array, OwnedArray, ReferenceCountedArray
  2277. */
  2278. template <class ElementType, class TypeOfCriticalSectionToUse>
  2279. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  2280. {
  2281. public:
  2282. /** Creates an empty array. */
  2283. ArrayAllocationBase() throw()
  2284. : numAllocated (0)
  2285. {
  2286. }
  2287. /** Destructor. */
  2288. ~ArrayAllocationBase()
  2289. {
  2290. }
  2291. /** Changes the amount of storage allocated.
  2292. This will retain any data currently held in the array, and either add or
  2293. remove extra space at the end.
  2294. @param numElements the number of elements that are needed
  2295. */
  2296. void setAllocatedSize (const int numElements)
  2297. {
  2298. if (numAllocated != numElements)
  2299. {
  2300. if (numElements > 0)
  2301. elements.realloc (numElements);
  2302. else
  2303. elements.free();
  2304. numAllocated = numElements;
  2305. }
  2306. }
  2307. /** Increases the amount of storage allocated if it is less than a given amount.
  2308. This will retain any data currently held in the array, but will add
  2309. extra space at the end to make sure there it's at least as big as the size
  2310. passed in. If it's already bigger, no action is taken.
  2311. @param minNumElements the minimum number of elements that are needed
  2312. */
  2313. void ensureAllocatedSize (const int minNumElements)
  2314. {
  2315. if (minNumElements > numAllocated)
  2316. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  2317. }
  2318. /** Minimises the amount of storage allocated so that it's no more than
  2319. the given number of elements.
  2320. */
  2321. void shrinkToNoMoreThan (const int maxNumElements)
  2322. {
  2323. if (maxNumElements < numAllocated)
  2324. setAllocatedSize (maxNumElements);
  2325. }
  2326. /** Swap the contents of two objects. */
  2327. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2328. {
  2329. elements.swapWith (other.elements);
  2330. swapVariables (numAllocated, other.numAllocated);
  2331. }
  2332. HeapBlock <ElementType> elements;
  2333. int numAllocated;
  2334. private:
  2335. ArrayAllocationBase (const ArrayAllocationBase&);
  2336. ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2337. };
  2338. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2339. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  2340. /*** Start of inlined file: juce_ElementComparator.h ***/
  2341. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2342. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2343. /**
  2344. Sorts a range of elements in an array.
  2345. The comparator object that is passed-in must define a public method with the following
  2346. signature:
  2347. @code
  2348. int compareElements (ElementType first, ElementType second);
  2349. @endcode
  2350. ..and this method must return:
  2351. - a value of < 0 if the first comes before the second
  2352. - a value of 0 if the two objects are equivalent
  2353. - a value of > 0 if the second comes before the first
  2354. To improve performance, the compareElements() method can be declared as static or const.
  2355. @param comparator an object which defines a compareElements() method
  2356. @param array the array to sort
  2357. @param firstElement the index of the first element of the range to be sorted
  2358. @param lastElement the index of the last element in the range that needs
  2359. sorting (this is inclusive)
  2360. @param retainOrderOfEquivalentItems if true, the order of items that the
  2361. comparator deems the same will be maintained - this will be
  2362. a slower algorithm than if they are allowed to be moved around.
  2363. @see sortArrayRetainingOrder
  2364. */
  2365. template <class ElementType, class ElementComparator>
  2366. static void sortArray (ElementComparator& comparator,
  2367. ElementType* const array,
  2368. int firstElement,
  2369. int lastElement,
  2370. const bool retainOrderOfEquivalentItems)
  2371. {
  2372. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2373. // avoids getting warning messages about the parameter being unused
  2374. if (lastElement > firstElement)
  2375. {
  2376. if (retainOrderOfEquivalentItems)
  2377. {
  2378. for (int i = firstElement; i < lastElement; ++i)
  2379. {
  2380. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2381. {
  2382. const ElementType temp = array [i];
  2383. array [i] = array[i + 1];
  2384. array [i + 1] = temp;
  2385. if (i > firstElement)
  2386. i -= 2;
  2387. }
  2388. }
  2389. }
  2390. else
  2391. {
  2392. int fromStack[30], toStack[30];
  2393. int stackIndex = 0;
  2394. for (;;)
  2395. {
  2396. const int size = (lastElement - firstElement) + 1;
  2397. if (size <= 8)
  2398. {
  2399. int j = lastElement;
  2400. int maxIndex;
  2401. while (j > firstElement)
  2402. {
  2403. maxIndex = firstElement;
  2404. for (int k = firstElement + 1; k <= j; ++k)
  2405. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2406. maxIndex = k;
  2407. const ElementType temp = array [maxIndex];
  2408. array [maxIndex] = array[j];
  2409. array [j] = temp;
  2410. --j;
  2411. }
  2412. }
  2413. else
  2414. {
  2415. const int mid = firstElement + (size >> 1);
  2416. ElementType temp = array [mid];
  2417. array [mid] = array [firstElement];
  2418. array [firstElement] = temp;
  2419. int i = firstElement;
  2420. int j = lastElement + 1;
  2421. for (;;)
  2422. {
  2423. while (++i <= lastElement
  2424. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2425. {}
  2426. while (--j > firstElement
  2427. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2428. {}
  2429. if (j < i)
  2430. break;
  2431. temp = array[i];
  2432. array[i] = array[j];
  2433. array[j] = temp;
  2434. }
  2435. temp = array [firstElement];
  2436. array [firstElement] = array[j];
  2437. array [j] = temp;
  2438. if (j - 1 - firstElement >= lastElement - i)
  2439. {
  2440. if (firstElement + 1 < j)
  2441. {
  2442. fromStack [stackIndex] = firstElement;
  2443. toStack [stackIndex] = j - 1;
  2444. ++stackIndex;
  2445. }
  2446. if (i < lastElement)
  2447. {
  2448. firstElement = i;
  2449. continue;
  2450. }
  2451. }
  2452. else
  2453. {
  2454. if (i < lastElement)
  2455. {
  2456. fromStack [stackIndex] = i;
  2457. toStack [stackIndex] = lastElement;
  2458. ++stackIndex;
  2459. }
  2460. if (firstElement + 1 < j)
  2461. {
  2462. lastElement = j - 1;
  2463. continue;
  2464. }
  2465. }
  2466. }
  2467. if (--stackIndex < 0)
  2468. break;
  2469. jassert (stackIndex < numElementsInArray (fromStack));
  2470. firstElement = fromStack [stackIndex];
  2471. lastElement = toStack [stackIndex];
  2472. }
  2473. }
  2474. }
  2475. }
  2476. /**
  2477. Searches a sorted array of elements, looking for the index at which a specified value
  2478. should be inserted for it to be in the correct order.
  2479. The comparator object that is passed-in must define a public method with the following
  2480. signature:
  2481. @code
  2482. int compareElements (ElementType first, ElementType second);
  2483. @endcode
  2484. ..and this method must return:
  2485. - a value of < 0 if the first comes before the second
  2486. - a value of 0 if the two objects are equivalent
  2487. - a value of > 0 if the second comes before the first
  2488. To improve performance, the compareElements() method can be declared as static or const.
  2489. @param comparator an object which defines a compareElements() method
  2490. @param array the array to search
  2491. @param newElement the value that is going to be inserted
  2492. @param firstElement the index of the first element to search
  2493. @param lastElement the index of the last element in the range (this is non-inclusive)
  2494. */
  2495. template <class ElementType, class ElementComparator>
  2496. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2497. ElementType* const array,
  2498. const ElementType newElement,
  2499. int firstElement,
  2500. int lastElement)
  2501. {
  2502. jassert (firstElement <= lastElement);
  2503. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2504. // avoids getting warning messages about the parameter being unused
  2505. while (firstElement < lastElement)
  2506. {
  2507. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2508. {
  2509. ++firstElement;
  2510. break;
  2511. }
  2512. else
  2513. {
  2514. const int halfway = (firstElement + lastElement) >> 1;
  2515. if (halfway == firstElement)
  2516. {
  2517. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2518. ++firstElement;
  2519. break;
  2520. }
  2521. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2522. {
  2523. firstElement = halfway;
  2524. }
  2525. else
  2526. {
  2527. lastElement = halfway;
  2528. }
  2529. }
  2530. }
  2531. return firstElement;
  2532. }
  2533. /**
  2534. A simple ElementComparator class that can be used to sort an array of
  2535. objects that support the '<' operator.
  2536. This will work for primitive types and objects that implement operator<().
  2537. Example: @code
  2538. Array <int> myArray;
  2539. DefaultElementComparator<int> sorter;
  2540. myArray.sort (sorter);
  2541. @endcode
  2542. @see ElementComparator
  2543. */
  2544. template <class ElementType>
  2545. class DefaultElementComparator
  2546. {
  2547. private:
  2548. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2549. public:
  2550. static int compareElements (ParameterType first, ParameterType second)
  2551. {
  2552. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  2553. }
  2554. };
  2555. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2556. /*** End of inlined file: juce_ElementComparator.h ***/
  2557. /*** Start of inlined file: juce_CriticalSection.h ***/
  2558. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2559. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2560. class JUCE_API ScopedLock;
  2561. class JUCE_API ScopedUnlock;
  2562. /**
  2563. Prevents multiple threads from accessing shared objects at the same time.
  2564. @see ScopedLock, Thread, InterProcessLock
  2565. */
  2566. class JUCE_API CriticalSection
  2567. {
  2568. public:
  2569. /**
  2570. Creates a CriticalSection object
  2571. */
  2572. CriticalSection() throw();
  2573. /** Destroys a CriticalSection object.
  2574. If the critical section is deleted whilst locked, its subsequent behaviour
  2575. is unpredictable.
  2576. */
  2577. ~CriticalSection() throw();
  2578. /** Locks this critical section.
  2579. If the lock is currently held by another thread, this will wait until it
  2580. becomes free.
  2581. If the lock is already held by the caller thread, the method returns immediately.
  2582. @see exit, ScopedLock
  2583. */
  2584. void enter() const throw();
  2585. /** Attempts to lock this critical section without blocking.
  2586. This method behaves identically to CriticalSection::enter, except that the caller thread
  2587. does not wait if the lock is currently held by another thread but returns false immediately.
  2588. @returns false if the lock is currently held by another thread, true otherwise.
  2589. @see enter
  2590. */
  2591. bool tryEnter() const throw();
  2592. /** Releases the lock.
  2593. If the caller thread hasn't got the lock, this can have unpredictable results.
  2594. If the enter() method has been called multiple times by the thread, each
  2595. call must be matched by a call to exit() before other threads will be allowed
  2596. to take over the lock.
  2597. @see enter, ScopedLock
  2598. */
  2599. void exit() const throw();
  2600. /** Provides the type of scoped lock to use with this type of critical section object. */
  2601. typedef ScopedLock ScopedLockType;
  2602. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  2603. typedef ScopedUnlock ScopedUnlockType;
  2604. juce_UseDebuggingNewOperator
  2605. private:
  2606. #if JUCE_WINDOWS
  2607. #if JUCE_64BIT
  2608. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2609. // block of memory here that's big enough to be used internally as a windows critical
  2610. // section object.
  2611. uint8 internal [44];
  2612. #else
  2613. uint8 internal [24];
  2614. #endif
  2615. #else
  2616. mutable pthread_mutex_t internal;
  2617. #endif
  2618. CriticalSection (const CriticalSection&);
  2619. CriticalSection& operator= (const CriticalSection&);
  2620. };
  2621. /**
  2622. A class that can be used in place of a real CriticalSection object.
  2623. This is currently used by some templated classes, and should get
  2624. optimised out by the compiler.
  2625. @see Array, OwnedArray, ReferenceCountedArray
  2626. */
  2627. class JUCE_API DummyCriticalSection
  2628. {
  2629. public:
  2630. inline DummyCriticalSection() throw() {}
  2631. inline ~DummyCriticalSection() throw() {}
  2632. inline void enter() const throw() {}
  2633. inline void exit() const throw() {}
  2634. /** A dummy scoped-lock type to use with a dummy critical section. */
  2635. struct ScopedLockType
  2636. {
  2637. ScopedLockType (const DummyCriticalSection&) throw() {}
  2638. };
  2639. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  2640. typedef ScopedLockType ScopedUnlockType;
  2641. private:
  2642. DummyCriticalSection (const DummyCriticalSection&);
  2643. DummyCriticalSection& operator= (const DummyCriticalSection&);
  2644. };
  2645. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2646. /*** End of inlined file: juce_CriticalSection.h ***/
  2647. /**
  2648. Holds a list of simple objects, such as ints, doubles, or pointers.
  2649. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  2650. The array can be used to hold simple, non-polymorphic objects as well as primitive types - to
  2651. do so, the class must fulfil these requirements:
  2652. - it must have a copy constructor and operator=
  2653. - it must be able to be relocated in memory by a memcpy without this causing a problem - so no
  2654. objects whose functionality relies on pointers or references to themselves can be used.
  2655. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  2656. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  2657. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  2658. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  2659. specialised class StringArray, which provides more useful functions.
  2660. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2661. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2662. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2663. */
  2664. template <typename ElementType,
  2665. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  2666. class Array
  2667. {
  2668. private:
  2669. #if defined (_MSC_VER) && _MSC_VER <= 1400
  2670. typedef const ElementType& ParameterType;
  2671. #else
  2672. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2673. #endif
  2674. public:
  2675. /** Creates an empty array. */
  2676. Array() throw()
  2677. : numUsed (0)
  2678. {
  2679. }
  2680. /** Creates a copy of another array.
  2681. @param other the array to copy
  2682. */
  2683. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  2684. {
  2685. const ScopedLockType lock (other.getLock());
  2686. numUsed = other.numUsed;
  2687. data.setAllocatedSize (other.numUsed);
  2688. for (int i = 0; i < numUsed; ++i)
  2689. new (data.elements + i) ElementType (other.data.elements[i]);
  2690. }
  2691. /** Initalises from a null-terminated C array of values.
  2692. @param values the array to copy from
  2693. */
  2694. template <typename TypeToCreateFrom>
  2695. explicit Array (const TypeToCreateFrom* values)
  2696. : numUsed (0)
  2697. {
  2698. while (*values != TypeToCreateFrom())
  2699. add (*values++);
  2700. }
  2701. /** Initalises from a C array of values.
  2702. @param values the array to copy from
  2703. @param numValues the number of values in the array
  2704. */
  2705. template <typename TypeToCreateFrom>
  2706. Array (const TypeToCreateFrom* values, int numValues)
  2707. : numUsed (numValues)
  2708. {
  2709. data.setAllocatedSize (numValues);
  2710. for (int i = 0; i < numValues; ++i)
  2711. new (data.elements + i) ElementType (values[i]);
  2712. }
  2713. /** Destructor. */
  2714. ~Array()
  2715. {
  2716. for (int i = 0; i < numUsed; ++i)
  2717. data.elements[i].~ElementType();
  2718. }
  2719. /** Copies another array.
  2720. @param other the array to copy
  2721. */
  2722. Array& operator= (const Array& other)
  2723. {
  2724. if (this != &other)
  2725. {
  2726. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  2727. swapWithArray (otherCopy);
  2728. }
  2729. return *this;
  2730. }
  2731. /** Compares this array to another one.
  2732. Two arrays are considered equal if they both contain the same set of
  2733. elements, in the same order.
  2734. @param other the other array to compare with
  2735. */
  2736. template <class OtherArrayType>
  2737. bool operator== (const OtherArrayType& other) const
  2738. {
  2739. const ScopedLockType lock (getLock());
  2740. if (numUsed != other.numUsed)
  2741. return false;
  2742. for (int i = numUsed; --i >= 0;)
  2743. if (! (data.elements [i] == other.data.elements [i]))
  2744. return false;
  2745. return true;
  2746. }
  2747. /** Compares this array to another one.
  2748. Two arrays are considered equal if they both contain the same set of
  2749. elements, in the same order.
  2750. @param other the other array to compare with
  2751. */
  2752. template <class OtherArrayType>
  2753. bool operator!= (const OtherArrayType& other) const
  2754. {
  2755. return ! operator== (other);
  2756. }
  2757. /** Removes all elements from the array.
  2758. This will remove all the elements, and free any storage that the array is
  2759. using. To clear the array without freeing the storage, use the clearQuick()
  2760. method instead.
  2761. @see clearQuick
  2762. */
  2763. void clear()
  2764. {
  2765. const ScopedLockType lock (getLock());
  2766. for (int i = 0; i < numUsed; ++i)
  2767. data.elements[i].~ElementType();
  2768. data.setAllocatedSize (0);
  2769. numUsed = 0;
  2770. }
  2771. /** Removes all elements from the array without freeing the array's allocated storage.
  2772. @see clear
  2773. */
  2774. void clearQuick()
  2775. {
  2776. const ScopedLockType lock (getLock());
  2777. for (int i = 0; i < numUsed; ++i)
  2778. data.elements[i].~ElementType();
  2779. numUsed = 0;
  2780. }
  2781. /** Returns the current number of elements in the array.
  2782. */
  2783. inline int size() const throw()
  2784. {
  2785. return numUsed;
  2786. }
  2787. /** Returns one of the elements in the array.
  2788. If the index passed in is beyond the range of valid elements, this
  2789. will return zero.
  2790. If you're certain that the index will always be a valid element, you
  2791. can call getUnchecked() instead, which is faster.
  2792. @param index the index of the element being requested (0 is the first element in the array)
  2793. @see getUnchecked, getFirst, getLast
  2794. */
  2795. inline ElementType operator[] (const int index) const
  2796. {
  2797. const ScopedLockType lock (getLock());
  2798. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  2799. : ElementType();
  2800. }
  2801. /** Returns one of the elements in the array, without checking the index passed in.
  2802. Unlike the operator[] method, this will try to return an element without
  2803. checking that the index is within the bounds of the array, so should only
  2804. be used when you're confident that it will always be a valid index.
  2805. @param index the index of the element being requested (0 is the first element in the array)
  2806. @see operator[], getFirst, getLast
  2807. */
  2808. inline const ElementType getUnchecked (const int index) const
  2809. {
  2810. const ScopedLockType lock (getLock());
  2811. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2812. return data.elements [index];
  2813. }
  2814. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2815. This is like getUnchecked, but returns a direct reference to the element, so that
  2816. you can alter it directly. Obviously this can be dangerous, so only use it when
  2817. absolutely necessary.
  2818. @param index the index of the element being requested (0 is the first element in the array)
  2819. @see operator[], getFirst, getLast
  2820. */
  2821. inline ElementType& getReference (const int index) const throw()
  2822. {
  2823. const ScopedLockType lock (getLock());
  2824. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2825. return data.elements [index];
  2826. }
  2827. /** Returns the first element in the array, or 0 if the array is empty.
  2828. @see operator[], getUnchecked, getLast
  2829. */
  2830. inline ElementType getFirst() const
  2831. {
  2832. const ScopedLockType lock (getLock());
  2833. return (numUsed > 0) ? data.elements [0]
  2834. : ElementType();
  2835. }
  2836. /** Returns the last element in the array, or 0 if the array is empty.
  2837. @see operator[], getUnchecked, getFirst
  2838. */
  2839. inline ElementType getLast() const
  2840. {
  2841. const ScopedLockType lock (getLock());
  2842. return (numUsed > 0) ? data.elements [numUsed - 1]
  2843. : ElementType();
  2844. }
  2845. /** Returns a pointer to the actual array data.
  2846. This pointer will only be valid until the next time a non-const method
  2847. is called on the array.
  2848. */
  2849. inline ElementType* getRawDataPointer() throw()
  2850. {
  2851. return data.elements;
  2852. }
  2853. /** Finds the index of the first element which matches the value passed in.
  2854. This will search the array for the given object, and return the index
  2855. of its first occurrence. If the object isn't found, the method will return -1.
  2856. @param elementToLookFor the value or object to look for
  2857. @returns the index of the object, or -1 if it's not found
  2858. */
  2859. int indexOf (ParameterType elementToLookFor) const
  2860. {
  2861. const ScopedLockType lock (getLock());
  2862. const ElementType* e = data.elements.getData();
  2863. const ElementType* const end = e + numUsed;
  2864. while (e != end)
  2865. {
  2866. if (elementToLookFor == *e)
  2867. return static_cast <int> (e - data.elements.getData());
  2868. ++e;
  2869. }
  2870. return -1;
  2871. }
  2872. /** Returns true if the array contains at least one occurrence of an object.
  2873. @param elementToLookFor the value or object to look for
  2874. @returns true if the item is found
  2875. */
  2876. bool contains (ParameterType elementToLookFor) const
  2877. {
  2878. const ScopedLockType lock (getLock());
  2879. const ElementType* e = data.elements.getData();
  2880. const ElementType* const end = e + numUsed;
  2881. while (e != end)
  2882. {
  2883. if (elementToLookFor == *e)
  2884. return true;
  2885. ++e;
  2886. }
  2887. return false;
  2888. }
  2889. /** Appends a new element at the end of the array.
  2890. @param newElement the new object to add to the array
  2891. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  2892. */
  2893. void add (ParameterType newElement)
  2894. {
  2895. const ScopedLockType lock (getLock());
  2896. data.ensureAllocatedSize (numUsed + 1);
  2897. new (data.elements + numUsed++) ElementType (newElement);
  2898. }
  2899. /** Inserts a new element into the array at a given position.
  2900. If the index is less than 0 or greater than the size of the array, the
  2901. element will be added to the end of the array.
  2902. Otherwise, it will be inserted into the array, moving all the later elements
  2903. along to make room.
  2904. @param indexToInsertAt the index at which the new element should be
  2905. inserted (pass in -1 to add it to the end)
  2906. @param newElement the new object to add to the array
  2907. @see add, addSorted, addUsingDefaultSort, set
  2908. */
  2909. void insert (int indexToInsertAt, ParameterType newElement)
  2910. {
  2911. const ScopedLockType lock (getLock());
  2912. data.ensureAllocatedSize (numUsed + 1);
  2913. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2914. {
  2915. ElementType* const insertPos = data.elements + indexToInsertAt;
  2916. const int numberToMove = numUsed - indexToInsertAt;
  2917. if (numberToMove > 0)
  2918. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2919. new (insertPos) ElementType (newElement);
  2920. ++numUsed;
  2921. }
  2922. else
  2923. {
  2924. new (data.elements + numUsed++) ElementType (newElement);
  2925. }
  2926. }
  2927. /** Inserts multiple copies of an element into the array at a given position.
  2928. If the index is less than 0 or greater than the size of the array, the
  2929. element will be added to the end of the array.
  2930. Otherwise, it will be inserted into the array, moving all the later elements
  2931. along to make room.
  2932. @param indexToInsertAt the index at which the new element should be inserted
  2933. @param newElement the new object to add to the array
  2934. @param numberOfTimesToInsertIt how many copies of the value to insert
  2935. @see insert, add, addSorted, set
  2936. */
  2937. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  2938. int numberOfTimesToInsertIt)
  2939. {
  2940. if (numberOfTimesToInsertIt > 0)
  2941. {
  2942. const ScopedLockType lock (getLock());
  2943. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2944. ElementType* insertPos;
  2945. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2946. {
  2947. insertPos = data.elements + indexToInsertAt;
  2948. const int numberToMove = numUsed - indexToInsertAt;
  2949. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2950. }
  2951. else
  2952. {
  2953. insertPos = data.elements + numUsed;
  2954. }
  2955. numUsed += numberOfTimesToInsertIt;
  2956. while (--numberOfTimesToInsertIt >= 0)
  2957. new (insertPos++) ElementType (newElement);
  2958. }
  2959. }
  2960. /** Inserts an array of values into this array at a given position.
  2961. If the index is less than 0 or greater than the size of the array, the
  2962. new elements will be added to the end of the array.
  2963. Otherwise, they will be inserted into the array, moving all the later elements
  2964. along to make room.
  2965. @param indexToInsertAt the index at which the first new element should be inserted
  2966. @param newElements the new values to add to the array
  2967. @param numberOfElements how many items are in the array
  2968. @see insert, add, addSorted, set
  2969. */
  2970. void insertArray (int indexToInsertAt,
  2971. const ElementType* newElements,
  2972. int numberOfElements)
  2973. {
  2974. if (numberOfElements > 0)
  2975. {
  2976. const ScopedLockType lock (getLock());
  2977. data.ensureAllocatedSize (numUsed + numberOfElements);
  2978. ElementType* insertPos;
  2979. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2980. {
  2981. insertPos = data.elements + indexToInsertAt;
  2982. const int numberToMove = numUsed - indexToInsertAt;
  2983. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  2984. }
  2985. else
  2986. {
  2987. insertPos = data.elements + numUsed;
  2988. }
  2989. numUsed += numberOfElements;
  2990. while (--numberOfElements >= 0)
  2991. new (insertPos++) ElementType (*newElements++);
  2992. }
  2993. }
  2994. /** Appends a new element at the end of the array as long as the array doesn't
  2995. already contain it.
  2996. If the array already contains an element that matches the one passed in, nothing
  2997. will be done.
  2998. @param newElement the new object to add to the array
  2999. */
  3000. void addIfNotAlreadyThere (ParameterType newElement)
  3001. {
  3002. const ScopedLockType lock (getLock());
  3003. if (! contains (newElement))
  3004. add (newElement);
  3005. }
  3006. /** Replaces an element with a new value.
  3007. If the index is less than zero, this method does nothing.
  3008. If the index is beyond the end of the array, the item is added to the end of the array.
  3009. @param indexToChange the index whose value you want to change
  3010. @param newValue the new value to set for this index.
  3011. @see add, insert
  3012. */
  3013. void set (const int indexToChange, ParameterType newValue)
  3014. {
  3015. jassert (indexToChange >= 0);
  3016. const ScopedLockType lock (getLock());
  3017. if (((unsigned int) indexToChange) < (unsigned int) numUsed)
  3018. {
  3019. data.elements [indexToChange] = newValue;
  3020. }
  3021. else if (indexToChange >= 0)
  3022. {
  3023. data.ensureAllocatedSize (numUsed + 1);
  3024. new (data.elements + numUsed++) ElementType (newValue);
  3025. }
  3026. }
  3027. /** Replaces an element with a new value without doing any bounds-checking.
  3028. This just sets a value directly in the array's internal storage, so you'd
  3029. better make sure it's in range!
  3030. @param indexToChange the index whose value you want to change
  3031. @param newValue the new value to set for this index.
  3032. @see set, getUnchecked
  3033. */
  3034. void setUnchecked (const int indexToChange, ParameterType newValue)
  3035. {
  3036. const ScopedLockType lock (getLock());
  3037. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3038. data.elements [indexToChange] = newValue;
  3039. }
  3040. /** Adds elements from an array to the end of this array.
  3041. @param elementsToAdd the array of elements to add
  3042. @param numElementsToAdd how many elements are in this other array
  3043. @see add
  3044. */
  3045. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  3046. {
  3047. const ScopedLockType lock (getLock());
  3048. if (numElementsToAdd > 0)
  3049. {
  3050. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  3051. while (--numElementsToAdd >= 0)
  3052. new (data.elements + numUsed++) ElementType (*elementsToAdd++);
  3053. }
  3054. }
  3055. /** This swaps the contents of this array with those of another array.
  3056. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3057. because it just swaps their internal pointers.
  3058. */
  3059. void swapWithArray (Array& otherArray) throw()
  3060. {
  3061. const ScopedLockType lock1 (getLock());
  3062. const ScopedLockType lock2 (otherArray.getLock());
  3063. data.swapWith (otherArray.data);
  3064. swapVariables (numUsed, otherArray.numUsed);
  3065. }
  3066. /** Adds elements from another array to the end of this array.
  3067. @param arrayToAddFrom the array from which to copy the elements
  3068. @param startIndex the first element of the other array to start copying from
  3069. @param numElementsToAdd how many elements to add from the other array. If this
  3070. value is negative or greater than the number of available elements,
  3071. all available elements will be copied.
  3072. @see add
  3073. */
  3074. template <class OtherArrayType>
  3075. void addArray (const OtherArrayType& arrayToAddFrom,
  3076. int startIndex = 0,
  3077. int numElementsToAdd = -1)
  3078. {
  3079. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  3080. const ScopedLockType lock2 (getLock());
  3081. if (startIndex < 0)
  3082. {
  3083. jassertfalse;
  3084. startIndex = 0;
  3085. }
  3086. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3087. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3088. while (--numElementsToAdd >= 0)
  3089. add (arrayToAddFrom.getUnchecked (startIndex++));
  3090. }
  3091. /** Inserts a new element into the array, assuming that the array is sorted.
  3092. This will use a comparator to find the position at which the new element
  3093. should go. If the array isn't sorted, the behaviour of this
  3094. method will be unpredictable.
  3095. @param comparator the comparator to use to compare the elements - see the sort()
  3096. method for details about the form this object should take
  3097. @param newElement the new element to insert to the array
  3098. @see addUsingDefaultSort, add, sort
  3099. */
  3100. template <class ElementComparator>
  3101. void addSorted (ElementComparator& comparator, ParameterType newElement)
  3102. {
  3103. const ScopedLockType lock (getLock());
  3104. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  3105. }
  3106. /** Inserts a new element into the array, assuming that the array is sorted.
  3107. This will use the DefaultElementComparator class for sorting, so your ElementType
  3108. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  3109. method will be unpredictable.
  3110. @param newElement the new element to insert to the array
  3111. @see addSorted, sort
  3112. */
  3113. void addUsingDefaultSort (ParameterType newElement)
  3114. {
  3115. DefaultElementComparator <ElementType> comparator;
  3116. addSorted (comparator, newElement);
  3117. }
  3118. /** Finds the index of an element in the array, assuming that the array is sorted.
  3119. This will use a comparator to do a binary-chop to find the index of the given
  3120. element, if it exists. If the array isn't sorted, the behaviour of this
  3121. method will be unpredictable.
  3122. @param comparator the comparator to use to compare the elements - see the sort()
  3123. method for details about the form this object should take
  3124. @param elementToLookFor the element to search for
  3125. @returns the index of the element, or -1 if it's not found
  3126. @see addSorted, sort
  3127. */
  3128. template <class ElementComparator>
  3129. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  3130. {
  3131. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3132. // avoids getting warning messages about the parameter being unused
  3133. const ScopedLockType lock (getLock());
  3134. int start = 0;
  3135. int end = numUsed;
  3136. for (;;)
  3137. {
  3138. if (start >= end)
  3139. {
  3140. return -1;
  3141. }
  3142. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  3143. {
  3144. return start;
  3145. }
  3146. else
  3147. {
  3148. const int halfway = (start + end) >> 1;
  3149. if (halfway == start)
  3150. return -1;
  3151. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  3152. start = halfway;
  3153. else
  3154. end = halfway;
  3155. }
  3156. }
  3157. }
  3158. /** Removes an element from the array.
  3159. This will remove the element at a given index, and move back
  3160. all the subsequent elements to close the gap.
  3161. If the index passed in is out-of-range, nothing will happen.
  3162. @param indexToRemove the index of the element to remove
  3163. @returns the element that has been removed
  3164. @see removeValue, removeRange
  3165. */
  3166. ElementType remove (const int indexToRemove)
  3167. {
  3168. const ScopedLockType lock (getLock());
  3169. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  3170. {
  3171. --numUsed;
  3172. ElementType* const e = data.elements + indexToRemove;
  3173. ElementType removed (*e);
  3174. e->~ElementType();
  3175. const int numberToShift = numUsed - indexToRemove;
  3176. if (numberToShift > 0)
  3177. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  3178. if ((numUsed << 1) < data.numAllocated)
  3179. minimiseStorageOverheads();
  3180. return removed;
  3181. }
  3182. else
  3183. {
  3184. return ElementType();
  3185. }
  3186. }
  3187. /** Removes an item from the array.
  3188. This will remove the first occurrence of the given element from the array.
  3189. If the item isn't found, no action is taken.
  3190. @param valueToRemove the object to try to remove
  3191. @see remove, removeRange
  3192. */
  3193. void removeValue (ParameterType valueToRemove)
  3194. {
  3195. const ScopedLockType lock (getLock());
  3196. ElementType* e = data.elements;
  3197. for (int i = numUsed; --i >= 0;)
  3198. {
  3199. if (valueToRemove == *e)
  3200. {
  3201. remove (static_cast <int> (e - data.elements.getData()));
  3202. break;
  3203. }
  3204. ++e;
  3205. }
  3206. }
  3207. /** Removes a range of elements from the array.
  3208. This will remove a set of elements, starting from the given index,
  3209. and move subsequent elements down to close the gap.
  3210. If the range extends beyond the bounds of the array, it will
  3211. be safely clipped to the size of the array.
  3212. @param startIndex the index of the first element to remove
  3213. @param numberToRemove how many elements should be removed
  3214. @see remove, removeValue
  3215. */
  3216. void removeRange (int startIndex, int numberToRemove)
  3217. {
  3218. const ScopedLockType lock (getLock());
  3219. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3220. startIndex = jlimit (0, numUsed, startIndex);
  3221. if (endIndex > startIndex)
  3222. {
  3223. ElementType* const e = data.elements + startIndex;
  3224. numberToRemove = endIndex - startIndex;
  3225. for (int i = 0; i < numberToRemove; ++i)
  3226. e[i].~ElementType();
  3227. const int numToShift = numUsed - endIndex;
  3228. if (numToShift > 0)
  3229. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  3230. numUsed -= numberToRemove;
  3231. if ((numUsed << 1) < data.numAllocated)
  3232. minimiseStorageOverheads();
  3233. }
  3234. }
  3235. /** Removes the last n elements from the array.
  3236. @param howManyToRemove how many elements to remove from the end of the array
  3237. @see remove, removeValue, removeRange
  3238. */
  3239. void removeLast (int howManyToRemove = 1)
  3240. {
  3241. const ScopedLockType lock (getLock());
  3242. if (howManyToRemove > numUsed)
  3243. howManyToRemove = numUsed;
  3244. for (int i = 0; i < howManyToRemove; ++i)
  3245. data.elements [numUsed - i].~ElementType();
  3246. numUsed -= howManyToRemove;
  3247. if ((numUsed << 1) < data.numAllocated)
  3248. minimiseStorageOverheads();
  3249. }
  3250. /** Removes any elements which are also in another array.
  3251. @param otherArray the other array in which to look for elements to remove
  3252. @see removeValuesNotIn, remove, removeValue, removeRange
  3253. */
  3254. template <class OtherArrayType>
  3255. void removeValuesIn (const OtherArrayType& otherArray)
  3256. {
  3257. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3258. const ScopedLockType lock2 (getLock());
  3259. if (this == &otherArray)
  3260. {
  3261. clear();
  3262. }
  3263. else
  3264. {
  3265. if (otherArray.size() > 0)
  3266. {
  3267. for (int i = numUsed; --i >= 0;)
  3268. if (otherArray.contains (data.elements [i]))
  3269. remove (i);
  3270. }
  3271. }
  3272. }
  3273. /** Removes any elements which are not found in another array.
  3274. Only elements which occur in this other array will be retained.
  3275. @param otherArray the array in which to look for elements NOT to remove
  3276. @see removeValuesIn, remove, removeValue, removeRange
  3277. */
  3278. template <class OtherArrayType>
  3279. void removeValuesNotIn (const OtherArrayType& otherArray)
  3280. {
  3281. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3282. const ScopedLockType lock2 (getLock());
  3283. if (this != &otherArray)
  3284. {
  3285. if (otherArray.size() <= 0)
  3286. {
  3287. clear();
  3288. }
  3289. else
  3290. {
  3291. for (int i = numUsed; --i >= 0;)
  3292. if (! otherArray.contains (data.elements [i]))
  3293. remove (i);
  3294. }
  3295. }
  3296. }
  3297. /** Swaps over two elements in the array.
  3298. This swaps over the elements found at the two indexes passed in.
  3299. If either index is out-of-range, this method will do nothing.
  3300. @param index1 index of one of the elements to swap
  3301. @param index2 index of the other element to swap
  3302. */
  3303. void swap (const int index1,
  3304. const int index2)
  3305. {
  3306. const ScopedLockType lock (getLock());
  3307. if (((unsigned int) index1) < (unsigned int) numUsed
  3308. && ((unsigned int) index2) < (unsigned int) numUsed)
  3309. {
  3310. swapVariables (data.elements [index1],
  3311. data.elements [index2]);
  3312. }
  3313. }
  3314. /** Moves one of the values to a different position.
  3315. This will move the value to a specified index, shuffling along
  3316. any intervening elements as required.
  3317. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3318. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3319. @param currentIndex the index of the value to be moved. If this isn't a
  3320. valid index, then nothing will be done
  3321. @param newIndex the index at which you'd like this value to end up. If this
  3322. is less than zero, the value will be moved to the end
  3323. of the array
  3324. */
  3325. void move (const int currentIndex, int newIndex) throw()
  3326. {
  3327. if (currentIndex != newIndex)
  3328. {
  3329. const ScopedLockType lock (getLock());
  3330. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3331. {
  3332. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3333. newIndex = numUsed - 1;
  3334. char tempCopy [sizeof (ElementType)];
  3335. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  3336. if (newIndex > currentIndex)
  3337. {
  3338. memmove (data.elements + currentIndex,
  3339. data.elements + currentIndex + 1,
  3340. (newIndex - currentIndex) * sizeof (ElementType));
  3341. }
  3342. else
  3343. {
  3344. memmove (data.elements + newIndex + 1,
  3345. data.elements + newIndex,
  3346. (currentIndex - newIndex) * sizeof (ElementType));
  3347. }
  3348. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  3349. }
  3350. }
  3351. }
  3352. /** Reduces the amount of storage being used by the array.
  3353. Arrays typically allocate slightly more storage than they need, and after
  3354. removing elements, they may have quite a lot of unused space allocated.
  3355. This method will reduce the amount of allocated storage to a minimum.
  3356. */
  3357. void minimiseStorageOverheads()
  3358. {
  3359. const ScopedLockType lock (getLock());
  3360. data.shrinkToNoMoreThan (numUsed);
  3361. }
  3362. /** Increases the array's internal storage to hold a minimum number of elements.
  3363. Calling this before adding a large known number of elements means that
  3364. the array won't have to keep dynamically resizing itself as the elements
  3365. are added, and it'll therefore be more efficient.
  3366. */
  3367. void ensureStorageAllocated (const int minNumElements)
  3368. {
  3369. const ScopedLockType lock (getLock());
  3370. data.ensureAllocatedSize (minNumElements);
  3371. }
  3372. /** Sorts the elements in the array.
  3373. This will use a comparator object to sort the elements into order. The object
  3374. passed must have a method of the form:
  3375. @code
  3376. int compareElements (ElementType first, ElementType second);
  3377. @endcode
  3378. ..and this method must return:
  3379. - a value of < 0 if the first comes before the second
  3380. - a value of 0 if the two objects are equivalent
  3381. - a value of > 0 if the second comes before the first
  3382. To improve performance, the compareElements() method can be declared as static or const.
  3383. @param comparator the comparator to use for comparing elements.
  3384. @param retainOrderOfEquivalentItems if this is true, then items
  3385. which the comparator says are equivalent will be
  3386. kept in the order in which they currently appear
  3387. in the array. This is slower to perform, but may
  3388. be important in some cases. If it's false, a faster
  3389. algorithm is used, but equivalent elements may be
  3390. rearranged.
  3391. @see addSorted, indexOfSorted, sortArray
  3392. */
  3393. template <class ElementComparator>
  3394. void sort (ElementComparator& comparator,
  3395. const bool retainOrderOfEquivalentItems = false) const
  3396. {
  3397. const ScopedLockType lock (getLock());
  3398. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3399. // avoids getting warning messages about the parameter being unused
  3400. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  3401. }
  3402. /** Returns the CriticalSection that locks this array.
  3403. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  3404. an object of ScopedLockType as an RAII lock for it.
  3405. */
  3406. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  3407. /** Returns the type of scoped lock to use for locking this array */
  3408. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  3409. juce_UseDebuggingNewOperator
  3410. private:
  3411. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  3412. int numUsed;
  3413. };
  3414. #endif // __JUCE_ARRAY_JUCEHEADER__
  3415. /*** End of inlined file: juce_Array.h ***/
  3416. #endif
  3417. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3418. #endif
  3419. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3420. /*** Start of inlined file: juce_BigInteger.h ***/
  3421. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3422. #define __JUCE_BIGINTEGER_JUCEHEADER__
  3423. class MemoryBlock;
  3424. /**
  3425. An arbitrarily large integer class.
  3426. A BigInteger can be used in a similar way to a normal integer, but has no size
  3427. limit (except for memory and performance constraints).
  3428. Negative values are possible, but the value isn't stored as 2s-complement, so
  3429. be careful if you use negative values and look at the values of individual bits.
  3430. */
  3431. class JUCE_API BigInteger
  3432. {
  3433. public:
  3434. /** Creates an empty BigInteger */
  3435. BigInteger();
  3436. /** Creates a BigInteger containing an integer value in its low bits.
  3437. The low 32 bits of the number are initialised with this value.
  3438. */
  3439. BigInteger (unsigned int value);
  3440. /** Creates a BigInteger containing an integer value in its low bits.
  3441. The low 32 bits of the number are initialised with the absolute value
  3442. passed in, and its sign is set to reflect the sign of the number.
  3443. */
  3444. BigInteger (int value);
  3445. /** Creates a BigInteger containing an integer value in its low bits.
  3446. The low 64 bits of the number are initialised with the absolute value
  3447. passed in, and its sign is set to reflect the sign of the number.
  3448. */
  3449. BigInteger (int64 value);
  3450. /** Creates a copy of another BigInteger. */
  3451. BigInteger (const BigInteger& other);
  3452. /** Destructor. */
  3453. ~BigInteger();
  3454. /** Copies another BigInteger onto this one. */
  3455. BigInteger& operator= (const BigInteger& other);
  3456. /** Swaps the internal contents of this with another object. */
  3457. void swapWith (BigInteger& other) throw();
  3458. /** Returns the value of a specified bit in the number.
  3459. If the index is out-of-range, the result will be false.
  3460. */
  3461. bool operator[] (int bit) const throw();
  3462. /** Returns true if no bits are set. */
  3463. bool isZero() const throw();
  3464. /** Returns true if the value is 1. */
  3465. bool isOne() const throw();
  3466. /** Attempts to get the lowest bits of the value as an integer.
  3467. If the value is bigger than the integer limits, this will return only the lower bits.
  3468. */
  3469. int toInteger() const throw();
  3470. /** Resets the value to 0. */
  3471. void clear();
  3472. /** Clears a particular bit in the number. */
  3473. void clearBit (int bitNumber) throw();
  3474. /** Sets a specified bit to 1. */
  3475. void setBit (int bitNumber);
  3476. /** Sets or clears a specified bit. */
  3477. void setBit (int bitNumber, bool shouldBeSet);
  3478. /** Sets a range of bits to be either on or off.
  3479. @param startBit the first bit to change
  3480. @param numBits the number of bits to change
  3481. @param shouldBeSet whether to turn these bits on or off
  3482. */
  3483. void setRange (int startBit, int numBits, bool shouldBeSet);
  3484. /** Inserts a bit an a given position, shifting up any bits above it. */
  3485. void insertBit (int bitNumber, bool shouldBeSet);
  3486. /** Returns a range of bits as a new BigInteger.
  3487. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3488. @see getBitRangeAsInt
  3489. */
  3490. const BigInteger getBitRange (int startBit, int numBits) const;
  3491. /** Returns a range of bits as an integer value.
  3492. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3493. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3494. getBitRange().
  3495. */
  3496. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3497. /** Sets a range of bits to an integer value.
  3498. Copies the given integer onto a range of bits, starting at startBit,
  3499. and using up to numBits of the available bits.
  3500. */
  3501. void setBitRangeAsInt (int startBit, int numBits, unsigned int valueToSet);
  3502. /** Shifts a section of bits left or right.
  3503. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3504. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3505. */
  3506. void shiftBits (int howManyBitsLeft, int startBit);
  3507. /** Returns the total number of set bits in the value. */
  3508. int countNumberOfSetBits() const throw();
  3509. /** Looks for the index of the next set bit after a given starting point.
  3510. This searches from startIndex (inclusive) upwards for the first set bit,
  3511. and returns its index. If no set bits are found, it returns -1.
  3512. */
  3513. int findNextSetBit (int startIndex = 0) const throw();
  3514. /** Looks for the index of the next clear bit after a given starting point.
  3515. This searches from startIndex (inclusive) upwards for the first clear bit,
  3516. and returns its index.
  3517. */
  3518. int findNextClearBit (int startIndex = 0) const throw();
  3519. /** Returns the index of the highest set bit in the number.
  3520. If the value is zero, this will return -1.
  3521. */
  3522. int getHighestBit() const throw();
  3523. // All the standard arithmetic ops...
  3524. BigInteger& operator+= (const BigInteger& other);
  3525. BigInteger& operator-= (const BigInteger& other);
  3526. BigInteger& operator*= (const BigInteger& other);
  3527. BigInteger& operator/= (const BigInteger& other);
  3528. BigInteger& operator|= (const BigInteger& other);
  3529. BigInteger& operator&= (const BigInteger& other);
  3530. BigInteger& operator^= (const BigInteger& other);
  3531. BigInteger& operator%= (const BigInteger& other);
  3532. BigInteger& operator<<= (int numBitsToShift);
  3533. BigInteger& operator>>= (int numBitsToShift);
  3534. BigInteger& operator++();
  3535. BigInteger& operator--();
  3536. const BigInteger operator++ (int);
  3537. const BigInteger operator-- (int);
  3538. const BigInteger operator-() const;
  3539. const BigInteger operator+ (const BigInteger& other) const;
  3540. const BigInteger operator- (const BigInteger& other) const;
  3541. const BigInteger operator* (const BigInteger& other) const;
  3542. const BigInteger operator/ (const BigInteger& other) const;
  3543. const BigInteger operator| (const BigInteger& other) const;
  3544. const BigInteger operator& (const BigInteger& other) const;
  3545. const BigInteger operator^ (const BigInteger& other) const;
  3546. const BigInteger operator% (const BigInteger& other) const;
  3547. const BigInteger operator<< (int numBitsToShift) const;
  3548. const BigInteger operator>> (int numBitsToShift) const;
  3549. bool operator== (const BigInteger& other) const throw();
  3550. bool operator!= (const BigInteger& other) const throw();
  3551. bool operator< (const BigInteger& other) const throw();
  3552. bool operator<= (const BigInteger& other) const throw();
  3553. bool operator> (const BigInteger& other) const throw();
  3554. bool operator>= (const BigInteger& other) const throw();
  3555. /** Does a signed comparison of two BigIntegers.
  3556. Return values are:
  3557. - 0 if the numbers are the same
  3558. - < 0 if this number is smaller than the other
  3559. - > 0 if this number is bigger than the other
  3560. */
  3561. int compare (const BigInteger& other) const throw();
  3562. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  3563. Return values are:
  3564. - 0 if the numbers are the same
  3565. - < 0 if this number is smaller than the other
  3566. - > 0 if this number is bigger than the other
  3567. */
  3568. int compareAbsolute (const BigInteger& other) const throw();
  3569. /** Divides this value by another one and returns the remainder.
  3570. This number is divided by other, leaving the quotient in this number,
  3571. with the remainder being copied to the other BigInteger passed in.
  3572. */
  3573. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  3574. /** Returns the largest value that will divide both this value and the one passed-in.
  3575. */
  3576. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  3577. /** Performs a combined exponent and modulo operation.
  3578. This BigInteger's value becomes (this ^ exponent) % modulus.
  3579. */
  3580. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  3581. /** Performs an inverse modulo on the value.
  3582. i.e. the result is (this ^ -1) mod (modulus).
  3583. */
  3584. void inverseModulo (const BigInteger& modulus);
  3585. /** Returns true if the value is less than zero.
  3586. @see setNegative, negate
  3587. */
  3588. bool isNegative() const throw();
  3589. /** Changes the sign of the number to be positive or negative.
  3590. @see isNegative, negate
  3591. */
  3592. void setNegative (const bool shouldBeNegative) throw();
  3593. /** Inverts the sign of the number.
  3594. @see isNegative, setNegative
  3595. */
  3596. void negate() throw();
  3597. /** Converts the number to a string.
  3598. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3599. If minimumNumCharacters is greater than 0, the returned string will be
  3600. padded with leading zeros to reach at least that length.
  3601. */
  3602. const String toString (int base, int minimumNumCharacters = 1) const;
  3603. /** Reads the numeric value from a string.
  3604. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3605. Any invalid characters will be ignored.
  3606. */
  3607. void parseString (const String& text, int base);
  3608. /** Turns the number into a block of binary data.
  3609. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3610. of the number, and so on.
  3611. @see loadFromMemoryBlock
  3612. */
  3613. const MemoryBlock toMemoryBlock() const;
  3614. /** Converts a block of raw data into a number.
  3615. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3616. of the number, and so on.
  3617. @see toMemoryBlock
  3618. */
  3619. void loadFromMemoryBlock (const MemoryBlock& data);
  3620. juce_UseDebuggingNewOperator
  3621. private:
  3622. HeapBlock <unsigned int> values;
  3623. int numValues, highestBit;
  3624. bool negative;
  3625. void ensureSize (int numVals);
  3626. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  3627. };
  3628. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  3629. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  3630. /** For backwards compatibility, BitArray is defined to be an alias for BigInteger.
  3631. */
  3632. typedef BigInteger BitArray;
  3633. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  3634. /*** End of inlined file: juce_BigInteger.h ***/
  3635. #endif
  3636. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3637. /*** Start of inlined file: juce_DynamicObject.h ***/
  3638. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3639. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3640. /*** Start of inlined file: juce_NamedValueSet.h ***/
  3641. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  3642. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  3643. /*** Start of inlined file: juce_Variant.h ***/
  3644. #ifndef __JUCE_VARIANT_JUCEHEADER__
  3645. #define __JUCE_VARIANT_JUCEHEADER__
  3646. /*** Start of inlined file: juce_Identifier.h ***/
  3647. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  3648. #define __JUCE_IDENTIFIER_JUCEHEADER__
  3649. /**
  3650. Represents a string identifier, designed for accessing properties by name.
  3651. Identifier objects are very light and fast to copy, but slower to initialise
  3652. from a string, so it's much faster to keep a static identifier object to refer
  3653. to frequently-used names, rather than constructing them each time you need it.
  3654. @see NamedPropertySet, ValueTree
  3655. */
  3656. class JUCE_API Identifier
  3657. {
  3658. public:
  3659. /** Creates a null identifier. */
  3660. Identifier() throw();
  3661. /** Creates an identifier with a specified name.
  3662. Because this name may need to be used in contexts such as script variables or XML
  3663. tags, it must only contain ascii letters and digits, or the underscore character.
  3664. */
  3665. Identifier (const char* name);
  3666. /** Creates an identifier with a specified name.
  3667. Because this name may need to be used in contexts such as script variables or XML
  3668. tags, it must only contain ascii letters and digits, or the underscore character.
  3669. */
  3670. Identifier (const String& name);
  3671. /** Creates a copy of another identifier. */
  3672. Identifier (const Identifier& other) throw();
  3673. /** Creates a copy of another identifier. */
  3674. Identifier& operator= (const Identifier& other) throw();
  3675. /** Destructor */
  3676. ~Identifier();
  3677. /** Compares two identifiers. This is a very fast operation. */
  3678. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  3679. /** Compares two identifiers. This is a very fast operation. */
  3680. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  3681. /** Returns this identifier as a string. */
  3682. const String toString() const { return name; }
  3683. /** Returns this identifier's raw string pointer. */
  3684. operator const juce_wchar*() const throw() { return name; }
  3685. private:
  3686. const juce_wchar* name;
  3687. class Pool;
  3688. };
  3689. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  3690. /*** End of inlined file: juce_Identifier.h ***/
  3691. /*** Start of inlined file: juce_OutputStream.h ***/
  3692. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3693. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3694. /*** Start of inlined file: juce_InputStream.h ***/
  3695. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  3696. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  3697. /*** Start of inlined file: juce_MemoryBlock.h ***/
  3698. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3699. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  3700. /**
  3701. A class to hold a resizable block of raw data.
  3702. */
  3703. class JUCE_API MemoryBlock
  3704. {
  3705. public:
  3706. /** Create an uninitialised block with 0 size. */
  3707. MemoryBlock() throw();
  3708. /** Creates a memory block with a given initial size.
  3709. @param initialSize the size of block to create
  3710. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  3711. */
  3712. MemoryBlock (const size_t initialSize,
  3713. const bool initialiseToZero = false) throw();
  3714. /** Creates a copy of another memory block. */
  3715. MemoryBlock (const MemoryBlock& other) throw();
  3716. /** Creates a memory block using a copy of a block of data.
  3717. @param dataToInitialiseFrom some data to copy into this block
  3718. @param sizeInBytes how much space to use
  3719. */
  3720. MemoryBlock (const void* const dataToInitialiseFrom,
  3721. const size_t sizeInBytes) throw();
  3722. /** Destructor. */
  3723. ~MemoryBlock() throw();
  3724. /** Copies another memory block onto this one.
  3725. This block will be resized and copied to exactly match the other one.
  3726. */
  3727. MemoryBlock& operator= (const MemoryBlock& other) throw();
  3728. /** Compares two memory blocks.
  3729. @returns true only if the two blocks are the same size and have identical contents.
  3730. */
  3731. bool operator== (const MemoryBlock& other) const throw();
  3732. /** Compares two memory blocks.
  3733. @returns true if the two blocks are different sizes or have different contents.
  3734. */
  3735. bool operator!= (const MemoryBlock& other) const throw();
  3736. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  3737. */
  3738. bool matches (const void* data, size_t dataSize) const throw();
  3739. /** Returns a void pointer to the data.
  3740. Note that the pointer returned will probably become invalid when the
  3741. block is resized.
  3742. */
  3743. void* getData() const throw() { return data; }
  3744. /** Returns a byte from the memory block.
  3745. This returns a reference, so you can also use it to set a byte.
  3746. */
  3747. template <typename Type>
  3748. char& operator[] (const Type offset) const throw() { return data [offset]; }
  3749. /** Returns the block's current allocated size, in bytes. */
  3750. size_t getSize() const throw() { return size; }
  3751. /** Resizes the memory block.
  3752. This will try to keep as much of the block's current content as it can,
  3753. and can optionally be made to clear any new space that gets allocated at
  3754. the end of the block.
  3755. @param newSize the new desired size for the block
  3756. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3757. whether to clear the new section or just leave it
  3758. uninitialised
  3759. @see ensureSize
  3760. */
  3761. void setSize (const size_t newSize,
  3762. const bool initialiseNewSpaceToZero = false) throw();
  3763. /** Increases the block's size only if it's smaller than a given size.
  3764. @param minimumSize if the block is already bigger than this size, no action
  3765. will be taken; otherwise it will be increased to this size
  3766. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3767. whether to clear the new section or just leave it
  3768. uninitialised
  3769. @see setSize
  3770. */
  3771. void ensureSize (const size_t minimumSize,
  3772. const bool initialiseNewSpaceToZero = false) throw();
  3773. /** Fills the entire memory block with a repeated byte value.
  3774. This is handy for clearing a block of memory to zero.
  3775. */
  3776. void fillWith (const uint8 valueToUse) throw();
  3777. /** Adds another block of data to the end of this one.
  3778. This block's size will be increased accordingly.
  3779. */
  3780. void append (const void* const data,
  3781. const size_t numBytes) throw();
  3782. /** Exchanges the contents of this and another memory block.
  3783. No actual copying is required for this, so it's very fast.
  3784. */
  3785. void swapWith (MemoryBlock& other) throw();
  3786. /** Copies data into this MemoryBlock from a memory address.
  3787. @param srcData the memory location of the data to copy into this block
  3788. @param destinationOffset the offset in this block at which the data being copied should begin
  3789. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  3790. it will be clipped so not to do anything nasty)
  3791. */
  3792. void copyFrom (const void* srcData,
  3793. int destinationOffset,
  3794. size_t numBytes) throw();
  3795. /** Copies data from this MemoryBlock to a memory address.
  3796. @param destData the memory location to write to
  3797. @param sourceOffset the offset within this block from which the copied data will be read
  3798. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  3799. zeros will be used for that portion of the data)
  3800. */
  3801. void copyTo (void* destData,
  3802. int sourceOffset,
  3803. size_t numBytes) const throw();
  3804. /** Chops out a section of the block.
  3805. This will remove a section of the memory block and close the gap around it,
  3806. shifting any subsequent data downwards and reducing the size of the block.
  3807. If the range specified goes beyond the size of the block, it will be clipped.
  3808. */
  3809. void removeSection (size_t startByte, size_t numBytesToRemove) throw();
  3810. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  3811. characters in the system's default encoding. */
  3812. const String toString() const throw();
  3813. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  3814. The block will be resized to the number of valid bytes read from the string.
  3815. Non-hex characters in the string will be ignored.
  3816. @see String::toHexString()
  3817. */
  3818. void loadFromHexString (const String& sourceHexString) throw();
  3819. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  3820. void setBitRange (size_t bitRangeStart,
  3821. size_t numBits,
  3822. int binaryNumberToApply) throw();
  3823. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  3824. int getBitRange (size_t bitRangeStart,
  3825. size_t numBitsToRead) const throw();
  3826. /** Returns a string of characters that represent the binary contents of this block.
  3827. Uses a 64-bit encoding system to allow binary data to be turned into a string
  3828. of simple non-extended characters, e.g. for storage in XML.
  3829. @see fromBase64Encoding
  3830. */
  3831. const String toBase64Encoding() const throw();
  3832. /** Takes a string of encoded characters and turns it into binary data.
  3833. The string passed in must have been created by to64BitEncoding(), and this
  3834. block will be resized to recreate the original data block.
  3835. @see toBase64Encoding
  3836. */
  3837. bool fromBase64Encoding (const String& encodedString) throw();
  3838. juce_UseDebuggingNewOperator
  3839. private:
  3840. HeapBlock <char> data;
  3841. size_t size;
  3842. };
  3843. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  3844. /*** End of inlined file: juce_MemoryBlock.h ***/
  3845. /** The base class for streams that read data.
  3846. Input and output streams are used throughout the library - subclasses can override
  3847. some or all of the virtual functions to implement their behaviour.
  3848. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  3849. */
  3850. class JUCE_API InputStream
  3851. {
  3852. public:
  3853. /** Destructor. */
  3854. virtual ~InputStream() {}
  3855. /** Returns the total number of bytes available for reading in this stream.
  3856. Note that this is the number of bytes available from the start of the
  3857. stream, not from the current position.
  3858. If the size of the stream isn't actually known, this may return -1.
  3859. */
  3860. virtual int64 getTotalLength() = 0;
  3861. /** Returns true if the stream has no more data to read. */
  3862. virtual bool isExhausted() = 0;
  3863. /** Reads a set of bytes from the stream into a memory buffer.
  3864. This is the only read method that subclasses actually need to implement, as the
  3865. InputStream base class implements the other read methods in terms of this one (although
  3866. it's often more efficient for subclasses to implement them directly).
  3867. @param destBuffer the destination buffer for the data
  3868. @param maxBytesToRead the maximum number of bytes to read - make sure the
  3869. memory block passed in is big enough to contain this
  3870. many bytes.
  3871. @returns the actual number of bytes that were read, which may be less than
  3872. maxBytesToRead if the stream is exhausted before it gets that far
  3873. */
  3874. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  3875. /** Reads a byte from the stream.
  3876. If the stream is exhausted, this will return zero.
  3877. @see OutputStream::writeByte
  3878. */
  3879. virtual char readByte();
  3880. /** Reads a boolean from the stream.
  3881. The bool is encoded as a single byte - 1 for true, 0 for false.
  3882. If the stream is exhausted, this will return false.
  3883. @see OutputStream::writeBool
  3884. */
  3885. virtual bool readBool();
  3886. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3887. If the next two bytes read are byte1 and byte2, this returns
  3888. (byte1 | (byte2 << 8)).
  3889. If the stream is exhausted partway through reading the bytes, this will return zero.
  3890. @see OutputStream::writeShort, readShortBigEndian
  3891. */
  3892. virtual short readShort();
  3893. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3894. If the next two bytes read are byte1 and byte2, this returns
  3895. (byte2 | (byte1 << 8)).
  3896. If the stream is exhausted partway through reading the bytes, this will return zero.
  3897. @see OutputStream::writeShortBigEndian, readShort
  3898. */
  3899. virtual short readShortBigEndian();
  3900. /** Reads four bytes from the stream as a little-endian 32-bit value.
  3901. If the next four bytes are byte1 to byte4, this returns
  3902. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  3903. If the stream is exhausted partway through reading the bytes, this will return zero.
  3904. @see OutputStream::writeInt, readIntBigEndian
  3905. */
  3906. virtual int readInt();
  3907. /** Reads four bytes from the stream as a big-endian 32-bit value.
  3908. If the next four bytes are byte1 to byte4, this returns
  3909. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  3910. If the stream is exhausted partway through reading the bytes, this will return zero.
  3911. @see OutputStream::writeIntBigEndian, readInt
  3912. */
  3913. virtual int readIntBigEndian();
  3914. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  3915. If the next eight bytes are byte1 to byte8, this returns
  3916. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  3917. If the stream is exhausted partway through reading the bytes, this will return zero.
  3918. @see OutputStream::writeInt64, readInt64BigEndian
  3919. */
  3920. virtual int64 readInt64();
  3921. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  3922. If the next eight bytes are byte1 to byte8, this returns
  3923. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  3924. If the stream is exhausted partway through reading the bytes, this will return zero.
  3925. @see OutputStream::writeInt64BigEndian, readInt64
  3926. */
  3927. virtual int64 readInt64BigEndian();
  3928. /** Reads four bytes as a 32-bit floating point value.
  3929. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  3930. If the stream is exhausted partway through reading the bytes, this will return zero.
  3931. @see OutputStream::writeFloat, readDouble
  3932. */
  3933. virtual float readFloat();
  3934. /** Reads four bytes as a 32-bit floating point value.
  3935. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  3936. If the stream is exhausted partway through reading the bytes, this will return zero.
  3937. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  3938. */
  3939. virtual float readFloatBigEndian();
  3940. /** Reads eight bytes as a 64-bit floating point value.
  3941. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  3942. If the stream is exhausted partway through reading the bytes, this will return zero.
  3943. @see OutputStream::writeDouble, readFloat
  3944. */
  3945. virtual double readDouble();
  3946. /** Reads eight bytes as a 64-bit floating point value.
  3947. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  3948. If the stream is exhausted partway through reading the bytes, this will return zero.
  3949. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  3950. */
  3951. virtual double readDoubleBigEndian();
  3952. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  3953. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  3954. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  3955. @see OutputStream::writeCompressedInt()
  3956. */
  3957. virtual int readCompressedInt();
  3958. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  3959. This will read up to the next "\n" or "\r\n" or end-of-stream.
  3960. After this call, the stream's position will be left pointing to the next character
  3961. following the line-feed, but the linefeeds aren't included in the string that
  3962. is returned.
  3963. */
  3964. virtual const String readNextLine();
  3965. /** Reads a zero-terminated UTF8 string from the stream.
  3966. This will read characters from the stream until it hits a zero character or
  3967. end-of-stream.
  3968. @see OutputStream::writeString, readEntireStreamAsString
  3969. */
  3970. virtual const String readString();
  3971. /** Tries to read the whole stream and turn it into a string.
  3972. This will read from the stream's current position until the end-of-stream, and
  3973. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  3974. */
  3975. virtual const String readEntireStreamAsString();
  3976. /** Reads from the stream and appends the data to a MemoryBlock.
  3977. @param destBlock the block to append the data onto
  3978. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  3979. of bytes that will be read - if it's negative, data
  3980. will be read until the stream is exhausted.
  3981. @returns the number of bytes that were added to the memory block
  3982. */
  3983. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  3984. int maxNumBytesToRead = -1);
  3985. /** Returns the offset of the next byte that will be read from the stream.
  3986. @see setPosition
  3987. */
  3988. virtual int64 getPosition() = 0;
  3989. /** Tries to move the current read position of the stream.
  3990. The position is an absolute number of bytes from the stream's start.
  3991. Some streams might not be able to do this, in which case they should do
  3992. nothing and return false. Others might be able to manage it by resetting
  3993. themselves and skipping to the correct position, although this is
  3994. obviously a bit slow.
  3995. @returns true if the stream manages to reposition itself correctly
  3996. @see getPosition
  3997. */
  3998. virtual bool setPosition (int64 newPosition) = 0;
  3999. /** Reads and discards a number of bytes from the stream.
  4000. Some input streams might implement this efficiently, but the base
  4001. class will just keep reading data until the requisite number of bytes
  4002. have been done.
  4003. */
  4004. virtual void skipNextBytes (int64 numBytesToSkip);
  4005. juce_UseDebuggingNewOperator
  4006. protected:
  4007. InputStream() throw() {}
  4008. };
  4009. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  4010. /*** End of inlined file: juce_InputStream.h ***/
  4011. class File;
  4012. /**
  4013. The base class for streams that write data to some kind of destination.
  4014. Input and output streams are used throughout the library - subclasses can override
  4015. some or all of the virtual functions to implement their behaviour.
  4016. @see InputStream, MemoryOutputStream, FileOutputStream
  4017. */
  4018. class JUCE_API OutputStream
  4019. {
  4020. protected:
  4021. OutputStream();
  4022. public:
  4023. /** Destructor.
  4024. Some subclasses might want to do things like call flush() during their
  4025. destructors.
  4026. */
  4027. virtual ~OutputStream();
  4028. /** If the stream is using a buffer, this will ensure it gets written
  4029. out to the destination. */
  4030. virtual void flush() = 0;
  4031. /** Tries to move the stream's output position.
  4032. Not all streams will be able to seek to a new position - this will return
  4033. false if it fails to work.
  4034. @see getPosition
  4035. */
  4036. virtual bool setPosition (int64 newPosition) = 0;
  4037. /** Returns the stream's current position.
  4038. @see setPosition
  4039. */
  4040. virtual int64 getPosition() = 0;
  4041. /** Writes a block of data to the stream.
  4042. When creating a subclass of OutputStream, this is the only write method
  4043. that needs to be overloaded - the base class has methods for writing other
  4044. types of data which use this to do the work.
  4045. @returns false if the write operation fails for some reason
  4046. */
  4047. virtual bool write (const void* dataToWrite,
  4048. int howManyBytes) = 0;
  4049. /** Writes a single byte to the stream.
  4050. @see InputStream::readByte
  4051. */
  4052. virtual void writeByte (char byte);
  4053. /** Writes a boolean to the stream as a single byte.
  4054. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  4055. @see InputStream::readBool
  4056. */
  4057. virtual void writeBool (bool boolValue);
  4058. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  4059. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  4060. @see InputStream::readShort
  4061. */
  4062. virtual void writeShort (short value);
  4063. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  4064. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  4065. @see InputStream::readShortBigEndian
  4066. */
  4067. virtual void writeShortBigEndian (short value);
  4068. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  4069. @see InputStream::readInt
  4070. */
  4071. virtual void writeInt (int value);
  4072. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  4073. @see InputStream::readIntBigEndian
  4074. */
  4075. virtual void writeIntBigEndian (int value);
  4076. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  4077. @see InputStream::readInt64
  4078. */
  4079. virtual void writeInt64 (int64 value);
  4080. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  4081. @see InputStream::readInt64BigEndian
  4082. */
  4083. virtual void writeInt64BigEndian (int64 value);
  4084. /** Writes a 32-bit floating point value to the stream in a binary format.
  4085. The binary 32-bit encoding of the float is written as a little-endian int.
  4086. @see InputStream::readFloat
  4087. */
  4088. virtual void writeFloat (float value);
  4089. /** Writes a 32-bit floating point value to the stream in a binary format.
  4090. The binary 32-bit encoding of the float is written as a big-endian int.
  4091. @see InputStream::readFloatBigEndian
  4092. */
  4093. virtual void writeFloatBigEndian (float value);
  4094. /** Writes a 64-bit floating point value to the stream in a binary format.
  4095. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  4096. @see InputStream::readDouble
  4097. */
  4098. virtual void writeDouble (double value);
  4099. /** Writes a 64-bit floating point value to the stream in a binary format.
  4100. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  4101. @see InputStream::readDoubleBigEndian
  4102. */
  4103. virtual void writeDoubleBigEndian (double value);
  4104. /** Writes a condensed binary encoding of a 32-bit integer.
  4105. If you're storing a lot of integers which are unlikely to have very large values,
  4106. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  4107. under 0xffff only 3 bytes, etc.
  4108. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4109. @see InputStream::readCompressedInt
  4110. */
  4111. virtual void writeCompressedInt (int value);
  4112. /** Stores a string in the stream in a binary format.
  4113. This isn't the method to use if you're trying to append text to the end of a
  4114. text-file! It's intended for storing a string so that it can be retrieved later
  4115. by InputStream::readString().
  4116. It writes the string to the stream as UTF8, including the null termination character.
  4117. For appending text to a file, instead use writeText, or operator<<
  4118. @see InputStream::readString, writeText, operator<<
  4119. */
  4120. virtual void writeString (const String& text);
  4121. /** Writes a string of text to the stream.
  4122. It can either write it as UTF8 characters or as unicode, and
  4123. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  4124. should only be done at the start of a file).
  4125. The method also replaces '\\n' characters in the text with '\\r\\n'.
  4126. */
  4127. virtual void writeText (const String& text,
  4128. bool asUnicode,
  4129. bool writeUnicodeHeaderBytes);
  4130. /** Reads data from an input stream and writes it to this stream.
  4131. @param source the stream to read from
  4132. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  4133. less than zero, it will keep reading until the input
  4134. is exhausted)
  4135. */
  4136. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  4137. juce_UseDebuggingNewOperator
  4138. };
  4139. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4140. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  4141. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4142. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  4143. /** Writes a character to a stream. */
  4144. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  4145. /** Writes a null-terminated text string to a stream. */
  4146. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  4147. /** Writes a block of data from a MemoryBlock to a stream. */
  4148. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  4149. /** Writes the contents of a file to a stream. */
  4150. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  4151. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4152. /*** End of inlined file: juce_OutputStream.h ***/
  4153. class JUCE_API DynamicObject;
  4154. /**
  4155. A variant class, that can be used to hold a range of primitive values.
  4156. A var object can hold a range of simple primitive values, strings, or
  4157. a reference-counted pointer to a DynamicObject. The var class is intended
  4158. to act like the values used in dynamic scripting languages.
  4159. @see DynamicObject
  4160. */
  4161. class JUCE_API var
  4162. {
  4163. public:
  4164. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  4165. typedef Identifier identifier;
  4166. /** Creates a void variant. */
  4167. var() throw();
  4168. /** Destructor. */
  4169. ~var() throw();
  4170. /** A static var object that can be used where you need an empty variant object. */
  4171. static const var null;
  4172. var (const var& valueToCopy);
  4173. var (int value) throw();
  4174. var (bool value) throw();
  4175. var (double value) throw();
  4176. var (const char* value);
  4177. var (const juce_wchar* value);
  4178. var (const String& value);
  4179. var (DynamicObject* object);
  4180. var (MethodFunction method) throw();
  4181. var& operator= (const var& valueToCopy);
  4182. var& operator= (int value);
  4183. var& operator= (bool value);
  4184. var& operator= (double value);
  4185. var& operator= (const char* value);
  4186. var& operator= (const juce_wchar* value);
  4187. var& operator= (const String& value);
  4188. var& operator= (DynamicObject* object);
  4189. var& operator= (MethodFunction method);
  4190. void swapWith (var& other) throw();
  4191. operator int() const;
  4192. operator bool() const;
  4193. operator float() const;
  4194. operator double() const;
  4195. operator const String() const;
  4196. const String toString() const;
  4197. DynamicObject* getObject() const;
  4198. bool isVoid() const throw() { return type == voidType; }
  4199. bool isInt() const throw() { return type == intType; }
  4200. bool isBool() const throw() { return type == boolType; }
  4201. bool isDouble() const throw() { return type == doubleType; }
  4202. bool isString() const throw() { return type == stringType; }
  4203. bool isObject() const throw() { return type == objectType; }
  4204. bool isMethod() const throw() { return type == methodType; }
  4205. /** Writes a binary representation of this value to a stream.
  4206. The data can be read back later using readFromStream().
  4207. */
  4208. void writeToStream (OutputStream& output) const;
  4209. /** Reads back a stored binary representation of a value.
  4210. The data in the stream must have been written using writeToStream(), or this
  4211. will have unpredictable results.
  4212. */
  4213. static const var readFromStream (InputStream& input);
  4214. /** If this variant is an object, this returns one of its properties. */
  4215. const var operator[] (const Identifier& propertyName) const;
  4216. /** If this variant is an object, this invokes one of its methods with no arguments. */
  4217. const var call (const Identifier& method) const;
  4218. /** If this variant is an object, this invokes one of its methods with one argument. */
  4219. const var call (const Identifier& method, const var& arg1) const;
  4220. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  4221. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  4222. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  4223. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  4224. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  4225. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  4226. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  4227. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  4228. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  4229. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  4230. /** If this variant is a method pointer, this invokes it on a target object. */
  4231. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  4232. juce_UseDebuggingNewOperator
  4233. /** Returns true if this var has the same value as the one supplied. */
  4234. bool equals (const var& other) const throw();
  4235. private:
  4236. enum Type
  4237. {
  4238. voidType = 0,
  4239. intType,
  4240. boolType,
  4241. doubleType,
  4242. stringType,
  4243. objectType,
  4244. methodType
  4245. };
  4246. union ValueUnion
  4247. {
  4248. int intValue;
  4249. bool boolValue;
  4250. double doubleValue;
  4251. String* stringValue;
  4252. DynamicObject* objectValue;
  4253. MethodFunction methodValue;
  4254. };
  4255. Type type;
  4256. ValueUnion value;
  4257. };
  4258. bool operator== (const var& v1, const var& v2) throw();
  4259. bool operator!= (const var& v1, const var& v2) throw();
  4260. bool operator== (const var& v1, const String& v2) throw();
  4261. bool operator!= (const var& v1, const String& v2) throw();
  4262. #endif // __JUCE_VARIANT_JUCEHEADER__
  4263. /*** End of inlined file: juce_Variant.h ***/
  4264. /** Holds a set of named var objects.
  4265. This can be used as a basic structure to hold a set of var object, which can
  4266. be retrieved by using their identifier.
  4267. */
  4268. class JUCE_API NamedValueSet
  4269. {
  4270. public:
  4271. /** Creates an empty set. */
  4272. NamedValueSet() throw();
  4273. /** Creates a copy of another set. */
  4274. NamedValueSet (const NamedValueSet& other);
  4275. /** Replaces this set with a copy of another set. */
  4276. NamedValueSet& operator= (const NamedValueSet& other);
  4277. /** Destructor. */
  4278. ~NamedValueSet();
  4279. bool operator== (const NamedValueSet& other) const;
  4280. bool operator!= (const NamedValueSet& other) const;
  4281. /** Returns the total number of values that the set contains. */
  4282. int size() const throw();
  4283. /** Returns the value of a named item.
  4284. If the name isn't found, this will return a void variant.
  4285. @see getProperty
  4286. */
  4287. const var& operator[] (const Identifier& name) const;
  4288. /** Tries to return the named value, but if no such value is found, this will
  4289. instead return the supplied default value.
  4290. */
  4291. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  4292. /** Returns a pointer to the object holding a named value, or
  4293. null if there is no value with this name. */
  4294. var* getItem (const Identifier& name) const;
  4295. /** Changes or adds a named value.
  4296. @returns true if a value was changed or added; false if the
  4297. value was already set the the value passed-in.
  4298. */
  4299. bool set (const Identifier& name, const var& newValue);
  4300. /** Returns true if the set contains an item with the specified name. */
  4301. bool contains (const Identifier& name) const;
  4302. /** Removes a value from the set.
  4303. @returns true if a value was removed; false if there was no value
  4304. with the name that was given.
  4305. */
  4306. bool remove (const Identifier& name);
  4307. /** Returns the name of the value at a given index.
  4308. The index must be between 0 and size() - 1. Out-of-range indexes will
  4309. return an empty identifier.
  4310. */
  4311. const Identifier getName (int index) const;
  4312. /** Returns the value of the item at a given index.
  4313. The index must be between 0 and size() - 1. Out-of-range indexes will
  4314. return an empty identifier.
  4315. */
  4316. const var getValueAt (int index) const;
  4317. /** Removes all values. */
  4318. void clear();
  4319. juce_UseDebuggingNewOperator
  4320. private:
  4321. struct NamedValue
  4322. {
  4323. NamedValue() throw();
  4324. NamedValue (const Identifier& name, const var& value);
  4325. bool operator== (const NamedValue& other) const throw();
  4326. Identifier name;
  4327. var value;
  4328. };
  4329. Array <NamedValue> values;
  4330. };
  4331. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  4332. /*** End of inlined file: juce_NamedValueSet.h ***/
  4333. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  4334. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4335. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4336. /*** Start of inlined file: juce_Atomic.h ***/
  4337. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  4338. #define __JUCE_ATOMIC_JUCEHEADER__
  4339. /**
  4340. Simple class to hold a primitive value and perform atomic operations on it.
  4341. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  4342. There are methods to perform most of the basic atomic operations.
  4343. */
  4344. template <typename Type>
  4345. class Atomic
  4346. {
  4347. public:
  4348. /** Creates a new value, initialised to zero. */
  4349. inline Atomic() throw()
  4350. : value (0)
  4351. {
  4352. }
  4353. /** Creates a new value, with a given initial value. */
  4354. inline Atomic (const Type initialValue) throw()
  4355. : value (initialValue)
  4356. {
  4357. }
  4358. /** Copies another value (atomically). */
  4359. inline Atomic (const Atomic& other) throw()
  4360. : value (other.get())
  4361. {
  4362. }
  4363. /** Copies another value onto this one (atomically). */
  4364. inline Atomic& operator= (const Atomic& other) throw()
  4365. {
  4366. set (other.get());
  4367. return *this;
  4368. }
  4369. /** Destructor. */
  4370. inline ~Atomic() throw()
  4371. {
  4372. // This class can only be used for types which are 32 or 64 bits in size.
  4373. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  4374. }
  4375. /** Atomically reads and returns the current value. */
  4376. Type get() const throw();
  4377. /** Atomically sets the current value. */
  4378. void set (Type newValue) throw();
  4379. /** Atomically sets the current value, returning the value that was replaced. */
  4380. Type exchange (Type value) throw();
  4381. /** Atomically adds a number to this value, returning the new value. */
  4382. Type operator+= (Type amountToAdd) throw();
  4383. /** Atomically subtracts a number from this value, returning the new value. */
  4384. Type operator-= (Type amountToSubtract) throw();
  4385. /** Atomically increments this value, returning the new value. */
  4386. Type operator++() throw();
  4387. /** Atomically decrements this value, returning the new value. */
  4388. Type operator--() throw();
  4389. /** Atomically compares this value with a target value, and if it is equal, sets
  4390. this to be equal to a new value.
  4391. This operation is the atomic equivalent of doing this:
  4392. @code
  4393. bool compareAndSetBool (Type newValue, Type valueToCompare)
  4394. {
  4395. if (get() == valueToCompare)
  4396. {
  4397. set (newValue);
  4398. return true;
  4399. }
  4400. return false;
  4401. }
  4402. @endcode
  4403. @returns true if the comparison was true and the value was replaced; false if
  4404. the comparison failed and the value was left unchanged.
  4405. @see compareAndSetValue
  4406. */
  4407. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  4408. /** Atomically compares this value with a target value, and if it is equal, sets
  4409. this to be equal to a new value.
  4410. This operation is the atomic equivalent of doing this:
  4411. @code
  4412. Type compareAndSetValue (Type newValue, Type valueToCompare)
  4413. {
  4414. Type oldValue = get();
  4415. if (oldValue == valueToCompare)
  4416. set (newValue);
  4417. return oldValue;
  4418. }
  4419. @endcode
  4420. @returns the old value before it was changed.
  4421. @see compareAndSetBool
  4422. */
  4423. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  4424. /** Implements a memory read/write barrier. */
  4425. static void memoryBarrier() throw();
  4426. JUCE_ALIGN(8)
  4427. /** The raw value that this class operates on.
  4428. This is exposed publically in case you need to manipulate it directly
  4429. for performance reasons.
  4430. */
  4431. Type value;
  4432. };
  4433. /*
  4434. The following code is in the header so that the atomics can be inlined where possible...
  4435. */
  4436. #if (JUCE_IPHONE && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  4437. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  4438. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  4439. #if JUCE_PPC || JUCE_IPHONE
  4440. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  4441. template <typename Type> static Type OSAtomicAdd64 (Type b, volatile Type* a) throw() { jassertfalse; return *a += b; }
  4442. template <typename Type> static Type OSAtomicIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4443. template <typename Type> static Type OSAtomicDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4444. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, volatile Type* value) throw()
  4445. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  4446. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4447. #endif
  4448. #elif JUCE_GCC
  4449. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  4450. #else
  4451. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  4452. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  4453. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  4454. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  4455. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  4456. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  4457. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  4458. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  4459. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  4460. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  4461. #define juce_MemoryBarrier _ReadWriteBarrier
  4462. #else
  4463. // (these are defined in juce_win32_Threads.cpp)
  4464. long juce_InterlockedExchange (volatile long* a, long b) throw();
  4465. long juce_InterlockedIncrement (volatile long* a) throw();
  4466. long juce_InterlockedDecrement (volatile long* a) throw();
  4467. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  4468. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  4469. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  4470. static void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  4471. #endif
  4472. #if JUCE_64BIT
  4473. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  4474. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  4475. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  4476. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  4477. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  4478. #else
  4479. // None of these atomics are available in a 32-bit Windows build!!
  4480. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  4481. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  4482. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4483. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4484. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4485. #endif
  4486. #endif
  4487. #if JUCE_MSVC
  4488. #pragma warning (push)
  4489. #pragma warning (disable: 4311) // (truncation warning)
  4490. #endif
  4491. template <typename Type>
  4492. inline Type Atomic<Type>::get() const throw()
  4493. {
  4494. return const_cast <Atomic<Type>*> (this)->operator+= (0);
  4495. }
  4496. template <typename Type>
  4497. inline void Atomic<Type>::set (const Type newValue) throw()
  4498. {
  4499. exchange (newValue);
  4500. }
  4501. template <typename Type>
  4502. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  4503. {
  4504. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  4505. Type currentVal = value;
  4506. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  4507. return currentVal;
  4508. #elif JUCE_ATOMICS_WINDOWS
  4509. return sizeof (Type) == 4 ? (Type) juce_InterlockedExchange ((volatile long*) &value, (long) newValue)
  4510. : (Type) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) newValue);
  4511. #endif
  4512. }
  4513. template <typename Type>
  4514. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  4515. {
  4516. #if JUCE_ATOMICS_MAC
  4517. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32 ((int32_t) amountToAdd, (int32_t*) &value)
  4518. : (Type) OSAtomicAdd64 ((int64_t) amountToAdd, (int64_t*) &value);
  4519. #elif JUCE_ATOMICS_WINDOWS
  4520. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  4521. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  4522. #elif JUCE_ATOMICS_GCC
  4523. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  4524. #endif
  4525. }
  4526. template <typename Type>
  4527. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  4528. {
  4529. return operator+= (juce_negate (amountToSubtract));
  4530. }
  4531. template <typename Type>
  4532. inline Type Atomic<Type>::operator++() throw()
  4533. {
  4534. #if JUCE_ATOMICS_MAC
  4535. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32 ((int32_t*) &value)
  4536. : (Type) OSAtomicIncrement64 ((int64_t*) &value);
  4537. #elif JUCE_ATOMICS_WINDOWS
  4538. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  4539. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  4540. #elif JUCE_ATOMICS_GCC
  4541. return (Type) __sync_add_and_fetch (&value, 1);
  4542. #endif
  4543. }
  4544. template <typename Type>
  4545. inline Type Atomic<Type>::operator--() throw()
  4546. {
  4547. #if JUCE_ATOMICS_MAC
  4548. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32 ((int32_t*) &value)
  4549. : (Type) OSAtomicDecrement64 ((int64_t*) &value);
  4550. #elif JUCE_ATOMICS_WINDOWS
  4551. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  4552. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  4553. #elif JUCE_ATOMICS_GCC
  4554. return (Type) __sync_add_and_fetch (&value, -1);
  4555. #endif
  4556. }
  4557. template <typename Type>
  4558. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  4559. {
  4560. #if JUCE_ATOMICS_MAC
  4561. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) valueToCompare, (int32_t) newValue, (int32_t*) &value)
  4562. : OSAtomicCompareAndSwap64Barrier ((int64_t) valueToCompare, (int64_t) newValue, (int64_t*) &value);
  4563. #elif JUCE_ATOMICS_WINDOWS
  4564. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  4565. #elif JUCE_ATOMICS_GCC
  4566. return __sync_bool_compare_and_swap (&value, valueToCompare, newValue);
  4567. #endif
  4568. }
  4569. template <typename Type>
  4570. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  4571. {
  4572. #if JUCE_ATOMICS_MAC
  4573. for (;;) // Annoying workaround for OSX only having a bool CAS operation..
  4574. {
  4575. if (compareAndSetBool (newValue, valueToCompare))
  4576. return valueToCompare;
  4577. const Type result = value;
  4578. if (result != valueToCompare)
  4579. return result;
  4580. }
  4581. #elif JUCE_ATOMICS_WINDOWS
  4582. return sizeof (Type) == 4 ? (Type) juce_InterlockedCompareExchange ((volatile long*) &value, (long) newValue, (long) valueToCompare)
  4583. : (Type) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) newValue, (__int64) valueToCompare);
  4584. #elif JUCE_ATOMICS_GCC
  4585. return __sync_val_compare_and_swap (&value, valueToCompare, newValue);
  4586. #endif
  4587. }
  4588. template <typename Type>
  4589. inline void Atomic<Type>::memoryBarrier() throw()
  4590. {
  4591. #if JUCE_ATOMICS_MAC
  4592. OSMemoryBarrier();
  4593. #elif JUCE_ATOMICS_GCC
  4594. __sync_synchronize();
  4595. #elif JUCE_ATOMICS_WINDOWS
  4596. juce_MemoryBarrier();
  4597. #endif
  4598. }
  4599. #if JUCE_MSVC
  4600. #pragma warning (pop)
  4601. #endif
  4602. #endif // __JUCE_ATOMIC_JUCEHEADER__
  4603. /*** End of inlined file: juce_Atomic.h ***/
  4604. /**
  4605. Adds reference-counting to an object.
  4606. To add reference-counting to a class, derive it from this class, and
  4607. use the ReferenceCountedObjectPtr class to point to it.
  4608. e.g. @code
  4609. class MyClass : public ReferenceCountedObject
  4610. {
  4611. void foo();
  4612. // This is a neat way of declaring a typedef for a pointer class,
  4613. // rather than typing out the full templated name each time..
  4614. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  4615. };
  4616. MyClass::Ptr p = new MyClass();
  4617. MyClass::Ptr p2 = p;
  4618. p = 0;
  4619. p2->foo();
  4620. @endcode
  4621. Once a new ReferenceCountedObject has been assigned to a pointer, be
  4622. careful not to delete the object manually.
  4623. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  4624. */
  4625. class JUCE_API ReferenceCountedObject
  4626. {
  4627. public:
  4628. /** Increments the object's reference count.
  4629. This is done automatically by the smart pointer, but is public just
  4630. in case it's needed for nefarious purposes.
  4631. */
  4632. inline void incReferenceCount() throw()
  4633. {
  4634. ++refCount;
  4635. }
  4636. /** Decreases the object's reference count.
  4637. If the count gets to zero, the object will be deleted.
  4638. */
  4639. inline void decReferenceCount() throw()
  4640. {
  4641. jassert (getReferenceCount() > 0);
  4642. if (--refCount == 0)
  4643. delete this;
  4644. }
  4645. /** Returns the object's current reference count. */
  4646. inline int getReferenceCount() const throw()
  4647. {
  4648. return refCount.get();
  4649. }
  4650. protected:
  4651. /** Creates the reference-counted object (with an initial ref count of zero). */
  4652. ReferenceCountedObject()
  4653. {
  4654. }
  4655. /** Destructor. */
  4656. virtual ~ReferenceCountedObject()
  4657. {
  4658. // it's dangerous to delete an object that's still referenced by something else!
  4659. jassert (getReferenceCount() == 0);
  4660. }
  4661. private:
  4662. Atomic <int> refCount;
  4663. };
  4664. /**
  4665. Used to point to an object of type ReferenceCountedObject.
  4666. It's wise to use a typedef instead of typing out the templated name
  4667. each time - e.g.
  4668. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  4669. @see ReferenceCountedObject, ReferenceCountedObjectArray
  4670. */
  4671. template <class ReferenceCountedObjectClass>
  4672. class ReferenceCountedObjectPtr
  4673. {
  4674. public:
  4675. /** Creates a pointer to a null object. */
  4676. inline ReferenceCountedObjectPtr() throw()
  4677. : referencedObject (0)
  4678. {
  4679. }
  4680. /** Creates a pointer to an object.
  4681. This will increment the object's reference-count if it is non-null.
  4682. */
  4683. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  4684. : referencedObject (refCountedObject)
  4685. {
  4686. if (refCountedObject != 0)
  4687. refCountedObject->incReferenceCount();
  4688. }
  4689. /** Copies another pointer.
  4690. This will increment the object's reference-count (if it is non-null).
  4691. */
  4692. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  4693. : referencedObject (other.referencedObject)
  4694. {
  4695. if (referencedObject != 0)
  4696. referencedObject->incReferenceCount();
  4697. }
  4698. /** Changes this pointer to point at a different object.
  4699. The reference count of the old object is decremented, and it might be
  4700. deleted if it hits zero. The new object's count is incremented.
  4701. */
  4702. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  4703. {
  4704. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  4705. if (newObject != referencedObject)
  4706. {
  4707. if (newObject != 0)
  4708. newObject->incReferenceCount();
  4709. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4710. referencedObject = newObject;
  4711. if (oldObject != 0)
  4712. oldObject->decReferenceCount();
  4713. }
  4714. return *this;
  4715. }
  4716. /** Changes this pointer to point at a different object.
  4717. The reference count of the old object is decremented, and it might be
  4718. deleted if it hits zero. The new object's count is incremented.
  4719. */
  4720. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  4721. {
  4722. if (referencedObject != newObject)
  4723. {
  4724. if (newObject != 0)
  4725. newObject->incReferenceCount();
  4726. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4727. referencedObject = newObject;
  4728. if (oldObject != 0)
  4729. oldObject->decReferenceCount();
  4730. }
  4731. return *this;
  4732. }
  4733. /** Destructor.
  4734. This will decrement the object's reference-count, and may delete it if it
  4735. gets to zero.
  4736. */
  4737. inline ~ReferenceCountedObjectPtr()
  4738. {
  4739. if (referencedObject != 0)
  4740. referencedObject->decReferenceCount();
  4741. }
  4742. /** Returns the object that this pointer references.
  4743. The pointer returned may be zero, of course.
  4744. */
  4745. inline operator ReferenceCountedObjectClass*() const throw()
  4746. {
  4747. return referencedObject;
  4748. }
  4749. /** Returns true if this pointer refers to the given object. */
  4750. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  4751. {
  4752. return referencedObject == object;
  4753. }
  4754. /** Returns true if this pointer doesn't refer to the given object. */
  4755. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  4756. {
  4757. return referencedObject != object;
  4758. }
  4759. // the -> operator is called on the referenced object
  4760. inline ReferenceCountedObjectClass* operator->() const throw()
  4761. {
  4762. return referencedObject;
  4763. }
  4764. /** Returns the object that this pointer references.
  4765. The pointer returned may be zero, of course.
  4766. */
  4767. inline ReferenceCountedObjectClass* getObject() const throw()
  4768. {
  4769. return referencedObject;
  4770. }
  4771. private:
  4772. ReferenceCountedObjectClass* referencedObject;
  4773. };
  4774. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4775. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  4776. /**
  4777. Represents a dynamically implemented object.
  4778. This class is primarily intended for wrapping scripting language objects,
  4779. but could be used for other purposes.
  4780. An instance of a DynamicObject can be used to store named properties, and
  4781. by subclassing hasMethod() and invokeMethod(), you can give your object
  4782. methods.
  4783. */
  4784. class JUCE_API DynamicObject : public ReferenceCountedObject
  4785. {
  4786. public:
  4787. DynamicObject();
  4788. /** Destructor. */
  4789. virtual ~DynamicObject();
  4790. /** Returns true if the object has a property with this name.
  4791. Note that if the property is actually a method, this will return false.
  4792. */
  4793. virtual bool hasProperty (const Identifier& propertyName) const;
  4794. /** Returns a named property.
  4795. This returns a void if no such property exists.
  4796. */
  4797. virtual const var getProperty (const Identifier& propertyName) const;
  4798. /** Sets a named property. */
  4799. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  4800. /** Removes a named property. */
  4801. virtual void removeProperty (const Identifier& propertyName);
  4802. /** Checks whether this object has the specified method.
  4803. The default implementation of this just checks whether there's a property
  4804. with this name that's actually a method, but this can be overridden for
  4805. building objects with dynamic invocation.
  4806. */
  4807. virtual bool hasMethod (const Identifier& methodName) const;
  4808. /** Invokes a named method on this object.
  4809. The default implementation looks up the named property, and if it's a method
  4810. call, then it invokes it.
  4811. This method is virtual to allow more dynamic invocation to used for objects
  4812. where the methods may not already be set as properies.
  4813. */
  4814. virtual const var invokeMethod (const Identifier& methodName,
  4815. const var* parameters,
  4816. int numParameters);
  4817. /** Sets up a method.
  4818. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  4819. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  4820. the code easier to read,
  4821. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  4822. @code
  4823. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  4824. @endcode
  4825. */
  4826. void setMethod (const Identifier& methodName,
  4827. var::MethodFunction methodFunction);
  4828. /** Removes all properties and methods from the object. */
  4829. void clear();
  4830. juce_UseDebuggingNewOperator
  4831. private:
  4832. NamedValueSet properties;
  4833. };
  4834. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4835. /*** End of inlined file: juce_DynamicObject.h ***/
  4836. #endif
  4837. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4838. #endif
  4839. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4840. #endif
  4841. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  4842. #endif
  4843. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4844. #endif
  4845. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  4846. #endif
  4847. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4848. /*** Start of inlined file: juce_OwnedArray.h ***/
  4849. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4850. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  4851. /*** Start of inlined file: juce_ScopedPointer.h ***/
  4852. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4853. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4854. /**
  4855. This class holds a pointer which is automatically deleted when this object goes
  4856. out of scope.
  4857. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  4858. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  4859. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  4860. created objects.
  4861. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  4862. to an object. If you use the assignment operator to assign a different object to a
  4863. ScopedPointer, the old one will be automatically deleted.
  4864. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  4865. object to which it points during its lifetime. This means that making a copy of a const
  4866. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  4867. old one.
  4868. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  4869. can use the release() method.
  4870. */
  4871. template <class ObjectType>
  4872. class ScopedPointer
  4873. {
  4874. public:
  4875. /** Creates a ScopedPointer containing a null pointer. */
  4876. inline ScopedPointer() throw() : object (0)
  4877. {
  4878. }
  4879. /** Creates a ScopedPointer that owns the specified object. */
  4880. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  4881. : object (objectToTakePossessionOf)
  4882. {
  4883. }
  4884. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  4885. Because a pointer can only belong to one ScopedPointer, this transfers
  4886. the pointer from the other object to this one, and the other object is reset to
  4887. be a null pointer.
  4888. */
  4889. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  4890. : object (objectToTransferFrom.object)
  4891. {
  4892. objectToTransferFrom.object = 0;
  4893. }
  4894. /** Destructor.
  4895. This will delete the object that this ScopedPointer currently refers to.
  4896. */
  4897. inline ~ScopedPointer() { delete object; }
  4898. /** Changes this ScopedPointer to point to a new object.
  4899. Because a pointer can only belong to one ScopedPointer, this transfers
  4900. the pointer from the other object to this one, and the other object is reset to
  4901. be a null pointer.
  4902. If this ScopedPointer already points to an object, that object
  4903. will first be deleted.
  4904. */
  4905. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  4906. {
  4907. if (this != objectToTransferFrom.getAddress())
  4908. {
  4909. // Two ScopedPointers should never be able to refer to the same object - if
  4910. // this happens, you must have done something dodgy!
  4911. jassert (object == 0 || object != objectToTransferFrom.object);
  4912. ObjectType* const oldObject = object;
  4913. object = objectToTransferFrom.object;
  4914. objectToTransferFrom.object = 0;
  4915. delete oldObject;
  4916. }
  4917. return *this;
  4918. }
  4919. /** Changes this ScopedPointer to point to a new object.
  4920. If this ScopedPointer already points to an object, that object
  4921. will first be deleted.
  4922. The pointer that you pass is may be null.
  4923. */
  4924. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  4925. {
  4926. if (object != newObjectToTakePossessionOf)
  4927. {
  4928. ObjectType* const oldObject = object;
  4929. object = newObjectToTakePossessionOf;
  4930. delete oldObject;
  4931. }
  4932. return *this;
  4933. }
  4934. /** Returns the object that this ScopedPointer refers to.
  4935. */
  4936. inline operator ObjectType*() const throw() { return object; }
  4937. /** Returns the object that this ScopedPointer refers to.
  4938. */
  4939. inline ObjectType& operator*() const throw() { return *object; }
  4940. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  4941. inline ObjectType* operator->() const throw() { return object; }
  4942. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  4943. inline ObjectType* const* operator&() const throw() { return static_cast <ObjectType* const*> (&object); }
  4944. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  4945. inline ObjectType** operator&() throw() { return static_cast <ObjectType**> (&object); }
  4946. /** Removes the current object from this ScopedPointer without deleting it.
  4947. This will return the current object, and set the ScopedPointer to a null pointer.
  4948. */
  4949. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  4950. /** Swaps this object with that of another ScopedPointer.
  4951. The two objects simply exchange their pointers.
  4952. */
  4953. void swapWith (ScopedPointer <ObjectType>& other) throw()
  4954. {
  4955. // Two ScopedPointers should never be able to refer to the same object - if
  4956. // this happens, you must have done something dodgy!
  4957. jassert (object != other.object);
  4958. swapVariables (object, other.object);
  4959. }
  4960. private:
  4961. ObjectType* object;
  4962. // (Required as an alternative to the overloaded & operator).
  4963. const ScopedPointer* getAddress() const throw() { return this; }
  4964. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  4965. // This is private to stop people accidentally copying a const ScopedPointer (the compiler
  4966. // will let you do so by implicitly casting the source to its raw object pointer).
  4967. ScopedPointer (const ScopedPointer&);
  4968. #endif
  4969. };
  4970. /** Compares a ScopedPointer with another pointer.
  4971. This can be handy for checking whether this is a null pointer.
  4972. */
  4973. template <class ObjectType>
  4974. inline bool operator== (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  4975. {
  4976. return static_cast <ObjectType*> (pointer1) == pointer2;
  4977. }
  4978. /** Compares a ScopedPointer with another pointer.
  4979. This can be handy for checking whether this is a null pointer.
  4980. */
  4981. template <class ObjectType>
  4982. inline bool operator!= (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  4983. {
  4984. return static_cast <ObjectType*> (pointer1) != pointer2;
  4985. }
  4986. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4987. /*** End of inlined file: juce_ScopedPointer.h ***/
  4988. /** An array designed for holding objects.
  4989. This holds a list of pointers to objects, and will automatically
  4990. delete the objects when they are removed from the array, or when the
  4991. array is itself deleted.
  4992. Declare it in the form: OwnedArray<MyObjectClass>
  4993. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  4994. After adding objects, they are 'owned' by the array and will be deleted when
  4995. removed or replaced.
  4996. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  4997. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  4998. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  4999. */
  5000. template <class ObjectClass,
  5001. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  5002. class OwnedArray
  5003. {
  5004. public:
  5005. /** Creates an empty array. */
  5006. OwnedArray() throw()
  5007. : numUsed (0)
  5008. {
  5009. }
  5010. /** Deletes the array and also deletes any objects inside it.
  5011. To get rid of the array without deleting its objects, use its
  5012. clear (false) method before deleting it.
  5013. */
  5014. ~OwnedArray()
  5015. {
  5016. clear (true);
  5017. }
  5018. /** Clears the array, optionally deleting the objects inside it first. */
  5019. void clear (const bool deleteObjects = true)
  5020. {
  5021. const ScopedLockType lock (getLock());
  5022. if (deleteObjects)
  5023. {
  5024. while (numUsed > 0)
  5025. delete data.elements [--numUsed];
  5026. }
  5027. data.setAllocatedSize (0);
  5028. numUsed = 0;
  5029. }
  5030. /** Returns the number of items currently in the array.
  5031. @see operator[]
  5032. */
  5033. inline int size() const throw()
  5034. {
  5035. return numUsed;
  5036. }
  5037. /** Returns a pointer to the object at this index in the array.
  5038. If the index is out-of-range, this will return a null pointer, (and
  5039. it could be null anyway, because it's ok for the array to hold null
  5040. pointers as well as objects).
  5041. @see getUnchecked
  5042. */
  5043. inline ObjectClass* operator[] (const int index) const throw()
  5044. {
  5045. const ScopedLockType lock (getLock());
  5046. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  5047. : static_cast <ObjectClass*> (0);
  5048. }
  5049. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  5050. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  5051. it can be used when you're sure the index if always going to be legal.
  5052. */
  5053. inline ObjectClass* getUnchecked (const int index) const throw()
  5054. {
  5055. const ScopedLockType lock (getLock());
  5056. jassert (((unsigned int) index) < (unsigned int) numUsed);
  5057. return data.elements [index];
  5058. }
  5059. /** Returns a pointer to the first object in the array.
  5060. This will return a null pointer if the array's empty.
  5061. @see getLast
  5062. */
  5063. inline ObjectClass* getFirst() const throw()
  5064. {
  5065. const ScopedLockType lock (getLock());
  5066. return numUsed > 0 ? data.elements [0]
  5067. : static_cast <ObjectClass*> (0);
  5068. }
  5069. /** Returns a pointer to the last object in the array.
  5070. This will return a null pointer if the array's empty.
  5071. @see getFirst
  5072. */
  5073. inline ObjectClass* getLast() const throw()
  5074. {
  5075. const ScopedLockType lock (getLock());
  5076. return numUsed > 0 ? data.elements [numUsed - 1]
  5077. : static_cast <ObjectClass*> (0);
  5078. }
  5079. /** Returns a pointer to the actual array data.
  5080. This pointer will only be valid until the next time a non-const method
  5081. is called on the array.
  5082. */
  5083. inline ObjectClass** getRawDataPointer() throw()
  5084. {
  5085. return data.elements;
  5086. }
  5087. /** Finds the index of an object which might be in the array.
  5088. @param objectToLookFor the object to look for
  5089. @returns the index at which the object was found, or -1 if it's not found
  5090. */
  5091. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  5092. {
  5093. const ScopedLockType lock (getLock());
  5094. ObjectClass* const* e = data.elements.getData();
  5095. ObjectClass* const* const end = e + numUsed;
  5096. while (e != end)
  5097. {
  5098. if (objectToLookFor == *e)
  5099. return static_cast <int> (e - data.elements.getData());
  5100. ++e;
  5101. }
  5102. return -1;
  5103. }
  5104. /** Returns true if the array contains a specified object.
  5105. @param objectToLookFor the object to look for
  5106. @returns true if the object is in the array
  5107. */
  5108. bool contains (const ObjectClass* const objectToLookFor) const throw()
  5109. {
  5110. const ScopedLockType lock (getLock());
  5111. ObjectClass* const* e = data.elements.getData();
  5112. ObjectClass* const* const end = e + numUsed;
  5113. while (e != end)
  5114. {
  5115. if (objectToLookFor == *e)
  5116. return true;
  5117. ++e;
  5118. }
  5119. return false;
  5120. }
  5121. /** Appends a new object to the end of the array.
  5122. Note that the this object will be deleted by the OwnedArray when it
  5123. is removed, so be careful not to delete it somewhere else.
  5124. Also be careful not to add the same object to the array more than once,
  5125. as this will obviously cause deletion of dangling pointers.
  5126. @param newObject the new object to add to the array
  5127. @see set, insert, addIfNotAlreadyThere, addSorted
  5128. */
  5129. void add (const ObjectClass* const newObject) throw()
  5130. {
  5131. const ScopedLockType lock (getLock());
  5132. data.ensureAllocatedSize (numUsed + 1);
  5133. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5134. }
  5135. /** Inserts a new object into the array at the given index.
  5136. Note that the this object will be deleted by the OwnedArray when it
  5137. is removed, so be careful not to delete it somewhere else.
  5138. If the index is less than 0 or greater than the size of the array, the
  5139. element will be added to the end of the array.
  5140. Otherwise, it will be inserted into the array, moving all the later elements
  5141. along to make room.
  5142. Be careful not to add the same object to the array more than once,
  5143. as this will obviously cause deletion of dangling pointers.
  5144. @param indexToInsertAt the index at which the new element should be inserted
  5145. @param newObject the new object to add to the array
  5146. @see add, addSorted, addIfNotAlreadyThere, set
  5147. */
  5148. void insert (int indexToInsertAt,
  5149. const ObjectClass* const newObject) throw()
  5150. {
  5151. if (indexToInsertAt >= 0)
  5152. {
  5153. const ScopedLockType lock (getLock());
  5154. if (indexToInsertAt > numUsed)
  5155. indexToInsertAt = numUsed;
  5156. data.ensureAllocatedSize (numUsed + 1);
  5157. ObjectClass** const e = data.elements + indexToInsertAt;
  5158. const int numToMove = numUsed - indexToInsertAt;
  5159. if (numToMove > 0)
  5160. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  5161. *e = const_cast <ObjectClass*> (newObject);
  5162. ++numUsed;
  5163. }
  5164. else
  5165. {
  5166. add (newObject);
  5167. }
  5168. }
  5169. /** Appends a new object at the end of the array as long as the array doesn't
  5170. already contain it.
  5171. If the array already contains a matching object, nothing will be done.
  5172. @param newObject the new object to add to the array
  5173. */
  5174. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  5175. {
  5176. const ScopedLockType lock (getLock());
  5177. if (! contains (newObject))
  5178. add (newObject);
  5179. }
  5180. /** Replaces an object in the array with a different one.
  5181. If the index is less than zero, this method does nothing.
  5182. If the index is beyond the end of the array, the new object is added to the end of the array.
  5183. Be careful not to add the same object to the array more than once,
  5184. as this will obviously cause deletion of dangling pointers.
  5185. @param indexToChange the index whose value you want to change
  5186. @param newObject the new value to set for this index.
  5187. @param deleteOldElement whether to delete the object that's being replaced with the new one
  5188. @see add, insert, remove
  5189. */
  5190. void set (const int indexToChange,
  5191. const ObjectClass* const newObject,
  5192. const bool deleteOldElement = true)
  5193. {
  5194. if (indexToChange >= 0)
  5195. {
  5196. ScopedPointer <ObjectClass> toDelete;
  5197. const ScopedLockType lock (getLock());
  5198. if (indexToChange < numUsed)
  5199. {
  5200. if (deleteOldElement)
  5201. {
  5202. toDelete = data.elements [indexToChange];
  5203. if (toDelete == newObject)
  5204. toDelete = 0;
  5205. }
  5206. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  5207. }
  5208. else
  5209. {
  5210. data.ensureAllocatedSize (numUsed + 1);
  5211. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5212. }
  5213. }
  5214. }
  5215. /** Adds elements from another array to the end of this array.
  5216. @param arrayToAddFrom the array from which to copy the elements
  5217. @param startIndex the first element of the other array to start copying from
  5218. @param numElementsToAdd how many elements to add from the other array. If this
  5219. value is negative or greater than the number of available elements,
  5220. all available elements will be copied.
  5221. @see add
  5222. */
  5223. template <class OtherArrayType>
  5224. void addArray (const OtherArrayType& arrayToAddFrom,
  5225. int startIndex = 0,
  5226. int numElementsToAdd = -1)
  5227. {
  5228. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5229. const ScopedLockType lock2 (getLock());
  5230. if (startIndex < 0)
  5231. {
  5232. jassertfalse;
  5233. startIndex = 0;
  5234. }
  5235. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5236. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5237. while (--numElementsToAdd >= 0)
  5238. add (arrayToAddFrom.getUnchecked (startIndex++));
  5239. }
  5240. /** Inserts a new object into the array assuming that the array is sorted.
  5241. This will use a comparator to find the position at which the new object
  5242. should go. If the array isn't sorted, the behaviour of this
  5243. method will be unpredictable.
  5244. @param comparator the comparator to use to compare the elements - see the sort method
  5245. for details about this object's structure
  5246. @param newObject the new object to insert to the array
  5247. @see add, sort, indexOfSorted
  5248. */
  5249. template <class ElementComparator>
  5250. void addSorted (ElementComparator& comparator,
  5251. ObjectClass* const newObject) throw()
  5252. {
  5253. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5254. // avoids getting warning messages about the parameter being unused
  5255. const ScopedLockType lock (getLock());
  5256. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  5257. }
  5258. /** Finds the index of an object in the array, assuming that the array is sorted.
  5259. This will use a comparator to do a binary-chop to find the index of the given
  5260. element, if it exists. If the array isn't sorted, the behaviour of this
  5261. method will be unpredictable.
  5262. @param comparator the comparator to use to compare the elements - see the sort()
  5263. method for details about the form this object should take
  5264. @param objectToLookFor the object to search for
  5265. @returns the index of the element, or -1 if it's not found
  5266. @see addSorted, sort
  5267. */
  5268. template <class ElementComparator>
  5269. int indexOfSorted (ElementComparator& comparator,
  5270. const ObjectClass* const objectToLookFor) const throw()
  5271. {
  5272. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5273. // avoids getting warning messages about the parameter being unused
  5274. const ScopedLockType lock (getLock());
  5275. int start = 0;
  5276. int end = numUsed;
  5277. for (;;)
  5278. {
  5279. if (start >= end)
  5280. {
  5281. return -1;
  5282. }
  5283. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  5284. {
  5285. return start;
  5286. }
  5287. else
  5288. {
  5289. const int halfway = (start + end) >> 1;
  5290. if (halfway == start)
  5291. return -1;
  5292. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  5293. start = halfway;
  5294. else
  5295. end = halfway;
  5296. }
  5297. }
  5298. }
  5299. /** Removes an object from the array.
  5300. This will remove the object at a given index (optionally also
  5301. deleting it) and move back all the subsequent objects to close the gap.
  5302. If the index passed in is out-of-range, nothing will happen.
  5303. @param indexToRemove the index of the element to remove
  5304. @param deleteObject whether to delete the object that is removed
  5305. @see removeObject, removeRange
  5306. */
  5307. void remove (const int indexToRemove,
  5308. const bool deleteObject = true)
  5309. {
  5310. ScopedPointer <ObjectClass> toDelete;
  5311. const ScopedLockType lock (getLock());
  5312. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5313. {
  5314. ObjectClass** const e = data.elements + indexToRemove;
  5315. if (deleteObject)
  5316. toDelete = *e;
  5317. --numUsed;
  5318. const int numToShift = numUsed - indexToRemove;
  5319. if (numToShift > 0)
  5320. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5321. if ((numUsed << 1) < data.numAllocated)
  5322. minimiseStorageOverheads();
  5323. }
  5324. }
  5325. /** Removes a specified object from the array.
  5326. If the item isn't found, no action is taken.
  5327. @param objectToRemove the object to try to remove
  5328. @param deleteObject whether to delete the object (if it's found)
  5329. @see remove, removeRange
  5330. */
  5331. void removeObject (const ObjectClass* const objectToRemove,
  5332. const bool deleteObject = true)
  5333. {
  5334. const ScopedLockType lock (getLock());
  5335. ObjectClass** e = data.elements.getData();
  5336. for (int i = numUsed; --i >= 0;)
  5337. {
  5338. if (objectToRemove == *e)
  5339. {
  5340. remove (static_cast <int> (e - data.elements.getData()), deleteObject);
  5341. break;
  5342. }
  5343. ++e;
  5344. }
  5345. }
  5346. /** Removes a range of objects from the array.
  5347. This will remove a set of objects, starting from the given index,
  5348. and move any subsequent elements down to close the gap.
  5349. If the range extends beyond the bounds of the array, it will
  5350. be safely clipped to the size of the array.
  5351. @param startIndex the index of the first object to remove
  5352. @param numberToRemove how many objects should be removed
  5353. @param deleteObjects whether to delete the objects that get removed
  5354. @see remove, removeObject
  5355. */
  5356. void removeRange (int startIndex,
  5357. const int numberToRemove,
  5358. const bool deleteObjects = true)
  5359. {
  5360. const ScopedLockType lock (getLock());
  5361. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5362. startIndex = jlimit (0, numUsed, startIndex);
  5363. if (endIndex > startIndex)
  5364. {
  5365. if (deleteObjects)
  5366. {
  5367. for (int i = startIndex; i < endIndex; ++i)
  5368. {
  5369. delete data.elements [i];
  5370. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  5371. }
  5372. }
  5373. const int rangeSize = endIndex - startIndex;
  5374. ObjectClass** e = data.elements + startIndex;
  5375. int numToShift = numUsed - endIndex;
  5376. numUsed -= rangeSize;
  5377. while (--numToShift >= 0)
  5378. {
  5379. *e = e [rangeSize];
  5380. ++e;
  5381. }
  5382. if ((numUsed << 1) < data.numAllocated)
  5383. minimiseStorageOverheads();
  5384. }
  5385. }
  5386. /** Removes the last n objects from the array.
  5387. @param howManyToRemove how many objects to remove from the end of the array
  5388. @param deleteObjects whether to also delete the objects that are removed
  5389. @see remove, removeObject, removeRange
  5390. */
  5391. void removeLast (int howManyToRemove = 1,
  5392. const bool deleteObjects = true)
  5393. {
  5394. const ScopedLockType lock (getLock());
  5395. if (howManyToRemove >= numUsed)
  5396. {
  5397. clear (deleteObjects);
  5398. }
  5399. else
  5400. {
  5401. while (--howManyToRemove >= 0)
  5402. remove (numUsed - 1, deleteObjects);
  5403. }
  5404. }
  5405. /** Swaps a pair of objects in the array.
  5406. If either of the indexes passed in is out-of-range, nothing will happen,
  5407. otherwise the two objects at these positions will be exchanged.
  5408. */
  5409. void swap (const int index1,
  5410. const int index2) throw()
  5411. {
  5412. const ScopedLockType lock (getLock());
  5413. if (((unsigned int) index1) < (unsigned int) numUsed
  5414. && ((unsigned int) index2) < (unsigned int) numUsed)
  5415. {
  5416. swapVariables (data.elements [index1],
  5417. data.elements [index2]);
  5418. }
  5419. }
  5420. /** Moves one of the objects to a different position.
  5421. This will move the object to a specified index, shuffling along
  5422. any intervening elements as required.
  5423. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5424. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5425. @param currentIndex the index of the object to be moved. If this isn't a
  5426. valid index, then nothing will be done
  5427. @param newIndex the index at which you'd like this object to end up. If this
  5428. is less than zero, it will be moved to the end of the array
  5429. */
  5430. void move (const int currentIndex,
  5431. int newIndex) throw()
  5432. {
  5433. if (currentIndex != newIndex)
  5434. {
  5435. const ScopedLockType lock (getLock());
  5436. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  5437. {
  5438. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  5439. newIndex = numUsed - 1;
  5440. ObjectClass* const value = data.elements [currentIndex];
  5441. if (newIndex > currentIndex)
  5442. {
  5443. memmove (data.elements + currentIndex,
  5444. data.elements + currentIndex + 1,
  5445. (newIndex - currentIndex) * sizeof (ObjectClass*));
  5446. }
  5447. else
  5448. {
  5449. memmove (data.elements + newIndex + 1,
  5450. data.elements + newIndex,
  5451. (currentIndex - newIndex) * sizeof (ObjectClass*));
  5452. }
  5453. data.elements [newIndex] = value;
  5454. }
  5455. }
  5456. }
  5457. /** This swaps the contents of this array with those of another array.
  5458. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5459. because it just swaps their internal pointers.
  5460. */
  5461. void swapWithArray (OwnedArray& otherArray) throw()
  5462. {
  5463. const ScopedLockType lock1 (getLock());
  5464. const ScopedLockType lock2 (otherArray.getLock());
  5465. data.swapWith (otherArray.data);
  5466. swapVariables (numUsed, otherArray.numUsed);
  5467. }
  5468. /** Reduces the amount of storage being used by the array.
  5469. Arrays typically allocate slightly more storage than they need, and after
  5470. removing elements, they may have quite a lot of unused space allocated.
  5471. This method will reduce the amount of allocated storage to a minimum.
  5472. */
  5473. void minimiseStorageOverheads() throw()
  5474. {
  5475. const ScopedLockType lock (getLock());
  5476. data.shrinkToNoMoreThan (numUsed);
  5477. }
  5478. /** Increases the array's internal storage to hold a minimum number of elements.
  5479. Calling this before adding a large known number of elements means that
  5480. the array won't have to keep dynamically resizing itself as the elements
  5481. are added, and it'll therefore be more efficient.
  5482. */
  5483. void ensureStorageAllocated (const int minNumElements) throw()
  5484. {
  5485. const ScopedLockType lock (getLock());
  5486. data.ensureAllocatedSize (minNumElements);
  5487. }
  5488. /** Sorts the elements in the array.
  5489. This will use a comparator object to sort the elements into order. The object
  5490. passed must have a method of the form:
  5491. @code
  5492. int compareElements (ElementType first, ElementType second);
  5493. @endcode
  5494. ..and this method must return:
  5495. - a value of < 0 if the first comes before the second
  5496. - a value of 0 if the two objects are equivalent
  5497. - a value of > 0 if the second comes before the first
  5498. To improve performance, the compareElements() method can be declared as static or const.
  5499. @param comparator the comparator to use for comparing elements.
  5500. @param retainOrderOfEquivalentItems if this is true, then items
  5501. which the comparator says are equivalent will be
  5502. kept in the order in which they currently appear
  5503. in the array. This is slower to perform, but may
  5504. be important in some cases. If it's false, a faster
  5505. algorithm is used, but equivalent elements may be
  5506. rearranged.
  5507. @see sortArray, indexOfSorted
  5508. */
  5509. template <class ElementComparator>
  5510. void sort (ElementComparator& comparator,
  5511. const bool retainOrderOfEquivalentItems = false) const throw()
  5512. {
  5513. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5514. // avoids getting warning messages about the parameter being unused
  5515. const ScopedLockType lock (getLock());
  5516. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  5517. }
  5518. /** Returns the CriticalSection that locks this array.
  5519. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  5520. an object of ScopedLockType as an RAII lock for it.
  5521. */
  5522. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  5523. /** Returns the type of scoped lock to use for locking this array */
  5524. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  5525. juce_UseDebuggingNewOperator
  5526. private:
  5527. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  5528. int numUsed;
  5529. // disallow copy constructor and assignment
  5530. OwnedArray (const OwnedArray&);
  5531. OwnedArray& operator= (const OwnedArray&);
  5532. };
  5533. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  5534. /*** End of inlined file: juce_OwnedArray.h ***/
  5535. #endif
  5536. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5537. /*** Start of inlined file: juce_PropertySet.h ***/
  5538. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5539. #define __JUCE_PROPERTYSET_JUCEHEADER__
  5540. /*** Start of inlined file: juce_StringPairArray.h ***/
  5541. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5542. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5543. /*** Start of inlined file: juce_StringArray.h ***/
  5544. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  5545. #define __JUCE_STRINGARRAY_JUCEHEADER__
  5546. /**
  5547. A special array for holding a list of strings.
  5548. @see String, StringPairArray
  5549. */
  5550. class JUCE_API StringArray
  5551. {
  5552. public:
  5553. /** Creates an empty string array */
  5554. StringArray() throw();
  5555. /** Creates a copy of another string array */
  5556. StringArray (const StringArray& other);
  5557. /** Creates an array containing a single string. */
  5558. explicit StringArray (const String& firstValue);
  5559. /** Creates a copy of an array of string literals.
  5560. @param strings an array of strings to add. Null pointers in the array will be
  5561. treated as empty strings
  5562. @param numberOfStrings how many items there are in the array
  5563. */
  5564. StringArray (const juce_wchar* const* strings, int numberOfStrings);
  5565. /** Creates a copy of an array of string literals.
  5566. @param strings an array of strings to add. Null pointers in the array will be
  5567. treated as empty strings
  5568. @param numberOfStrings how many items there are in the array
  5569. */
  5570. StringArray (const char* const* strings, int numberOfStrings);
  5571. /** Creates a copy of a null-terminated array of string literals.
  5572. Each item from the array passed-in is added, until it encounters a null pointer,
  5573. at which point it stops.
  5574. */
  5575. explicit StringArray (const juce_wchar* const* strings);
  5576. /** Creates a copy of a null-terminated array of string literals.
  5577. Each item from the array passed-in is added, until it encounters a null pointer,
  5578. at which point it stops.
  5579. */
  5580. explicit StringArray (const char* const* strings);
  5581. /** Destructor. */
  5582. ~StringArray();
  5583. /** Copies the contents of another string array into this one */
  5584. StringArray& operator= (const StringArray& other);
  5585. /** Compares two arrays.
  5586. Comparisons are case-sensitive.
  5587. @returns true only if the other array contains exactly the same strings in the same order
  5588. */
  5589. bool operator== (const StringArray& other) const throw();
  5590. /** Compares two arrays.
  5591. Comparisons are case-sensitive.
  5592. @returns false if the other array contains exactly the same strings in the same order
  5593. */
  5594. bool operator!= (const StringArray& other) const throw();
  5595. /** Returns the number of strings in the array */
  5596. inline int size() const throw() { return strings.size(); };
  5597. /** Returns one of the strings from the array.
  5598. If the index is out-of-range, an empty string is returned.
  5599. Obviously the reference returned shouldn't be stored for later use, as the
  5600. string it refers to may disappear when the array changes.
  5601. */
  5602. const String& operator[] (int index) const throw();
  5603. /** Returns a reference to one of the strings in the array.
  5604. This lets you modify a string in-place in the array, but you must be sure that
  5605. the index is in-range.
  5606. */
  5607. String& getReference (int index) throw();
  5608. /** Searches for a string in the array.
  5609. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5610. @returns true if the string is found inside the array
  5611. */
  5612. bool contains (const String& stringToLookFor,
  5613. bool ignoreCase = false) const;
  5614. /** Searches for a string in the array.
  5615. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5616. @param stringToLookFor the string to try to find
  5617. @param ignoreCase whether the comparison should be case-insensitive
  5618. @param startIndex the first index to start searching from
  5619. @returns the index of the first occurrence of the string in this array,
  5620. or -1 if it isn't found.
  5621. */
  5622. int indexOf (const String& stringToLookFor,
  5623. bool ignoreCase = false,
  5624. int startIndex = 0) const;
  5625. /** Appends a string at the end of the array. */
  5626. void add (const String& stringToAdd);
  5627. /** Inserts a string into the array.
  5628. This will insert a string into the array at the given index, moving
  5629. up the other elements to make room for it.
  5630. If the index is less than zero or greater than the size of the array,
  5631. the new string will be added to the end of the array.
  5632. */
  5633. void insert (int index, const String& stringToAdd);
  5634. /** Adds a string to the array as long as it's not already in there.
  5635. The search can optionally be case-insensitive.
  5636. */
  5637. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  5638. /** Replaces one of the strings in the array with another one.
  5639. If the index is higher than the array's size, the new string will be
  5640. added to the end of the array; if it's less than zero nothing happens.
  5641. */
  5642. void set (int index, const String& newString);
  5643. /** Appends some strings from another array to the end of this one.
  5644. @param other the array to add
  5645. @param startIndex the first element of the other array to add
  5646. @param numElementsToAdd the maximum number of elements to add (if this is
  5647. less than zero, they are all added)
  5648. */
  5649. void addArray (const StringArray& other,
  5650. int startIndex = 0,
  5651. int numElementsToAdd = -1);
  5652. /** Breaks up a string into tokens and adds them to this array.
  5653. This will tokenise the given string using whitespace characters as the
  5654. token delimiters, and will add these tokens to the end of the array.
  5655. @returns the number of tokens added
  5656. */
  5657. int addTokens (const String& stringToTokenise,
  5658. bool preserveQuotedStrings);
  5659. /** Breaks up a string into tokens and adds them to this array.
  5660. This will tokenise the given string (using the string passed in to define the
  5661. token delimiters), and will add these tokens to the end of the array.
  5662. @param stringToTokenise the string to tokenise
  5663. @param breakCharacters a string of characters, any of which will be considered
  5664. to be a token delimiter.
  5665. @param quoteCharacters if this string isn't empty, it defines a set of characters
  5666. which are treated as quotes. Any text occurring
  5667. between quotes is not broken up into tokens.
  5668. @returns the number of tokens added
  5669. */
  5670. int addTokens (const String& stringToTokenise,
  5671. const String& breakCharacters,
  5672. const String& quoteCharacters);
  5673. /** Breaks up a string into lines and adds them to this array.
  5674. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  5675. to the array. Line-break characters are omitted from the strings that are added to
  5676. the array.
  5677. */
  5678. int addLines (const String& stringToBreakUp);
  5679. /** Removes all elements from the array. */
  5680. void clear();
  5681. /** Removes a string from the array.
  5682. If the index is out-of-range, no action will be taken.
  5683. */
  5684. void remove (int index);
  5685. /** Finds a string in the array and removes it.
  5686. This will remove the first occurrence of the given string from the array. The
  5687. comparison may be case-insensitive depending on the ignoreCase parameter.
  5688. */
  5689. void removeString (const String& stringToRemove,
  5690. bool ignoreCase = false);
  5691. /** Removes a range of elements from the array.
  5692. This will remove a set of elements, starting from the given index,
  5693. and move subsequent elements down to close the gap.
  5694. If the range extends beyond the bounds of the array, it will
  5695. be safely clipped to the size of the array.
  5696. @param startIndex the index of the first element to remove
  5697. @param numberToRemove how many elements should be removed
  5698. */
  5699. void removeRange (int startIndex, int numberToRemove);
  5700. /** Removes any duplicated elements from the array.
  5701. If any string appears in the array more than once, only the first occurrence of
  5702. it will be retained.
  5703. @param ignoreCase whether to use a case-insensitive comparison
  5704. */
  5705. void removeDuplicates (bool ignoreCase);
  5706. /** Removes empty strings from the array.
  5707. @param removeWhitespaceStrings if true, strings that only contain whitespace
  5708. characters will also be removed
  5709. */
  5710. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  5711. /** Moves one of the strings to a different position.
  5712. This will move the string to a specified index, shuffling along
  5713. any intervening elements as required.
  5714. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5715. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5716. @param currentIndex the index of the value to be moved. If this isn't a
  5717. valid index, then nothing will be done
  5718. @param newIndex the index at which you'd like this value to end up. If this
  5719. is less than zero, the value will be moved to the end
  5720. of the array
  5721. */
  5722. void move (int currentIndex, int newIndex) throw();
  5723. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  5724. void trim();
  5725. /** Adds numbers to the strings in the array, to make each string unique.
  5726. This will add numbers to the ends of groups of similar strings.
  5727. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  5728. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  5729. @param appendNumberToFirstInstance whether the first of a group of similar strings
  5730. also has a number appended to it.
  5731. @param preNumberString when adding a number, this string is added before the number.
  5732. If you pass 0, a default string will be used, which adds
  5733. brackets around the number.
  5734. @param postNumberString this string is appended after any numbers that are added.
  5735. If you pass 0, a default string will be used, which adds
  5736. brackets around the number.
  5737. */
  5738. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  5739. bool appendNumberToFirstInstance,
  5740. const juce_wchar* preNumberString = 0,
  5741. const juce_wchar* postNumberString = 0);
  5742. /** Joins the strings in the array together into one string.
  5743. This will join a range of elements from the array into a string, separating
  5744. them with a given string.
  5745. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  5746. @param separatorString the string to insert between all the strings
  5747. @param startIndex the first element to join
  5748. @param numberOfElements how many elements to join together. If this is less
  5749. than zero, all available elements will be used.
  5750. */
  5751. const String joinIntoString (const String& separatorString,
  5752. int startIndex = 0,
  5753. int numberOfElements = -1) const;
  5754. /** Sorts the array into alphabetical order.
  5755. @param ignoreCase if true, the comparisons used will be case-sensitive.
  5756. */
  5757. void sort (bool ignoreCase);
  5758. /** Reduces the amount of storage being used by the array.
  5759. Arrays typically allocate slightly more storage than they need, and after
  5760. removing elements, they may have quite a lot of unused space allocated.
  5761. This method will reduce the amount of allocated storage to a minimum.
  5762. */
  5763. void minimiseStorageOverheads();
  5764. juce_UseDebuggingNewOperator
  5765. private:
  5766. Array <String> strings;
  5767. };
  5768. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  5769. /*** End of inlined file: juce_StringArray.h ***/
  5770. /**
  5771. A container for holding a set of strings which are keyed by another string.
  5772. @see StringArray
  5773. */
  5774. class JUCE_API StringPairArray
  5775. {
  5776. public:
  5777. /** Creates an empty array */
  5778. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  5779. /** Creates a copy of another array */
  5780. StringPairArray (const StringPairArray& other);
  5781. /** Destructor. */
  5782. ~StringPairArray();
  5783. /** Copies the contents of another string array into this one */
  5784. StringPairArray& operator= (const StringPairArray& other);
  5785. /** Compares two arrays.
  5786. Comparisons are case-sensitive.
  5787. @returns true only if the other array contains exactly the same strings with the same keys
  5788. */
  5789. bool operator== (const StringPairArray& other) const;
  5790. /** Compares two arrays.
  5791. Comparisons are case-sensitive.
  5792. @returns false if the other array contains exactly the same strings with the same keys
  5793. */
  5794. bool operator!= (const StringPairArray& other) const;
  5795. /** Finds the value corresponding to a key string.
  5796. If no such key is found, this will just return an empty string. To check whether
  5797. a given key actually exists (because it might actually be paired with an empty string), use
  5798. the getAllKeys() method to obtain a list.
  5799. Obviously the reference returned shouldn't be stored for later use, as the
  5800. string it refers to may disappear when the array changes.
  5801. @see getValue
  5802. */
  5803. const String& operator[] (const String& key) const;
  5804. /** Finds the value corresponding to a key string.
  5805. If no such key is found, this will just return the value provided as a default.
  5806. @see operator[]
  5807. */
  5808. const String getValue (const String& key, const String& defaultReturnValue) const;
  5809. /** Returns a list of all keys in the array. */
  5810. const StringArray& getAllKeys() const throw() { return keys; }
  5811. /** Returns a list of all values in the array. */
  5812. const StringArray& getAllValues() const throw() { return values; }
  5813. /** Returns the number of strings in the array */
  5814. inline int size() const throw() { return keys.size(); };
  5815. /** Adds or amends a key/value pair.
  5816. If a value already exists with this key, its value will be overwritten,
  5817. otherwise the key/value pair will be added to the array.
  5818. */
  5819. void set (const String& key, const String& value);
  5820. /** Adds the items from another array to this one.
  5821. This is equivalent to using set() to add each of the pairs from the other array.
  5822. */
  5823. void addArray (const StringPairArray& other);
  5824. /** Removes all elements from the array. */
  5825. void clear();
  5826. /** Removes a string from the array based on its key.
  5827. If the key isn't found, nothing will happen.
  5828. */
  5829. void remove (const String& key);
  5830. /** Removes a string from the array based on its index.
  5831. If the index is out-of-range, no action will be taken.
  5832. */
  5833. void remove (int index);
  5834. /** Indicates whether to use a case-insensitive search when looking up a key string.
  5835. */
  5836. void setIgnoresCase (bool shouldIgnoreCase);
  5837. /** Returns a descriptive string containing the items.
  5838. This is handy for dumping the contents of an array.
  5839. */
  5840. const String getDescription() const;
  5841. /** Reduces the amount of storage being used by the array.
  5842. Arrays typically allocate slightly more storage than they need, and after
  5843. removing elements, they may have quite a lot of unused space allocated.
  5844. This method will reduce the amount of allocated storage to a minimum.
  5845. */
  5846. void minimiseStorageOverheads();
  5847. juce_UseDebuggingNewOperator
  5848. private:
  5849. StringArray keys, values;
  5850. bool ignoreCase;
  5851. };
  5852. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5853. /*** End of inlined file: juce_StringPairArray.h ***/
  5854. /*** Start of inlined file: juce_XmlElement.h ***/
  5855. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  5856. #define __JUCE_XMLELEMENT_JUCEHEADER__
  5857. /*** Start of inlined file: juce_File.h ***/
  5858. #ifndef __JUCE_FILE_JUCEHEADER__
  5859. #define __JUCE_FILE_JUCEHEADER__
  5860. /*** Start of inlined file: juce_Time.h ***/
  5861. #ifndef __JUCE_TIME_JUCEHEADER__
  5862. #define __JUCE_TIME_JUCEHEADER__
  5863. /*** Start of inlined file: juce_RelativeTime.h ***/
  5864. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  5865. #define __JUCE_RELATIVETIME_JUCEHEADER__
  5866. /** A relative measure of time.
  5867. The time is stored as a number of seconds, at double-precision floating
  5868. point accuracy, and may be positive or negative.
  5869. If you need an absolute time, (i.e. a date + time), see the Time class.
  5870. */
  5871. class JUCE_API RelativeTime
  5872. {
  5873. public:
  5874. /** Creates a RelativeTime.
  5875. @param seconds the number of seconds, which may be +ve or -ve.
  5876. @see milliseconds, minutes, hours, days, weeks
  5877. */
  5878. explicit RelativeTime (double seconds = 0.0) throw();
  5879. /** Copies another relative time. */
  5880. RelativeTime (const RelativeTime& other) throw();
  5881. /** Copies another relative time. */
  5882. RelativeTime& operator= (const RelativeTime& other) throw();
  5883. /** Destructor. */
  5884. ~RelativeTime() throw();
  5885. /** Creates a new RelativeTime object representing a number of milliseconds.
  5886. @see minutes, hours, days, weeks
  5887. */
  5888. static const RelativeTime milliseconds (int milliseconds) throw();
  5889. /** Creates a new RelativeTime object representing a number of milliseconds.
  5890. @see minutes, hours, days, weeks
  5891. */
  5892. static const RelativeTime milliseconds (int64 milliseconds) throw();
  5893. /** Creates a new RelativeTime object representing a number of minutes.
  5894. @see milliseconds, hours, days, weeks
  5895. */
  5896. static const RelativeTime minutes (double numberOfMinutes) throw();
  5897. /** Creates a new RelativeTime object representing a number of hours.
  5898. @see milliseconds, minutes, days, weeks
  5899. */
  5900. static const RelativeTime hours (double numberOfHours) throw();
  5901. /** Creates a new RelativeTime object representing a number of days.
  5902. @see milliseconds, minutes, hours, weeks
  5903. */
  5904. static const RelativeTime days (double numberOfDays) throw();
  5905. /** Creates a new RelativeTime object representing a number of weeks.
  5906. @see milliseconds, minutes, hours, days
  5907. */
  5908. static const RelativeTime weeks (double numberOfWeeks) throw();
  5909. /** Returns the number of milliseconds this time represents.
  5910. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  5911. */
  5912. int64 inMilliseconds() const throw();
  5913. /** Returns the number of seconds this time represents.
  5914. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  5915. */
  5916. double inSeconds() const throw() { return seconds; }
  5917. /** Returns the number of minutes this time represents.
  5918. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  5919. */
  5920. double inMinutes() const throw();
  5921. /** Returns the number of hours this time represents.
  5922. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  5923. */
  5924. double inHours() const throw();
  5925. /** Returns the number of days this time represents.
  5926. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  5927. */
  5928. double inDays() const throw();
  5929. /** Returns the number of weeks this time represents.
  5930. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  5931. */
  5932. double inWeeks() const throw();
  5933. /** Returns a readable textual description of the time.
  5934. The exact format of the string returned will depend on
  5935. the magnitude of the time - e.g.
  5936. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  5937. so that only the two most significant units are printed.
  5938. The returnValueForZeroTime value is the result that is returned if the
  5939. length is zero. Depending on your application you might want to use this
  5940. to return something more relevant like "empty" or "0 secs", etc.
  5941. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  5942. */
  5943. const String getDescription (const String& returnValueForZeroTime = "0") const throw();
  5944. /** Compares two RelativeTimes. */
  5945. bool operator== (const RelativeTime& other) const throw();
  5946. /** Compares two RelativeTimes. */
  5947. bool operator!= (const RelativeTime& other) const throw();
  5948. /** Compares two RelativeTimes. */
  5949. bool operator> (const RelativeTime& other) const throw();
  5950. /** Compares two RelativeTimes. */
  5951. bool operator< (const RelativeTime& other) const throw();
  5952. /** Compares two RelativeTimes. */
  5953. bool operator>= (const RelativeTime& other) const throw();
  5954. /** Compares two RelativeTimes. */
  5955. bool operator<= (const RelativeTime& other) const throw();
  5956. /** Adds another RelativeTime to this one and returns the result. */
  5957. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  5958. /** Subtracts another RelativeTime from this one and returns the result. */
  5959. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  5960. /** Adds a number of seconds to this RelativeTime and returns the result. */
  5961. const RelativeTime operator+ (double secondsToAdd) const throw();
  5962. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  5963. const RelativeTime operator- (double secondsToSubtract) const throw();
  5964. /** Adds another RelativeTime to this one. */
  5965. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  5966. /** Subtracts another RelativeTime from this one. */
  5967. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  5968. /** Adds a number of seconds to this time. */
  5969. const RelativeTime& operator+= (double secondsToAdd) throw();
  5970. /** Subtracts a number of seconds from this time. */
  5971. const RelativeTime& operator-= (double secondsToSubtract) throw();
  5972. juce_UseDebuggingNewOperator
  5973. private:
  5974. double seconds;
  5975. };
  5976. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  5977. /*** End of inlined file: juce_RelativeTime.h ***/
  5978. /**
  5979. Holds an absolute date and time.
  5980. Internally, the time is stored at millisecond precision.
  5981. @see RelativeTime
  5982. */
  5983. class JUCE_API Time
  5984. {
  5985. public:
  5986. /** Creates a Time object.
  5987. This default constructor creates a time of 1st January 1970, (which is
  5988. represented internally as 0ms).
  5989. To create a time object representing the current time, use getCurrentTime().
  5990. @see getCurrentTime
  5991. */
  5992. Time() throw();
  5993. /** Creates a copy of another Time object. */
  5994. Time (const Time& other) throw();
  5995. /** Creates a time based on a number of milliseconds.
  5996. The internal millisecond count is set to 0 (1st January 1970). To create a
  5997. time object set to the current time, use getCurrentTime().
  5998. @param millisecondsSinceEpoch the number of milliseconds since the unix
  5999. 'epoch' (midnight Jan 1st 1970).
  6000. @see getCurrentTime, currentTimeMillis
  6001. */
  6002. Time (int64 millisecondsSinceEpoch) throw();
  6003. /** Creates a time from a set of date components.
  6004. The timezone is assumed to be whatever the system is using as its locale.
  6005. @param year the year, in 4-digit format, e.g. 2004
  6006. @param month the month, in the range 0 to 11
  6007. @param day the day of the month, in the range 1 to 31
  6008. @param hours hours in 24-hour clock format, 0 to 23
  6009. @param minutes minutes 0 to 59
  6010. @param seconds seconds 0 to 59
  6011. @param milliseconds milliseconds 0 to 999
  6012. @param useLocalTime if true, encode using the current machine's local time; if
  6013. false, it will always work in GMT.
  6014. */
  6015. Time (int year,
  6016. int month,
  6017. int day,
  6018. int hours,
  6019. int minutes,
  6020. int seconds = 0,
  6021. int milliseconds = 0,
  6022. bool useLocalTime = true) throw();
  6023. /** Destructor. */
  6024. ~Time() throw();
  6025. /** Copies this time from another one. */
  6026. Time& operator= (const Time& other) throw();
  6027. /** Returns a Time object that is set to the current system time.
  6028. @see currentTimeMillis
  6029. */
  6030. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  6031. /** Returns the time as a number of milliseconds.
  6032. @returns the number of milliseconds this Time object represents, since
  6033. midnight jan 1st 1970.
  6034. @see getMilliseconds
  6035. */
  6036. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  6037. /** Returns the year.
  6038. A 4-digit format is used, e.g. 2004.
  6039. */
  6040. int getYear() const throw();
  6041. /** Returns the number of the month.
  6042. The value returned is in the range 0 to 11.
  6043. @see getMonthName
  6044. */
  6045. int getMonth() const throw();
  6046. /** Returns the name of the month.
  6047. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6048. it'll return the long form, e.g. "January"
  6049. @see getMonth
  6050. */
  6051. const String getMonthName (bool threeLetterVersion) const throw();
  6052. /** Returns the day of the month.
  6053. The value returned is in the range 1 to 31.
  6054. */
  6055. int getDayOfMonth() const throw();
  6056. /** Returns the number of the day of the week.
  6057. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  6058. */
  6059. int getDayOfWeek() const throw();
  6060. /** Returns the name of the weekday.
  6061. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6062. false, it'll return the full version, e.g. "Tuesday".
  6063. */
  6064. const String getWeekdayName (bool threeLetterVersion) const throw();
  6065. /** Returns the number of hours since midnight.
  6066. This is in 24-hour clock format, in the range 0 to 23.
  6067. @see getHoursInAmPmFormat, isAfternoon
  6068. */
  6069. int getHours() const throw();
  6070. /** Returns true if the time is in the afternoon.
  6071. So it returns true for "PM", false for "AM".
  6072. @see getHoursInAmPmFormat, getHours
  6073. */
  6074. bool isAfternoon() const throw();
  6075. /** Returns the hours in 12-hour clock format.
  6076. This will return a value 1 to 12 - use isAfternoon() to find out
  6077. whether this is in the afternoon or morning.
  6078. @see getHours, isAfternoon
  6079. */
  6080. int getHoursInAmPmFormat() const throw();
  6081. /** Returns the number of minutes, 0 to 59. */
  6082. int getMinutes() const throw();
  6083. /** Returns the number of seconds, 0 to 59. */
  6084. int getSeconds() const throw();
  6085. /** Returns the number of milliseconds, 0 to 999.
  6086. Unlike toMilliseconds(), this just returns the position within the
  6087. current second rather than the total number since the epoch.
  6088. @see toMilliseconds
  6089. */
  6090. int getMilliseconds() const throw();
  6091. /** Returns true if the local timezone uses a daylight saving correction. */
  6092. bool isDaylightSavingTime() const throw();
  6093. /** Returns a 3-character string to indicate the local timezone. */
  6094. const String getTimeZone() const throw();
  6095. /** Quick way of getting a string version of a date and time.
  6096. For a more powerful way of formatting the date and time, see the formatted() method.
  6097. @param includeDate whether to include the date in the string
  6098. @param includeTime whether to include the time in the string
  6099. @param includeSeconds if the time is being included, this provides an option not to include
  6100. the seconds in it
  6101. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  6102. hour notation.
  6103. @see formatted
  6104. */
  6105. const String toString (bool includeDate,
  6106. bool includeTime,
  6107. bool includeSeconds = true,
  6108. bool use24HourClock = false) const throw();
  6109. /** Converts this date/time to a string with a user-defined format.
  6110. This uses the C strftime() function to format this time as a string. To save you
  6111. looking it up, these are the escape codes that strftime uses (other codes might
  6112. work on some platforms and not others, but these are the common ones):
  6113. %a is replaced by the locale's abbreviated weekday name.
  6114. %A is replaced by the locale's full weekday name.
  6115. %b is replaced by the locale's abbreviated month name.
  6116. %B is replaced by the locale's full month name.
  6117. %c is replaced by the locale's appropriate date and time representation.
  6118. %d is replaced by the day of the month as a decimal number [01,31].
  6119. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  6120. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  6121. %j is replaced by the day of the year as a decimal number [001,366].
  6122. %m is replaced by the month as a decimal number [01,12].
  6123. %M is replaced by the minute as a decimal number [00,59].
  6124. %p is replaced by the locale's equivalent of either a.m. or p.m.
  6125. %S is replaced by the second as a decimal number [00,61].
  6126. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  6127. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  6128. %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.
  6129. %x is replaced by the locale's appropriate date representation.
  6130. %X is replaced by the locale's appropriate time representation.
  6131. %y is replaced by the year without century as a decimal number [00,99].
  6132. %Y is replaced by the year with century as a decimal number.
  6133. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  6134. %% is replaced by %.
  6135. @see toString
  6136. */
  6137. const String formatted (const String& format) const throw();
  6138. /** Adds a RelativeTime to this time and returns the result. */
  6139. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  6140. /** Subtracts a RelativeTime from this time and returns the result. */
  6141. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  6142. /** Returns the relative time difference between this time and another one. */
  6143. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  6144. /** Compares two Time objects. */
  6145. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  6146. /** Compares two Time objects. */
  6147. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  6148. /** Compares two Time objects. */
  6149. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  6150. /** Compares two Time objects. */
  6151. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  6152. /** Compares two Time objects. */
  6153. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  6154. /** Compares two Time objects. */
  6155. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  6156. /** Tries to set the computer's clock.
  6157. @returns true if this succeeds, although depending on the system, the
  6158. application might not have sufficient privileges to do this.
  6159. */
  6160. bool setSystemTimeToThisTime() const;
  6161. /** Returns the name of a day of the week.
  6162. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  6163. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6164. false, it'll return the full version, e.g. "Tuesday".
  6165. */
  6166. static const String getWeekdayName (int dayNumber,
  6167. bool threeLetterVersion) throw();
  6168. /** Returns the name of one of the months.
  6169. @param monthNumber the month, 0 to 11
  6170. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6171. it'll return the long form, e.g. "January"
  6172. */
  6173. static const String getMonthName (int monthNumber,
  6174. bool threeLetterVersion) throw();
  6175. // Static methods for getting system timers directly..
  6176. /** Returns the current system time.
  6177. Returns the number of milliseconds since midnight jan 1st 1970.
  6178. Should be accurate to within a few millisecs, depending on platform,
  6179. hardware, etc.
  6180. */
  6181. static int64 currentTimeMillis() throw();
  6182. /** Returns the number of millisecs since system startup.
  6183. Should be accurate to within a few millisecs, depending on platform,
  6184. hardware, etc.
  6185. @see getApproximateMillisecondCounter
  6186. */
  6187. static uint32 getMillisecondCounter() throw();
  6188. /** Returns the number of millisecs since system startup.
  6189. Same as getMillisecondCounter(), but returns a more accurate value, using
  6190. the high-res timer.
  6191. @see getMillisecondCounter
  6192. */
  6193. static double getMillisecondCounterHiRes() throw();
  6194. /** Waits until the getMillisecondCounter() reaches a given value.
  6195. This will make the thread sleep as efficiently as it can while it's waiting.
  6196. */
  6197. static void waitForMillisecondCounter (uint32 targetTime) throw();
  6198. /** Less-accurate but faster version of getMillisecondCounter().
  6199. This will return the last value that getMillisecondCounter() returned, so doesn't
  6200. need to make a system call, but is less accurate - it shouldn't be more than
  6201. 100ms away from the correct time, though, so is still accurate enough for a
  6202. lot of purposes.
  6203. @see getMillisecondCounter
  6204. */
  6205. static uint32 getApproximateMillisecondCounter() throw();
  6206. // High-resolution timers..
  6207. /** Returns the current high-resolution counter's tick-count.
  6208. This is a similar idea to getMillisecondCounter(), but with a higher
  6209. resolution.
  6210. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  6211. secondsToHighResolutionTicks
  6212. */
  6213. static int64 getHighResolutionTicks() throw();
  6214. /** Returns the resolution of the high-resolution counter in ticks per second.
  6215. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  6216. secondsToHighResolutionTicks
  6217. */
  6218. static int64 getHighResolutionTicksPerSecond() throw();
  6219. /** Converts a number of high-resolution ticks into seconds.
  6220. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6221. secondsToHighResolutionTicks
  6222. */
  6223. static double highResolutionTicksToSeconds (int64 ticks) throw();
  6224. /** Converts a number seconds into high-resolution ticks.
  6225. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6226. highResolutionTicksToSeconds
  6227. */
  6228. static int64 secondsToHighResolutionTicks (double seconds) throw();
  6229. private:
  6230. int64 millisSinceEpoch;
  6231. };
  6232. #endif // __JUCE_TIME_JUCEHEADER__
  6233. /*** End of inlined file: juce_Time.h ***/
  6234. class FileInputStream;
  6235. class FileOutputStream;
  6236. /**
  6237. Represents a local file or directory.
  6238. This class encapsulates the absolute pathname of a file or directory, and
  6239. has methods for finding out about the file and changing its properties.
  6240. To read or write to the file, there are methods for returning an input or
  6241. output stream.
  6242. @see FileInputStream, FileOutputStream
  6243. */
  6244. class JUCE_API File
  6245. {
  6246. public:
  6247. /** Creates an (invalid) file object.
  6248. The file is initially set to an empty path, so getFullPath() will return
  6249. an empty string, and comparing the file to File::nonexistent will return
  6250. true.
  6251. You can use its operator= method to point it at a proper file.
  6252. */
  6253. File() {}
  6254. /** Creates a file from an absolute path.
  6255. If the path supplied is a relative path, it is taken to be relative
  6256. to the current working directory (see File::getCurrentWorkingDirectory()),
  6257. but this isn't a recommended way of creating a file, because you
  6258. never know what the CWD is going to be.
  6259. On the Mac/Linux, the path can include "~" notation for referring to
  6260. user home directories.
  6261. */
  6262. File (const String& path);
  6263. /** Creates a copy of another file object. */
  6264. File (const File& other);
  6265. /** Destructor. */
  6266. ~File() {}
  6267. /** Sets the file based on an absolute pathname.
  6268. If the path supplied is a relative path, it is taken to be relative
  6269. to the current working directory (see File::getCurrentWorkingDirectory()),
  6270. but this isn't a recommended way of creating a file, because you
  6271. never know what the CWD is going to be.
  6272. On the Mac/Linux, the path can include "~" notation for referring to
  6273. user home directories.
  6274. */
  6275. File& operator= (const String& newFilePath);
  6276. /** Copies from another file object. */
  6277. File& operator= (const File& otherFile);
  6278. /** This static constant is used for referring to an 'invalid' file. */
  6279. static const File nonexistent;
  6280. /** Checks whether the file actually exists.
  6281. @returns true if the file exists, either as a file or a directory.
  6282. @see existsAsFile, isDirectory
  6283. */
  6284. bool exists() const;
  6285. /** Checks whether the file exists and is a file rather than a directory.
  6286. @returns true only if this is a real file, false if it's a directory
  6287. or doesn't exist
  6288. @see exists, isDirectory
  6289. */
  6290. bool existsAsFile() const;
  6291. /** Checks whether the file is a directory that exists.
  6292. @returns true only if the file is a directory which actually exists, so
  6293. false if it's a file or doesn't exist at all
  6294. @see exists, existsAsFile
  6295. */
  6296. bool isDirectory() const;
  6297. /** Returns the size of the file in bytes.
  6298. @returns the number of bytes in the file, or 0 if it doesn't exist.
  6299. */
  6300. int64 getSize() const;
  6301. /** Utility function to convert a file size in bytes to a neat string description.
  6302. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  6303. 2000000 would produce "2 MB", etc.
  6304. */
  6305. static const String descriptionOfSizeInBytes (int64 bytes);
  6306. /** Returns the complete, absolute path of this file.
  6307. This includes the filename and all its parent folders. On Windows it'll
  6308. also include the drive letter prefix; on Mac or Linux it'll be a complete
  6309. path starting from the root folder.
  6310. If you just want the file's name, you should use getFileName() or
  6311. getFileNameWithoutExtension().
  6312. @see getFileName, getRelativePathFrom
  6313. */
  6314. const String& getFullPathName() const throw() { return fullPath; }
  6315. /** Returns the last section of the pathname.
  6316. Returns just the final part of the path - e.g. if the whole path
  6317. is "/moose/fish/foo.txt" this will return "foo.txt".
  6318. For a directory, it returns the final part of the path - e.g. for the
  6319. directory "/moose/fish" it'll return "fish".
  6320. If the filename begins with a dot, it'll return the whole filename, e.g. for
  6321. "/moose/.fish", it'll return ".fish"
  6322. @see getFullPathName, getFileNameWithoutExtension
  6323. */
  6324. const String getFileName() const;
  6325. /** Creates a relative path that refers to a file relatively to a given directory.
  6326. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  6327. would return "../../foo.txt".
  6328. If it's not possible to navigate from one file to the other, an absolute
  6329. path is returned. If the paths are invalid, an empty string may also be
  6330. returned.
  6331. @param directoryToBeRelativeTo the directory which the resultant string will
  6332. be relative to. If this is actually a file rather than
  6333. a directory, its parent directory will be used instead.
  6334. If it doesn't exist, it's assumed to be a directory.
  6335. @see getChildFile, isAbsolutePath
  6336. */
  6337. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  6338. /** Returns the file's extension.
  6339. Returns the file extension of this file, also including the dot.
  6340. e.g. "/moose/fish/foo.txt" would return ".txt"
  6341. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  6342. */
  6343. const String getFileExtension() const;
  6344. /** Checks whether the file has a given extension.
  6345. @param extensionToTest the extension to look for - it doesn't matter whether or
  6346. not this string has a dot at the start, so ".wav" and "wav"
  6347. will have the same effect. The comparison used is
  6348. case-insensitve. To compare with multiple extensions, this
  6349. parameter can contain multiple strings, separated by semi-colons -
  6350. so, for example: hasFileExtension (".jpeg;png;gif") would return
  6351. true if the file has any of those three extensions.
  6352. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  6353. */
  6354. bool hasFileExtension (const String& extensionToTest) const;
  6355. /** Returns a version of this file with a different file extension.
  6356. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  6357. @param newExtension the new extension, either with or without a dot at the start (this
  6358. doesn't make any difference). To get remove a file's extension altogether,
  6359. pass an empty string into this function.
  6360. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  6361. */
  6362. const File withFileExtension (const String& newExtension) const;
  6363. /** Returns the last part of the filename, without its file extension.
  6364. e.g. for "/moose/fish/foo.txt" this will return "foo".
  6365. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  6366. */
  6367. const String getFileNameWithoutExtension() const;
  6368. /** Returns a 32-bit hash-code that identifies this file.
  6369. This is based on the filename. Obviously it's possible, although unlikely, that
  6370. two files will have the same hash-code.
  6371. */
  6372. int hashCode() const;
  6373. /** Returns a 64-bit hash-code that identifies this file.
  6374. This is based on the filename. Obviously it's possible, although unlikely, that
  6375. two files will have the same hash-code.
  6376. */
  6377. int64 hashCode64() const;
  6378. /** Returns a file based on a relative path.
  6379. This will find a child file or directory of the current object.
  6380. e.g.
  6381. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  6382. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  6383. If the string is actually an absolute path, it will be treated as such, e.g.
  6384. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  6385. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  6386. */
  6387. const File getChildFile (String relativePath) const;
  6388. /** Returns a file which is in the same directory as this one.
  6389. This is equivalent to getParentDirectory().getChildFile (name).
  6390. @see getChildFile, getParentDirectory
  6391. */
  6392. const File getSiblingFile (const String& siblingFileName) const;
  6393. /** Returns the directory that contains this file or directory.
  6394. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  6395. */
  6396. const File getParentDirectory() const;
  6397. /** Checks whether a file is somewhere inside a directory.
  6398. Returns true if this file is somewhere inside a subdirectory of the directory
  6399. that is passed in. Neither file actually has to exist, because the function
  6400. just checks the paths for similarities.
  6401. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  6402. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  6403. */
  6404. bool isAChildOf (const File& potentialParentDirectory) const;
  6405. /** Chooses a filename relative to this one that doesn't already exist.
  6406. If this file is a directory, this will return a child file of this
  6407. directory that doesn't exist, by adding numbers to a prefix and suffix until
  6408. it finds one that isn't already there.
  6409. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  6410. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  6411. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  6412. @param prefix the string to use for the filename before the number
  6413. @param suffix the string to add to the filename after the number
  6414. @param putNumbersInBrackets if true, this will create filenames in the
  6415. format "prefix(number)suffix", if false, it will leave the
  6416. brackets out.
  6417. */
  6418. const File getNonexistentChildFile (const String& prefix,
  6419. const String& suffix,
  6420. bool putNumbersInBrackets = true) const;
  6421. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  6422. If this file doesn't exist, this will just return itself, otherwise it
  6423. will return an appropriate sibling that doesn't exist, e.g. if a file
  6424. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  6425. @param putNumbersInBrackets whether to add brackets around the numbers that
  6426. get appended to the new filename.
  6427. */
  6428. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  6429. /** Compares the pathnames for two files. */
  6430. bool operator== (const File& otherFile) const;
  6431. /** Compares the pathnames for two files. */
  6432. bool operator!= (const File& otherFile) const;
  6433. /** Compares the pathnames for two files. */
  6434. bool operator< (const File& otherFile) const;
  6435. /** Compares the pathnames for two files. */
  6436. bool operator> (const File& otherFile) const;
  6437. /** Checks whether a file can be created or written to.
  6438. @returns true if it's possible to create and write to this file. If the file
  6439. doesn't already exist, this will check its parent directory to
  6440. see if writing is allowed.
  6441. @see setReadOnly
  6442. */
  6443. bool hasWriteAccess() const;
  6444. /** Changes the write-permission of a file or directory.
  6445. @param shouldBeReadOnly whether to add or remove write-permission
  6446. @param applyRecursively if the file is a directory and this is true, it will
  6447. recurse through all the subfolders changing the permissions
  6448. of all files
  6449. @returns true if it manages to change the file's permissions.
  6450. @see hasWriteAccess
  6451. */
  6452. bool setReadOnly (bool shouldBeReadOnly,
  6453. bool applyRecursively = false) const;
  6454. /** Returns true if this file is a hidden or system file.
  6455. The criteria for deciding whether a file is hidden are platform-dependent.
  6456. */
  6457. bool isHidden() const;
  6458. /** If this file is a link, this returns the file that it points to.
  6459. If this file isn't actually link, it'll just return itself.
  6460. */
  6461. const File getLinkedTarget() const;
  6462. /** Returns the last modification time of this file.
  6463. @returns the time, or an invalid time if the file doesn't exist.
  6464. @see setLastModificationTime, getLastAccessTime, getCreationTime
  6465. */
  6466. const Time getLastModificationTime() const;
  6467. /** Returns the last time this file was accessed.
  6468. @returns the time, or an invalid time if the file doesn't exist.
  6469. @see setLastAccessTime, getLastModificationTime, getCreationTime
  6470. */
  6471. const Time getLastAccessTime() const;
  6472. /** Returns the time that this file was created.
  6473. @returns the time, or an invalid time if the file doesn't exist.
  6474. @see getLastModificationTime, getLastAccessTime
  6475. */
  6476. const Time getCreationTime() const;
  6477. /** Changes the modification time for this file.
  6478. @param newTime the time to apply to the file
  6479. @returns true if it manages to change the file's time.
  6480. @see getLastModificationTime, setLastAccessTime, setCreationTime
  6481. */
  6482. bool setLastModificationTime (const Time& newTime) const;
  6483. /** Changes the last-access time for this file.
  6484. @param newTime the time to apply to the file
  6485. @returns true if it manages to change the file's time.
  6486. @see getLastAccessTime, setLastModificationTime, setCreationTime
  6487. */
  6488. bool setLastAccessTime (const Time& newTime) const;
  6489. /** Changes the creation date for this file.
  6490. @param newTime the time to apply to the file
  6491. @returns true if it manages to change the file's time.
  6492. @see getCreationTime, setLastModificationTime, setLastAccessTime
  6493. */
  6494. bool setCreationTime (const Time& newTime) const;
  6495. /** If possible, this will try to create a version string for the given file.
  6496. The OS may be able to look at the file and give a version for it - e.g. with
  6497. executables, bundles, dlls, etc. If no version is available, this will
  6498. return an empty string.
  6499. */
  6500. const String getVersion() const;
  6501. /** Creates an empty file if it doesn't already exist.
  6502. If the file that this object refers to doesn't exist, this will create a file
  6503. of zero size.
  6504. If it already exists or is a directory, this method will do nothing.
  6505. @returns true if the file has been created (or if it already existed).
  6506. @see createDirectory
  6507. */
  6508. bool create() const;
  6509. /** Creates a new directory for this filename.
  6510. This will try to create the file as a directory, and fill also create
  6511. any parent directories it needs in order to complete the operation.
  6512. @returns true if the directory has been created successfully, (or if it
  6513. already existed beforehand).
  6514. @see create
  6515. */
  6516. bool createDirectory() const;
  6517. /** Deletes a file.
  6518. If this file is actually a directory, it may not be deleted correctly if it
  6519. contains files. See deleteRecursively() as a better way of deleting directories.
  6520. @returns true if the file has been successfully deleted (or if it didn't exist to
  6521. begin with).
  6522. @see deleteRecursively
  6523. */
  6524. bool deleteFile() const;
  6525. /** Deletes a file or directory and all its subdirectories.
  6526. If this file is a directory, this will try to delete it and all its subfolders. If
  6527. it's just a file, it will just try to delete the file.
  6528. @returns true if the file and all its subfolders have been successfully deleted
  6529. (or if it didn't exist to begin with).
  6530. @see deleteFile
  6531. */
  6532. bool deleteRecursively() const;
  6533. /** Moves this file or folder to the trash.
  6534. @returns true if the operation succeeded. It could fail if the trash is full, or
  6535. if the file is write-protected, so you should check the return value
  6536. and act appropriately.
  6537. */
  6538. bool moveToTrash() const;
  6539. /** Moves or renames a file.
  6540. Tries to move a file to a different location.
  6541. If the target file already exists, this will attempt to delete it first, and
  6542. will fail if this can't be done.
  6543. Note that the destination file isn't the directory to put it in, it's the actual
  6544. filename that you want the new file to have.
  6545. @returns true if the operation succeeds
  6546. */
  6547. bool moveFileTo (const File& targetLocation) const;
  6548. /** Copies a file.
  6549. Tries to copy a file to a different location.
  6550. If the target file already exists, this will attempt to delete it first, and
  6551. will fail if this can't be done.
  6552. @returns true if the operation succeeds
  6553. */
  6554. bool copyFileTo (const File& targetLocation) const;
  6555. /** Copies a directory.
  6556. Tries to copy an entire directory, recursively.
  6557. If this file isn't a directory or if any target files can't be created, this
  6558. will return false.
  6559. @param newDirectory the directory that this one should be copied to. Note that this
  6560. is the name of the actual directory to create, not the directory
  6561. into which the new one should be placed, so there must be enough
  6562. write privileges to create it if it doesn't exist. Any files inside
  6563. it will be overwritten by similarly named ones that are copied.
  6564. */
  6565. bool copyDirectoryTo (const File& newDirectory) const;
  6566. /** Used in file searching, to specify whether to return files, directories, or both.
  6567. */
  6568. enum TypesOfFileToFind
  6569. {
  6570. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  6571. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  6572. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  6573. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  6574. };
  6575. /** Searches inside a directory for files matching a wildcard pattern.
  6576. Assuming that this file is a directory, this method will search it
  6577. for either files or subdirectories whose names match a filename pattern.
  6578. @param results an array to which File objects will be added for the
  6579. files that the search comes up with
  6580. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6581. return files, directories, or both. If the ignoreHiddenFiles flag
  6582. is also added to this value, hidden files won't be returned
  6583. @param searchRecursively if true, all subdirectories will be recursed into to do
  6584. an exhaustive search
  6585. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6586. @returns the number of results that have been found
  6587. @see getNumberOfChildFiles, DirectoryIterator
  6588. */
  6589. int findChildFiles (Array<File>& results,
  6590. int whatToLookFor,
  6591. bool searchRecursively,
  6592. const String& wildCardPattern = "*") const;
  6593. /** Searches inside a directory and counts how many files match a wildcard pattern.
  6594. Assuming that this file is a directory, this method will search it
  6595. for either files or subdirectories whose names match a filename pattern,
  6596. and will return the number of matches found.
  6597. This isn't a recursive call, and will only search this directory, not
  6598. its children.
  6599. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6600. count files, directories, or both. If the ignoreHiddenFiles flag
  6601. is also added to this value, hidden files won't be counted
  6602. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6603. @returns the number of matches found
  6604. @see findChildFiles, DirectoryIterator
  6605. */
  6606. int getNumberOfChildFiles (int whatToLookFor,
  6607. const String& wildCardPattern = "*") const;
  6608. /** Returns true if this file is a directory that contains one or more subdirectories.
  6609. @see isDirectory, findChildFiles
  6610. */
  6611. bool containsSubDirectories() const;
  6612. /** Creates a stream to read from this file.
  6613. @returns a stream that will read from this file (initially positioned at the
  6614. start of the file), or 0 if the file can't be opened for some reason
  6615. @see createOutputStream, loadFileAsData
  6616. */
  6617. FileInputStream* createInputStream() const;
  6618. /** Creates a stream to write to this file.
  6619. If the file exists, the stream that is returned will be positioned ready for
  6620. writing at the end of the file, so you might want to use deleteFile() first
  6621. to write to an empty file.
  6622. @returns a stream that will write to this file (initially positioned at the
  6623. end of the file), or 0 if the file can't be opened for some reason
  6624. @see createInputStream, appendData, appendText
  6625. */
  6626. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  6627. /** Loads a file's contents into memory as a block of binary data.
  6628. Of course, trying to load a very large file into memory will blow up, so
  6629. it's better to check first.
  6630. @param result the data block to which the file's contents should be appended - note
  6631. that if the memory block might already contain some data, you
  6632. might want to clear it first
  6633. @returns true if the file could all be read into memory
  6634. */
  6635. bool loadFileAsData (MemoryBlock& result) const;
  6636. /** Reads a file into memory as a string.
  6637. Attempts to load the entire file as a zero-terminated string.
  6638. This makes use of InputStream::readEntireStreamAsString, which should
  6639. automatically cope with unicode/acsii file formats.
  6640. */
  6641. const String loadFileAsString() const;
  6642. /** Appends a block of binary data to the end of the file.
  6643. This will try to write the given buffer to the end of the file.
  6644. @returns false if it can't write to the file for some reason
  6645. */
  6646. bool appendData (const void* dataToAppend,
  6647. int numberOfBytes) const;
  6648. /** Replaces this file's contents with a given block of data.
  6649. This will delete the file and replace it with the given data.
  6650. A nice feature of this method is that it's safe - instead of deleting
  6651. the file first and then re-writing it, it creates a new temporary file,
  6652. writes the data to that, and then moves the new file to replace the existing
  6653. file. This means that if the power gets pulled out or something crashes,
  6654. you're a lot less likely to end up with an empty file..
  6655. Returns true if the operation succeeds, or false if it fails.
  6656. @see appendText
  6657. */
  6658. bool replaceWithData (const void* dataToWrite,
  6659. int numberOfBytes) const;
  6660. /** Appends a string to the end of the file.
  6661. This will try to append a text string to the file, as either 16-bit unicode
  6662. or 8-bit characters in the default system encoding.
  6663. It can also write the 'ff fe' unicode header bytes before the text to indicate
  6664. the endianness of the file.
  6665. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  6666. @see replaceWithText
  6667. */
  6668. bool appendText (const String& textToAppend,
  6669. bool asUnicode = false,
  6670. bool writeUnicodeHeaderBytes = false) const;
  6671. /** Replaces this file's contents with a given text string.
  6672. This will delete the file and replace it with the given text.
  6673. A nice feature of this method is that it's safe - instead of deleting
  6674. the file first and then re-writing it, it creates a new temporary file,
  6675. writes the text to that, and then moves the new file to replace the existing
  6676. file. This means that if the power gets pulled out or something crashes,
  6677. you're a lot less likely to end up with an empty file..
  6678. For an explanation of the parameters here, see the appendText() method.
  6679. Returns true if the operation succeeds, or false if it fails.
  6680. @see appendText
  6681. */
  6682. bool replaceWithText (const String& textToWrite,
  6683. bool asUnicode = false,
  6684. bool writeUnicodeHeaderBytes = false) const;
  6685. /** Attempts to scan the contents of this file and compare it to another file, returning
  6686. true if this is possible and they match byte-for-byte.
  6687. */
  6688. bool hasIdenticalContentTo (const File& other) const;
  6689. /** Creates a set of files to represent each file root.
  6690. e.g. on Windows this will create files for "c:\", "d:\" etc according
  6691. to which ones are available. On the Mac/Linux, this will probably
  6692. just add a single entry for "/".
  6693. */
  6694. static void findFileSystemRoots (Array<File>& results);
  6695. /** Finds the name of the drive on which this file lives.
  6696. @returns the volume label of the drive, or an empty string if this isn't possible
  6697. */
  6698. const String getVolumeLabel() const;
  6699. /** Returns the serial number of the volume on which this file lives.
  6700. @returns the serial number, or zero if there's a problem doing this
  6701. */
  6702. int getVolumeSerialNumber() const;
  6703. /** Returns the number of bytes free on the drive that this file lives on.
  6704. @returns the number of bytes free, or 0 if there's a problem finding this out
  6705. @see getVolumeTotalSize
  6706. */
  6707. int64 getBytesFreeOnVolume() const;
  6708. /** Returns the total size of the drive that contains this file.
  6709. @returns the total number of bytes that the volume can hold
  6710. @see getBytesFreeOnVolume
  6711. */
  6712. int64 getVolumeTotalSize() const;
  6713. /** Returns true if this file is on a CD or DVD drive. */
  6714. bool isOnCDRomDrive() const;
  6715. /** Returns true if this file is on a hard disk.
  6716. This will fail if it's a network drive, but will still be true for
  6717. removable hard-disks.
  6718. */
  6719. bool isOnHardDisk() const;
  6720. /** Returns true if this file is on a removable disk drive.
  6721. This might be a usb-drive, a CD-rom, or maybe a network drive.
  6722. */
  6723. bool isOnRemovableDrive() const;
  6724. /** Launches the file as a process.
  6725. - if the file is executable, this will run it.
  6726. - if it's a document of some kind, it will launch the document with its
  6727. default viewer application.
  6728. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  6729. @see revealToUser
  6730. */
  6731. bool startAsProcess (const String& parameters = String::empty) const;
  6732. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  6733. @see startAsProcess
  6734. */
  6735. void revealToUser() const;
  6736. /** A set of types of location that can be passed to the getSpecialLocation() method.
  6737. */
  6738. enum SpecialLocationType
  6739. {
  6740. /** The user's home folder. This is the same as using File ("~"). */
  6741. userHomeDirectory,
  6742. /** The user's default documents folder. On Windows, this might be the user's
  6743. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  6744. doesn't tend to have one of these, so it might just return their home folder.
  6745. */
  6746. userDocumentsDirectory,
  6747. /** The folder that contains the user's desktop objects. */
  6748. userDesktopDirectory,
  6749. /** The folder in which applications store their persistent user-specific settings.
  6750. On Windows, this might be "\Documents and Settings\username\Application Data".
  6751. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  6752. always create your own sub-folder to put them in, to avoid making a mess.
  6753. */
  6754. userApplicationDataDirectory,
  6755. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  6756. of the computer, rather than just the current user.
  6757. On the Mac it'll be "/Library", on Windows, it could be something like
  6758. "\Documents and Settings\All Users\Application Data".
  6759. Depending on the setup, this folder may be read-only.
  6760. */
  6761. commonApplicationDataDirectory,
  6762. /** The folder that should be used for temporary files.
  6763. Always delete them when you're finished, to keep the user's computer tidy!
  6764. */
  6765. tempDirectory,
  6766. /** Returns this application's executable file.
  6767. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6768. host app.
  6769. On the mac this will return the unix binary, not the package folder - see
  6770. currentApplicationFile for that.
  6771. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  6772. file link, invokedExecutableFile will return the name of the link.
  6773. */
  6774. currentExecutableFile,
  6775. /** Returns this application's location.
  6776. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6777. host app.
  6778. On the mac this will return the package folder (if it's in one), not the unix binary
  6779. that's inside it - compare with currentExecutableFile.
  6780. */
  6781. currentApplicationFile,
  6782. /** Returns the file that was invoked to launch this executable.
  6783. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  6784. will return the name of the link that was used, whereas currentExecutableFile will return
  6785. the actual location of the target executable.
  6786. */
  6787. invokedExecutableFile,
  6788. /** The directory in which applications normally get installed.
  6789. So on windows, this would be something like "c:\program files", on the
  6790. Mac "/Applications", or "/usr" on linux.
  6791. */
  6792. globalApplicationsDirectory,
  6793. /** The most likely place where a user might store their music files.
  6794. */
  6795. userMusicDirectory,
  6796. /** The most likely place where a user might store their movie files.
  6797. */
  6798. userMoviesDirectory,
  6799. };
  6800. /** Finds the location of a special type of file or directory, such as a home folder or
  6801. documents folder.
  6802. @see SpecialLocationType
  6803. */
  6804. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  6805. /** Returns a temporary file in the system's temp directory.
  6806. This will try to return the name of a non-existent temp file.
  6807. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  6808. */
  6809. static const File createTempFile (const String& fileNameEnding);
  6810. /** Returns the current working directory.
  6811. @see setAsCurrentWorkingDirectory
  6812. */
  6813. static const File getCurrentWorkingDirectory();
  6814. /** Sets the current working directory to be this file.
  6815. For this to work the file must point to a valid directory.
  6816. @returns true if the current directory has been changed.
  6817. @see getCurrentWorkingDirectory
  6818. */
  6819. bool setAsCurrentWorkingDirectory() const;
  6820. /** The system-specific file separator character.
  6821. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6822. */
  6823. static const juce_wchar separator;
  6824. /** The system-specific file separator character, as a string.
  6825. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6826. */
  6827. static const String separatorString;
  6828. /** Removes illegal characters from a filename.
  6829. This will return a copy of the given string after removing characters
  6830. that are not allowed in a legal filename, and possibly shortening the
  6831. string if it's too long.
  6832. Because this will remove slashes, don't use it on an absolute pathname.
  6833. @see createLegalPathName
  6834. */
  6835. static const String createLegalFileName (const String& fileNameToFix);
  6836. /** Removes illegal characters from a pathname.
  6837. Similar to createLegalFileName(), but this won't remove slashes, so can
  6838. be used on a complete pathname.
  6839. @see createLegalFileName
  6840. */
  6841. static const String createLegalPathName (const String& pathNameToFix);
  6842. /** Indicates whether filenames are case-sensitive on the current operating system.
  6843. */
  6844. static bool areFileNamesCaseSensitive();
  6845. /** Returns true if the string seems to be a fully-specified absolute path.
  6846. */
  6847. static bool isAbsolutePath (const String& path);
  6848. /** Creates a file that simply contains this string, without doing the sanity-checking
  6849. that the normal constructors do.
  6850. Best to avoid this unless you really know what you're doing.
  6851. */
  6852. static const File createFileWithoutCheckingPath (const String& path);
  6853. /** Adds a separator character to the end of a path if it doesn't already have one. */
  6854. static const String addTrailingSeparator (const String& path);
  6855. juce_UseDebuggingNewOperator
  6856. private:
  6857. String fullPath;
  6858. // internal way of contructing a file without checking the path
  6859. friend class DirectoryIterator;
  6860. File (const String&, int);
  6861. const String getPathUpToLastSlash() const;
  6862. void createDirectoryInternal (const String& fileName) const;
  6863. bool copyInternal (const File& dest) const;
  6864. bool moveInternal (const File& dest) const;
  6865. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  6866. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  6867. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  6868. static const String parseAbsolutePath (const String& path);
  6869. static bool fileTypeMatches (int whatToLookFor, bool isDir, bool isHidden);
  6870. };
  6871. #endif // __JUCE_FILE_JUCEHEADER__
  6872. /*** End of inlined file: juce_File.h ***/
  6873. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  6874. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6875. will be the name of a pointer to each child element.
  6876. E.g. @code
  6877. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6878. forEachXmlChildElement (*myParentXml, child)
  6879. {
  6880. if (child->hasTagName ("FOO"))
  6881. doSomethingWithXmlElement (child);
  6882. }
  6883. @endcode
  6884. @see forEachXmlChildElementWithTagName
  6885. */
  6886. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  6887. \
  6888. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  6889. childElementVariableName != 0; \
  6890. childElementVariableName = childElementVariableName->getNextElement())
  6891. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  6892. which have a specified tag.
  6893. This does the same job as the forEachXmlChildElement macro, but only for those
  6894. elements that have a particular tag name.
  6895. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  6896. will be the name of a pointer to each child element. The requiredTagName is the
  6897. tag name to match.
  6898. E.g. @code
  6899. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  6900. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  6901. {
  6902. // the child object is now guaranteed to be a <MYTAG> element..
  6903. doSomethingWithMYTAGElement (child);
  6904. }
  6905. @endcode
  6906. @see forEachXmlChildElement
  6907. */
  6908. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  6909. \
  6910. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  6911. childElementVariableName != 0; \
  6912. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  6913. /** Used to build a tree of elements representing an XML document.
  6914. An XML document can be parsed into a tree of XmlElements, each of which
  6915. represents an XML tag structure, and which may itself contain other
  6916. nested elements.
  6917. An XmlElement can also be converted back into a text document, and has
  6918. lots of useful methods for manipulating its attributes and sub-elements,
  6919. so XmlElements can actually be used as a handy general-purpose data
  6920. structure.
  6921. Here's an example of parsing some elements: @code
  6922. // check we're looking at the right kind of document..
  6923. if (myElement->hasTagName ("ANIMALS"))
  6924. {
  6925. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  6926. forEachXmlChildElement (*myElement, e)
  6927. {
  6928. if (e->hasTagName ("GIRAFFE"))
  6929. {
  6930. // found a giraffe, so use some of its attributes..
  6931. String giraffeName = e->getStringAttribute ("name");
  6932. int giraffeAge = e->getIntAttribute ("age");
  6933. bool isFriendly = e->getBoolAttribute ("friendly");
  6934. }
  6935. }
  6936. }
  6937. @endcode
  6938. And here's an example of how to create an XML document from scratch: @code
  6939. // create an outer node called "ANIMALS"
  6940. XmlElement animalsList ("ANIMALS");
  6941. for (int i = 0; i < numAnimals; ++i)
  6942. {
  6943. // create an inner element..
  6944. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  6945. giraffe->setAttribute ("name", "nigel");
  6946. giraffe->setAttribute ("age", 10);
  6947. giraffe->setAttribute ("friendly", true);
  6948. // ..and add our new element to the parent node
  6949. animalsList.addChildElement (giraffe);
  6950. }
  6951. // now we can turn the whole thing into a text document..
  6952. String myXmlDoc = animalsList.createDocument (String::empty);
  6953. @endcode
  6954. @see XmlDocument
  6955. */
  6956. class JUCE_API XmlElement
  6957. {
  6958. public:
  6959. /** Creates an XmlElement with this tag name. */
  6960. explicit XmlElement (const String& tagName) throw();
  6961. /** Creates a (deep) copy of another element. */
  6962. XmlElement (const XmlElement& other);
  6963. /** Creates a (deep) copy of another element. */
  6964. XmlElement& operator= (const XmlElement& other);
  6965. /** Deleting an XmlElement will also delete all its child elements. */
  6966. ~XmlElement() throw();
  6967. /** Compares two XmlElements to see if they contain the same text and attiributes.
  6968. The elements are only considered equivalent if they contain the same attiributes
  6969. with the same values, and have the same sub-nodes.
  6970. @param other the other element to compare to
  6971. @param ignoreOrderOfAttributes if true, this means that two elements with the
  6972. same attributes in a different order will be
  6973. considered the same; if false, the attributes must
  6974. be in the same order as well
  6975. */
  6976. bool isEquivalentTo (const XmlElement* other,
  6977. bool ignoreOrderOfAttributes) const throw();
  6978. /** Returns an XML text document that represents this element.
  6979. The string returned can be parsed to recreate the same XmlElement that
  6980. was used to create it.
  6981. @param dtdToUse the DTD to add to the document
  6982. @param allOnOneLine if true, this means that the document will not contain any
  6983. linefeeds, so it'll be smaller but not very easy to read.
  6984. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  6985. document
  6986. @param encodingType the character encoding format string to put into the xml
  6987. header
  6988. @param lineWrapLength the line length that will be used before items get placed on
  6989. a new line. This isn't an absolute maximum length, it just
  6990. determines how lists of attributes get broken up
  6991. @see writeToStream, writeToFile
  6992. */
  6993. const String createDocument (const String& dtdToUse,
  6994. bool allOnOneLine = false,
  6995. bool includeXmlHeader = true,
  6996. const String& encodingType = "UTF-8",
  6997. int lineWrapLength = 60) const;
  6998. /** Writes the document to a stream as UTF-8.
  6999. @param output the stream to write to
  7000. @param dtdToUse the DTD to add to the document
  7001. @param allOnOneLine if true, this means that the document will not contain any
  7002. linefeeds, so it'll be smaller but not very easy to read.
  7003. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7004. document
  7005. @param encodingType the character encoding format string to put into the xml
  7006. header
  7007. @param lineWrapLength the line length that will be used before items get placed on
  7008. a new line. This isn't an absolute maximum length, it just
  7009. determines how lists of attributes get broken up
  7010. @see writeToFile, createDocument
  7011. */
  7012. void writeToStream (OutputStream& output,
  7013. const String& dtdToUse,
  7014. bool allOnOneLine = false,
  7015. bool includeXmlHeader = true,
  7016. const String& encodingType = "UTF-8",
  7017. int lineWrapLength = 60) const;
  7018. /** Writes the element to a file as an XML document.
  7019. To improve safety in case something goes wrong while writing the file, this
  7020. will actually write the document to a new temporary file in the same
  7021. directory as the destination file, and if this succeeds, it will rename this
  7022. new file as the destination file (overwriting any existing file that was there).
  7023. @param destinationFile the file to write to. If this already exists, it will be
  7024. overwritten.
  7025. @param dtdToUse the DTD to add to the document
  7026. @param encodingType the character encoding format string to put into the xml
  7027. header
  7028. @param lineWrapLength the line length that will be used before items get placed on
  7029. a new line. This isn't an absolute maximum length, it just
  7030. determines how lists of attributes get broken up
  7031. @returns true if the file is written successfully; false if something goes wrong
  7032. in the process
  7033. @see createDocument
  7034. */
  7035. bool writeToFile (const File& destinationFile,
  7036. const String& dtdToUse,
  7037. const String& encodingType = "UTF-8",
  7038. int lineWrapLength = 60) const;
  7039. /** Returns this element's tag type name.
  7040. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7041. "MOOSE".
  7042. @see hasTagName
  7043. */
  7044. inline const String& getTagName() const throw() { return tagName; }
  7045. /** Tests whether this element has a particular tag name.
  7046. @param possibleTagName the tag name you're comparing it with
  7047. @see getTagName
  7048. */
  7049. bool hasTagName (const String& possibleTagName) const throw();
  7050. /** Returns the number of XML attributes this element contains.
  7051. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7052. return 2.
  7053. */
  7054. int getNumAttributes() const throw();
  7055. /** Returns the name of one of the elements attributes.
  7056. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7057. getAttributeName(1) would return "antlers".
  7058. @see getAttributeValue, getStringAttribute
  7059. */
  7060. const String& getAttributeName (int attributeIndex) const throw();
  7061. /** Returns the value of one of the elements attributes.
  7062. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7063. getAttributeName(1) would return "2".
  7064. @see getAttributeName, getStringAttribute
  7065. */
  7066. const String& getAttributeValue (int attributeIndex) const throw();
  7067. // Attribute-handling methods..
  7068. /** Checks whether the element contains an attribute with a certain name. */
  7069. bool hasAttribute (const String& attributeName) const throw();
  7070. /** Returns the value of a named attribute.
  7071. @param attributeName the name of the attribute to look up
  7072. */
  7073. const String& getStringAttribute (const String& attributeName) const throw();
  7074. /** Returns the value of a named attribute.
  7075. @param attributeName the name of the attribute to look up
  7076. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7077. with this name
  7078. */
  7079. const String getStringAttribute (const String& attributeName,
  7080. const String& defaultReturnValue) const;
  7081. /** Compares the value of a named attribute with a value passed-in.
  7082. @param attributeName the name of the attribute to look up
  7083. @param stringToCompareAgainst the value to compare it with
  7084. @param ignoreCase whether the comparison should be case-insensitive
  7085. @returns true if the value of the attribute is the same as the string passed-in;
  7086. false if it's different (or if no such attribute exists)
  7087. */
  7088. bool compareAttribute (const String& attributeName,
  7089. const String& stringToCompareAgainst,
  7090. bool ignoreCase = false) const throw();
  7091. /** Returns the value of a named attribute as an integer.
  7092. This will try to find the attribute and convert it to an integer (using
  7093. the String::getIntValue() method).
  7094. @param attributeName the name of the attribute to look up
  7095. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7096. with this name
  7097. @see setAttribute
  7098. */
  7099. int getIntAttribute (const String& attributeName,
  7100. int defaultReturnValue = 0) const;
  7101. /** Returns the value of a named attribute as floating-point.
  7102. This will try to find the attribute and convert it to an integer (using
  7103. the String::getDoubleValue() method).
  7104. @param attributeName the name of the attribute to look up
  7105. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7106. with this name
  7107. @see setAttribute
  7108. */
  7109. double getDoubleAttribute (const String& attributeName,
  7110. double defaultReturnValue = 0.0) const;
  7111. /** Returns the value of a named attribute as a boolean.
  7112. This will try to find the attribute and interpret it as a boolean. To do this,
  7113. it'll return true if the value is "1", "true", "y", etc, or false for other
  7114. values.
  7115. @param attributeName the name of the attribute to look up
  7116. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7117. with this name
  7118. */
  7119. bool getBoolAttribute (const String& attributeName,
  7120. bool defaultReturnValue = false) const;
  7121. /** Adds a named attribute to the element.
  7122. If the element already contains an attribute with this name, it's value will
  7123. be updated to the new value. If there's no such attribute yet, a new one will
  7124. be added.
  7125. Note that there are other setAttribute() methods that take integers,
  7126. doubles, etc. to make it easy to store numbers.
  7127. @param attributeName the name of the attribute to set
  7128. @param newValue the value to set it to
  7129. @see removeAttribute
  7130. */
  7131. void setAttribute (const String& attributeName,
  7132. const String& newValue);
  7133. /** Adds a named attribute to the element, setting it to an integer value.
  7134. If the element already contains an attribute with this name, it's value will
  7135. be updated to the new value. If there's no such attribute yet, a new one will
  7136. be added.
  7137. Note that there are other setAttribute() methods that take integers,
  7138. doubles, etc. to make it easy to store numbers.
  7139. @param attributeName the name of the attribute to set
  7140. @param newValue the value to set it to
  7141. */
  7142. void setAttribute (const String& attributeName,
  7143. int newValue);
  7144. /** Adds a named attribute to the element, setting it to a floating-point value.
  7145. If the element already contains an attribute with this name, it's value will
  7146. be updated to the new value. If there's no such attribute yet, a new one will
  7147. be added.
  7148. Note that there are other setAttribute() methods that take integers,
  7149. doubles, etc. to make it easy to store numbers.
  7150. @param attributeName the name of the attribute to set
  7151. @param newValue the value to set it to
  7152. */
  7153. void setAttribute (const String& attributeName,
  7154. double newValue);
  7155. /** Removes a named attribute from the element.
  7156. @param attributeName the name of the attribute to remove
  7157. @see removeAllAttributes
  7158. */
  7159. void removeAttribute (const String& attributeName) throw();
  7160. /** Removes all attributes from this element.
  7161. */
  7162. void removeAllAttributes() throw();
  7163. // Child element methods..
  7164. /** Returns the first of this element's sub-elements.
  7165. see getNextElement() for an example of how to iterate the sub-elements.
  7166. @see forEachXmlChildElement
  7167. */
  7168. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7169. /** Returns the next of this element's siblings.
  7170. This can be used for iterating an element's sub-elements, e.g.
  7171. @code
  7172. XmlElement* child = myXmlDocument->getFirstChildElement();
  7173. while (child != 0)
  7174. {
  7175. ...do stuff with this child..
  7176. child = child->getNextElement();
  7177. }
  7178. @endcode
  7179. Note that when iterating the child elements, some of them might be
  7180. text elements as well as XML tags - use isTextElement() to work this
  7181. out.
  7182. Also, it's much easier and neater to use this method indirectly via the
  7183. forEachXmlChildElement macro.
  7184. @returns the sibling element that follows this one, or zero if this is the last
  7185. element in its parent
  7186. @see getNextElement, isTextElement, forEachXmlChildElement
  7187. */
  7188. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7189. /** Returns the next of this element's siblings which has the specified tag
  7190. name.
  7191. This is like getNextElement(), but will scan through the list until it
  7192. finds an element with the given tag name.
  7193. @see getNextElement, forEachXmlChildElementWithTagName
  7194. */
  7195. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  7196. /** Returns the number of sub-elements in this element.
  7197. @see getChildElement
  7198. */
  7199. int getNumChildElements() const throw();
  7200. /** Returns the sub-element at a certain index.
  7201. It's not very efficient to iterate the sub-elements by index - see
  7202. getNextElement() for an example of how best to iterate.
  7203. @returns the n'th child of this element, or 0 if the index is out-of-range
  7204. @see getNextElement, isTextElement, getChildByName
  7205. */
  7206. XmlElement* getChildElement (int index) const throw();
  7207. /** Returns the first sub-element with a given tag-name.
  7208. @param tagNameToLookFor the tag name of the element you want to find
  7209. @returns the first element with this tag name, or 0 if none is found
  7210. @see getNextElement, isTextElement, getChildElement
  7211. */
  7212. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  7213. /** Appends an element to this element's list of children.
  7214. Child elements are deleted automatically when their parent is deleted, so
  7215. make sure the object that you pass in will not be deleted by anything else,
  7216. and make sure it's not already the child of another element.
  7217. @see getFirstChildElement, getNextElement, getNumChildElements,
  7218. getChildElement, removeChildElement
  7219. */
  7220. void addChildElement (XmlElement* const newChildElement) throw();
  7221. /** Inserts an element into this element's list of children.
  7222. Child elements are deleted automatically when their parent is deleted, so
  7223. make sure the object that you pass in will not be deleted by anything else,
  7224. and make sure it's not already the child of another element.
  7225. @param newChildNode the element to add
  7226. @param indexToInsertAt the index at which to insert the new element - if this is
  7227. below zero, it will be added to the end of the list
  7228. @see addChildElement, insertChildElement
  7229. */
  7230. void insertChildElement (XmlElement* newChildNode,
  7231. int indexToInsertAt) throw();
  7232. /** Creates a new element with the given name and returns it, after adding it
  7233. as a child element.
  7234. This is a handy method that means that instead of writing this:
  7235. @code
  7236. XmlElement* newElement = new XmlElement ("foobar");
  7237. myParentElement->addChildElement (newElement);
  7238. @endcode
  7239. ..you could just write this:
  7240. @code
  7241. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  7242. @endcode
  7243. */
  7244. XmlElement* createNewChildElement (const String& tagName);
  7245. /** Replaces one of this element's children with another node.
  7246. If the current element passed-in isn't actually a child of this element,
  7247. this will return false and the new one won't be added. Otherwise, the
  7248. existing element will be deleted, replaced with the new one, and it
  7249. will return true.
  7250. */
  7251. bool replaceChildElement (XmlElement* currentChildElement,
  7252. XmlElement* newChildNode) throw();
  7253. /** Removes a child element.
  7254. @param childToRemove the child to look for and remove
  7255. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7256. just remove it
  7257. */
  7258. void removeChildElement (XmlElement* childToRemove,
  7259. bool shouldDeleteTheChild) throw();
  7260. /** Deletes all the child elements in the element.
  7261. @see removeChildElement, deleteAllChildElementsWithTagName
  7262. */
  7263. void deleteAllChildElements() throw();
  7264. /** Deletes all the child elements with a given tag name.
  7265. @see removeChildElement
  7266. */
  7267. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  7268. /** Returns true if the given element is a child of this one. */
  7269. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7270. /** Recursively searches all sub-elements to find one that contains the specified
  7271. child element.
  7272. */
  7273. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  7274. /** Sorts the child elements using a comparator.
  7275. This will use a comparator object to sort the elements into order. The object
  7276. passed must have a method of the form:
  7277. @code
  7278. int compareElements (const XmlElement* first, const XmlElement* second);
  7279. @endcode
  7280. ..and this method must return:
  7281. - a value of < 0 if the first comes before the second
  7282. - a value of 0 if the two objects are equivalent
  7283. - a value of > 0 if the second comes before the first
  7284. To improve performance, the compareElements() method can be declared as static or const.
  7285. @param comparator the comparator to use for comparing elements.
  7286. @param retainOrderOfEquivalentItems if this is true, then items
  7287. which the comparator says are equivalent will be
  7288. kept in the order in which they currently appear
  7289. in the array. This is slower to perform, but may
  7290. be important in some cases. If it's false, a faster
  7291. algorithm is used, but equivalent elements may be
  7292. rearranged.
  7293. */
  7294. template <class ElementComparator>
  7295. void sortChildElements (ElementComparator& comparator,
  7296. bool retainOrderOfEquivalentItems = false)
  7297. {
  7298. const int num = getNumChildElements();
  7299. if (num > 1)
  7300. {
  7301. HeapBlock <XmlElement*> elems (num);
  7302. getChildElementsAsArray (elems);
  7303. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  7304. reorderChildElements (elems, num);
  7305. }
  7306. }
  7307. /** Returns true if this element is a section of text.
  7308. Elements can either be an XML tag element or a secton of text, so this
  7309. is used to find out what kind of element this one is.
  7310. @see getAllText, addTextElement, deleteAllTextElements
  7311. */
  7312. bool isTextElement() const throw();
  7313. /** Returns the text for a text element.
  7314. Note that if you have an element like this:
  7315. @code<xyz>hello</xyz>@endcode
  7316. then calling getText on the "xyz" element won't return "hello", because that is
  7317. actually stored in a special text sub-element inside the xyz element. To get the
  7318. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7319. use getAllSubText() to do this automatically.
  7320. @see isTextElement, getAllSubText, getChildElementAllSubText
  7321. */
  7322. const String& getText() const throw();
  7323. /** Sets the text in a text element.
  7324. Note that this is only a valid call if this element is a text element. If it's
  7325. not, then no action will be performed.
  7326. */
  7327. void setText (const String& newText);
  7328. /** Returns all the text from this element's child nodes.
  7329. This iterates all the child elements and when it finds text elements,
  7330. it concatenates their text into a big string which it returns.
  7331. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7332. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7333. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7334. */
  7335. const String getAllSubText() const;
  7336. /** Returns all the sub-text of a named child element.
  7337. If there is a child element with the given tag name, this will return
  7338. all of its sub-text (by calling getAllSubText() on it). If there is
  7339. no such child element, this will return the default string passed-in.
  7340. @see getAllSubText
  7341. */
  7342. const String getChildElementAllSubText (const String& childTagName,
  7343. const String& defaultReturnValue) const;
  7344. /** Appends a section of text to this element.
  7345. @see isTextElement, getText, getAllSubText
  7346. */
  7347. void addTextElement (const String& text);
  7348. /** Removes all the text elements from this element.
  7349. @see isTextElement, getText, getAllSubText, addTextElement
  7350. */
  7351. void deleteAllTextElements() throw();
  7352. /** Creates a text element that can be added to a parent element.
  7353. */
  7354. static XmlElement* createTextElement (const String& text);
  7355. juce_UseDebuggingNewOperator
  7356. private:
  7357. friend class XmlDocument;
  7358. String tagName;
  7359. XmlElement* firstChildElement;
  7360. XmlElement* nextElement;
  7361. struct XmlAttributeNode
  7362. {
  7363. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7364. XmlAttributeNode (const String& name, const String& value) throw();
  7365. String name, value;
  7366. XmlAttributeNode* next;
  7367. private:
  7368. XmlAttributeNode& operator= (const XmlAttributeNode&);
  7369. };
  7370. XmlAttributeNode* attributes;
  7371. XmlElement (int) throw();
  7372. void copyChildrenAndAttributesFrom (const XmlElement& other);
  7373. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  7374. void getChildElementsAsArray (XmlElement**) const throw();
  7375. void reorderChildElements (XmlElement** const, const int) throw();
  7376. };
  7377. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7378. /*** End of inlined file: juce_XmlElement.h ***/
  7379. /**
  7380. A set of named property values, which can be strings, integers, floating point, etc.
  7381. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7382. to load and save types other than strings.
  7383. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7384. messages and saves/loads the list from a file.
  7385. */
  7386. class JUCE_API PropertySet
  7387. {
  7388. public:
  7389. /** Creates an empty PropertySet.
  7390. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7391. case-insensitive way
  7392. */
  7393. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7394. /** Creates a copy of another PropertySet.
  7395. */
  7396. PropertySet (const PropertySet& other) throw();
  7397. /** Copies another PropertySet over this one.
  7398. */
  7399. PropertySet& operator= (const PropertySet& other) throw();
  7400. /** Destructor. */
  7401. virtual ~PropertySet();
  7402. /** Returns one of the properties as a string.
  7403. If the value isn't found in this set, then this will look for it in a fallback
  7404. property set (if you've specified one with the setFallbackPropertySet() method),
  7405. and if it can't find one there, it'll return the default value passed-in.
  7406. @param keyName the name of the property to retrieve
  7407. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7408. */
  7409. const String getValue (const String& keyName,
  7410. const String& defaultReturnValue = String::empty) const throw();
  7411. /** Returns one of the properties as an integer.
  7412. If the value isn't found in this set, then this will look for it in a fallback
  7413. property set (if you've specified one with the setFallbackPropertySet() method),
  7414. and if it can't find one there, it'll return the default value passed-in.
  7415. @param keyName the name of the property to retrieve
  7416. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7417. */
  7418. int getIntValue (const String& keyName,
  7419. const int defaultReturnValue = 0) const throw();
  7420. /** Returns one of the properties as an double.
  7421. If the value isn't found in this set, then this will look for it in a fallback
  7422. property set (if you've specified one with the setFallbackPropertySet() method),
  7423. and if it can't find one there, it'll return the default value passed-in.
  7424. @param keyName the name of the property to retrieve
  7425. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7426. */
  7427. double getDoubleValue (const String& keyName,
  7428. const double defaultReturnValue = 0.0) const throw();
  7429. /** Returns one of the properties as an boolean.
  7430. The result will be true if the string found for this key name can be parsed as a non-zero
  7431. integer.
  7432. If the value isn't found in this set, then this will look for it in a fallback
  7433. property set (if you've specified one with the setFallbackPropertySet() method),
  7434. and if it can't find one there, it'll return the default value passed-in.
  7435. @param keyName the name of the property to retrieve
  7436. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7437. */
  7438. bool getBoolValue (const String& keyName,
  7439. const bool defaultReturnValue = false) const throw();
  7440. /** Returns one of the properties as an XML element.
  7441. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7442. key isn't found, or if the entry contains an string that isn't valid XML.
  7443. If the value isn't found in this set, then this will look for it in a fallback
  7444. property set (if you've specified one with the setFallbackPropertySet() method),
  7445. and if it can't find one there, it'll return the default value passed-in.
  7446. @param keyName the name of the property to retrieve
  7447. */
  7448. XmlElement* getXmlValue (const String& keyName) const;
  7449. /** Sets a named property as a string.
  7450. @param keyName the name of the property to set. (This mustn't be an empty string)
  7451. @param value the new value to set it to
  7452. */
  7453. void setValue (const String& keyName, const String& value) throw();
  7454. /** Sets a named property to an integer.
  7455. @param keyName the name of the property to set. (This mustn't be an empty string)
  7456. @param value the new value to set it to
  7457. */
  7458. void setValue (const String& keyName, const int value) throw();
  7459. /** Sets a named property to a double.
  7460. @param keyName the name of the property to set. (This mustn't be an empty string)
  7461. @param value the new value to set it to
  7462. */
  7463. void setValue (const String& keyName, const double value) throw();
  7464. /** Sets a named property to a boolean.
  7465. @param keyName the name of the property to set. (This mustn't be an empty string)
  7466. @param value the new value to set it to
  7467. */
  7468. void setValue (const String& keyName, const bool value) throw();
  7469. /** Sets a named property to an XML element.
  7470. @param keyName the name of the property to set. (This mustn't be an empty string)
  7471. @param xml the new element to set it to. If this is zero, the value will be set to
  7472. an empty string
  7473. @see getXmlValue
  7474. */
  7475. void setValue (const String& keyName, const XmlElement* const xml);
  7476. /** Deletes a property.
  7477. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7478. */
  7479. void removeValue (const String& keyName) throw();
  7480. /** Returns true if the properies include the given key. */
  7481. bool containsKey (const String& keyName) const throw();
  7482. /** Removes all values. */
  7483. void clear();
  7484. /** Returns the keys/value pair array containing all the properties. */
  7485. StringPairArray& getAllProperties() throw() { return properties; }
  7486. /** Returns the lock used when reading or writing to this set */
  7487. const CriticalSection& getLock() const throw() { return lock; }
  7488. /** Returns an XML element which encapsulates all the items in this property set.
  7489. The string parameter is the tag name that should be used for the node.
  7490. @see restoreFromXml
  7491. */
  7492. XmlElement* createXml (const String& nodeName) const throw();
  7493. /** Reloads a set of properties that were previously stored as XML.
  7494. The node passed in must have been created by the createXml() method.
  7495. @see createXml
  7496. */
  7497. void restoreFromXml (const XmlElement& xml) throw();
  7498. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7499. set in this one.
  7500. If you set this up to be a pointer to a second property set, then whenever one
  7501. of the getValue() methods fails to find an entry in this set, it will look up that
  7502. value in the fallback set, and if it finds it, it will return that.
  7503. Make sure that you don't delete the fallback set while it's still being used by
  7504. another set! To remove the fallback set, just call this method with a null pointer.
  7505. @see getFallbackPropertySet
  7506. */
  7507. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7508. /** Returns the fallback property set.
  7509. @see setFallbackPropertySet
  7510. */
  7511. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7512. juce_UseDebuggingNewOperator
  7513. protected:
  7514. /** Subclasses can override this to be told when one of the properies has been changed.
  7515. */
  7516. virtual void propertyChanged();
  7517. private:
  7518. StringPairArray properties;
  7519. PropertySet* fallbackProperties;
  7520. CriticalSection lock;
  7521. bool ignoreCaseOfKeys;
  7522. };
  7523. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7524. /*** End of inlined file: juce_PropertySet.h ***/
  7525. #endif
  7526. #ifndef __JUCE_RANGE_JUCEHEADER__
  7527. /*** Start of inlined file: juce_Range.h ***/
  7528. #ifndef __JUCE_RANGE_JUCEHEADER__
  7529. #define __JUCE_RANGE_JUCEHEADER__
  7530. /** A general-purpose range object, that simply represents any linear range with
  7531. a start and end point.
  7532. The templated parameter is expected to be a primitive integer or floating point
  7533. type, though class types could also be used if they behave in a number-like way.
  7534. */
  7535. template <typename ValueType>
  7536. class Range
  7537. {
  7538. public:
  7539. /** Constructs an empty range. */
  7540. Range() throw()
  7541. : start (ValueType()), end (ValueType())
  7542. {
  7543. }
  7544. /** Constructs a range with given start and end values. */
  7545. Range (const ValueType start_, const ValueType end_) throw()
  7546. : start (start_), end (jmax (start_, end_))
  7547. {
  7548. }
  7549. /** Constructs a copy of another range. */
  7550. Range (const Range& other) throw()
  7551. : start (other.start), end (other.end)
  7552. {
  7553. }
  7554. /** Copies another range object. */
  7555. Range& operator= (const Range& other) throw()
  7556. {
  7557. start = other.start;
  7558. end = other.end;
  7559. return *this;
  7560. }
  7561. /** Destructor. */
  7562. ~Range() throw()
  7563. {
  7564. }
  7565. /** Returns the range that lies between two positions (in either order). */
  7566. static const Range between (const ValueType position1, const ValueType position2) throw()
  7567. {
  7568. return (position1 < position2) ? Range (position1, position2)
  7569. : Range (position2, position1);
  7570. }
  7571. /** Returns a range with the specified start position and a length of zero. */
  7572. static const Range emptyRange (const ValueType start) throw()
  7573. {
  7574. return Range (start, start);
  7575. }
  7576. /** Returns the start of the range. */
  7577. inline ValueType getStart() const throw() { return start; }
  7578. /** Returns the length of the range. */
  7579. inline ValueType getLength() const throw() { return end - start; }
  7580. /** Returns the end of the range. */
  7581. inline ValueType getEnd() const throw() { return end; }
  7582. /** Returns true if the range has a length of zero. */
  7583. inline bool isEmpty() const throw() { return start == end; }
  7584. /** Changes the start position of the range, leaving the end position unchanged.
  7585. If the new start position is higher than the current end of the range, the end point
  7586. will be pushed along to equal it, leaving an empty range at the new position.
  7587. */
  7588. void setStart (const ValueType newStart) throw()
  7589. {
  7590. start = newStart;
  7591. if (end < newStart)
  7592. end = newStart;
  7593. }
  7594. /** Returns a range with the same end as this one, but a different start.
  7595. If the new start position is higher than the current end of the range, the end point
  7596. will be pushed along to equal it, returning an empty range at the new position.
  7597. */
  7598. const Range withStart (const ValueType newStart) const throw()
  7599. {
  7600. return Range (newStart, jmax (newStart, end));
  7601. }
  7602. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7603. const Range movedToStartAt (const ValueType newStart) const throw()
  7604. {
  7605. return Range (newStart, newStart + getLength());
  7606. }
  7607. /** Changes the end position of the range, leaving the start unchanged.
  7608. If the new end position is below the current start of the range, the start point
  7609. will be pushed back to equal the new end point.
  7610. */
  7611. void setEnd (const ValueType newEnd) throw()
  7612. {
  7613. end = newEnd;
  7614. if (newEnd < start)
  7615. start = newEnd;
  7616. }
  7617. /** Returns a range with the same start position as this one, but a different end.
  7618. If the new end position is below the current start of the range, the start point
  7619. will be pushed back to equal the new end point.
  7620. */
  7621. const Range withEnd (const ValueType newEnd) const throw()
  7622. {
  7623. return Range (jmin (start, newEnd), newEnd);
  7624. }
  7625. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7626. const Range movedToEndAt (const ValueType newEnd) const throw()
  7627. {
  7628. return Range (newEnd - getLength(), newEnd);
  7629. }
  7630. /** Changes the length of the range.
  7631. Lengths less than zero are treated as zero.
  7632. */
  7633. void setLength (const ValueType newLength) throw()
  7634. {
  7635. end = start + jmax (ValueType(), newLength);
  7636. }
  7637. /** Returns a range with the same start as this one, but a different length.
  7638. Lengths less than zero are treated as zero.
  7639. */
  7640. const Range withLength (const ValueType newLength) const throw()
  7641. {
  7642. return Range (start, start + newLength);
  7643. }
  7644. /** Adds an amount to the start and end of the range. */
  7645. inline const Range& operator+= (const ValueType amountToAdd) throw()
  7646. {
  7647. start += amountToAdd;
  7648. end += amountToAdd;
  7649. return *this;
  7650. }
  7651. /** Subtracts an amount from the start and end of the range. */
  7652. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  7653. {
  7654. start -= amountToSubtract;
  7655. end -= amountToSubtract;
  7656. return *this;
  7657. }
  7658. /** Returns a range that is equal to this one with an amount added to its
  7659. start and end.
  7660. */
  7661. const Range operator+ (const ValueType amountToAdd) const throw()
  7662. {
  7663. return Range (start + amountToAdd, end + amountToAdd);
  7664. }
  7665. /** Returns a range that is equal to this one with the specified amount
  7666. subtracted from its start and end. */
  7667. const Range operator- (const ValueType amountToSubtract) const throw()
  7668. {
  7669. return Range (start - amountToSubtract, end - amountToSubtract);
  7670. }
  7671. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  7672. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  7673. /** Returns true if the given position lies inside this range. */
  7674. bool contains (const ValueType position) const throw()
  7675. {
  7676. return start <= position && position < end;
  7677. }
  7678. /** Returns the nearest value to the one supplied, which lies within the range. */
  7679. ValueType clipValue (const ValueType value) const throw()
  7680. {
  7681. return jlimit (start, end, value);
  7682. }
  7683. /** Returns true if the given range lies entirely inside this range. */
  7684. bool contains (const Range& other) const throw()
  7685. {
  7686. return start <= other.start && end >= other.end;
  7687. }
  7688. /** Returns true if the given range intersects this one. */
  7689. bool intersects (const Range& other) const throw()
  7690. {
  7691. return other.start < end && start < other.end;
  7692. }
  7693. /** Returns the range that is the intersection of the two ranges, or an empty range
  7694. with an undefined start position if they don't overlap. */
  7695. const Range getIntersectionWith (const Range& other) const throw()
  7696. {
  7697. return Range (jmax (start, other.start),
  7698. jmin (end, other.end));
  7699. }
  7700. /** Returns the smallest range that contains both this one and the other one. */
  7701. const Range getUnionWith (const Range& other) const throw()
  7702. {
  7703. return Range (jmin (start, other.start),
  7704. jmax (end, other.end));
  7705. }
  7706. /** Returns a given range, after moving it forwards or backwards to fit it
  7707. within this range.
  7708. If the supplied range has a greater length than this one, the return value
  7709. will be this range.
  7710. Otherwise, if the supplied range is smaller than this one, the return value
  7711. will be the new range, shifted forwards or backwards so that it doesn't extend
  7712. beyond this one, but keeping its original length.
  7713. */
  7714. const Range constrainRange (const Range& rangeToConstrain) const throw()
  7715. {
  7716. const ValueType otherLen = rangeToConstrain.getLength();
  7717. return getLength() <= otherLen
  7718. ? *this
  7719. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  7720. }
  7721. juce_UseDebuggingNewOperator
  7722. private:
  7723. ValueType start, end;
  7724. };
  7725. #endif // __JUCE_RANGE_JUCEHEADER__
  7726. /*** End of inlined file: juce_Range.h ***/
  7727. #endif
  7728. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7729. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  7730. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7731. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7732. /**
  7733. Holds a list of objects derived from ReferenceCountedObject.
  7734. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7735. and takes care of incrementing and decrementing their ref counts when they
  7736. are added and removed from the array.
  7737. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7738. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7739. @see Array, OwnedArray, StringArray
  7740. */
  7741. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7742. class ReferenceCountedArray
  7743. {
  7744. public:
  7745. /** Creates an empty array.
  7746. @see ReferenceCountedObject, Array, OwnedArray
  7747. */
  7748. ReferenceCountedArray() throw()
  7749. : numUsed (0)
  7750. {
  7751. }
  7752. /** Creates a copy of another array */
  7753. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7754. {
  7755. const ScopedLockType lock (other.getLock());
  7756. numUsed = other.numUsed;
  7757. data.setAllocatedSize (numUsed);
  7758. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7759. for (int i = numUsed; --i >= 0;)
  7760. if (data.elements[i] != 0)
  7761. data.elements[i]->incReferenceCount();
  7762. }
  7763. /** Copies another array into this one.
  7764. Any existing objects in this array will first be released.
  7765. */
  7766. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7767. {
  7768. if (this != &other)
  7769. {
  7770. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  7771. swapWithArray (otherCopy);
  7772. }
  7773. return *this;
  7774. }
  7775. /** Destructor.
  7776. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7777. */
  7778. ~ReferenceCountedArray()
  7779. {
  7780. clear();
  7781. }
  7782. /** Removes all objects from the array.
  7783. Any objects in the array that are not referenced from elsewhere will be deleted.
  7784. */
  7785. void clear()
  7786. {
  7787. const ScopedLockType lock (getLock());
  7788. while (numUsed > 0)
  7789. if (data.elements [--numUsed] != 0)
  7790. data.elements [numUsed]->decReferenceCount();
  7791. jassert (numUsed == 0);
  7792. data.setAllocatedSize (0);
  7793. }
  7794. /** Returns the current number of objects in the array. */
  7795. inline int size() const throw()
  7796. {
  7797. return numUsed;
  7798. }
  7799. /** Returns a pointer to the object at this index in the array.
  7800. If the index is out-of-range, this will return a null pointer, (and
  7801. it could be null anyway, because it's ok for the array to hold null
  7802. pointers as well as objects).
  7803. @see getUnchecked
  7804. */
  7805. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7806. {
  7807. const ScopedLockType lock (getLock());
  7808. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  7809. : static_cast <ObjectClass*> (0);
  7810. }
  7811. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7812. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7813. it can be used when you're sure the index if always going to be legal.
  7814. */
  7815. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7816. {
  7817. const ScopedLockType lock (getLock());
  7818. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7819. return data.elements [index];
  7820. }
  7821. /** Returns a pointer to the first object in the array.
  7822. This will return a null pointer if the array's empty.
  7823. @see getLast
  7824. */
  7825. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7826. {
  7827. const ScopedLockType lock (getLock());
  7828. return numUsed > 0 ? data.elements [0]
  7829. : static_cast <ObjectClass*> (0);
  7830. }
  7831. /** Returns a pointer to the last object in the array.
  7832. This will return a null pointer if the array's empty.
  7833. @see getFirst
  7834. */
  7835. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7836. {
  7837. const ScopedLockType lock (getLock());
  7838. return numUsed > 0 ? data.elements [numUsed - 1]
  7839. : static_cast <ObjectClass*> (0);
  7840. }
  7841. /** Finds the index of the first occurrence of an object in the array.
  7842. @param objectToLookFor the object to look for
  7843. @returns the index at which the object was found, or -1 if it's not found
  7844. */
  7845. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7846. {
  7847. const ScopedLockType lock (getLock());
  7848. ObjectClass** e = data.elements.getData();
  7849. ObjectClass** const end = e + numUsed;
  7850. while (e != end)
  7851. {
  7852. if (objectToLookFor == *e)
  7853. return static_cast <int> (e - data.elements.getData());
  7854. ++e;
  7855. }
  7856. return -1;
  7857. }
  7858. /** Returns true if the array contains a specified object.
  7859. @param objectToLookFor the object to look for
  7860. @returns true if the object is in the array
  7861. */
  7862. bool contains (const ObjectClass* const objectToLookFor) const throw()
  7863. {
  7864. const ScopedLockType lock (getLock());
  7865. ObjectClass** e = data.elements.getData();
  7866. ObjectClass** const end = e + numUsed;
  7867. while (e != end)
  7868. {
  7869. if (objectToLookFor == *e)
  7870. return true;
  7871. ++e;
  7872. }
  7873. return false;
  7874. }
  7875. /** Appends a new object to the end of the array.
  7876. This will increase the new object's reference count.
  7877. @param newObject the new object to add to the array
  7878. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  7879. */
  7880. void add (ObjectClass* const newObject) throw()
  7881. {
  7882. const ScopedLockType lock (getLock());
  7883. data.ensureAllocatedSize (numUsed + 1);
  7884. data.elements [numUsed++] = newObject;
  7885. if (newObject != 0)
  7886. newObject->incReferenceCount();
  7887. }
  7888. /** Inserts a new object into the array at the given index.
  7889. If the index is less than 0 or greater than the size of the array, the
  7890. element will be added to the end of the array.
  7891. Otherwise, it will be inserted into the array, moving all the later elements
  7892. along to make room.
  7893. This will increase the new object's reference count.
  7894. @param indexToInsertAt the index at which the new element should be inserted
  7895. @param newObject the new object to add to the array
  7896. @see add, addSorted, addIfNotAlreadyThere, set
  7897. */
  7898. void insert (int indexToInsertAt,
  7899. ObjectClass* const newObject) throw()
  7900. {
  7901. if (indexToInsertAt >= 0)
  7902. {
  7903. const ScopedLockType lock (getLock());
  7904. if (indexToInsertAt > numUsed)
  7905. indexToInsertAt = numUsed;
  7906. data.ensureAllocatedSize (numUsed + 1);
  7907. ObjectClass** const e = data.elements + indexToInsertAt;
  7908. const int numToMove = numUsed - indexToInsertAt;
  7909. if (numToMove > 0)
  7910. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  7911. *e = newObject;
  7912. if (newObject != 0)
  7913. newObject->incReferenceCount();
  7914. ++numUsed;
  7915. }
  7916. else
  7917. {
  7918. add (newObject);
  7919. }
  7920. }
  7921. /** Appends a new object at the end of the array as long as the array doesn't
  7922. already contain it.
  7923. If the array already contains a matching object, nothing will be done.
  7924. @param newObject the new object to add to the array
  7925. */
  7926. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  7927. {
  7928. const ScopedLockType lock (getLock());
  7929. if (! contains (newObject))
  7930. add (newObject);
  7931. }
  7932. /** Replaces an object in the array with a different one.
  7933. If the index is less than zero, this method does nothing.
  7934. If the index is beyond the end of the array, the new object is added to the end of the array.
  7935. The object being added has its reference count increased, and if it's replacing
  7936. another object, then that one has its reference count decreased, and may be deleted.
  7937. @param indexToChange the index whose value you want to change
  7938. @param newObject the new value to set for this index.
  7939. @see add, insert, remove
  7940. */
  7941. void set (const int indexToChange,
  7942. ObjectClass* const newObject)
  7943. {
  7944. if (indexToChange >= 0)
  7945. {
  7946. const ScopedLockType lock (getLock());
  7947. if (newObject != 0)
  7948. newObject->incReferenceCount();
  7949. if (indexToChange < numUsed)
  7950. {
  7951. if (data.elements [indexToChange] != 0)
  7952. data.elements [indexToChange]->decReferenceCount();
  7953. data.elements [indexToChange] = newObject;
  7954. }
  7955. else
  7956. {
  7957. data.ensureAllocatedSize (numUsed + 1);
  7958. data.elements [numUsed++] = newObject;
  7959. }
  7960. }
  7961. }
  7962. /** Adds elements from another array to the end of this array.
  7963. @param arrayToAddFrom the array from which to copy the elements
  7964. @param startIndex the first element of the other array to start copying from
  7965. @param numElementsToAdd how many elements to add from the other array. If this
  7966. value is negative or greater than the number of available elements,
  7967. all available elements will be copied.
  7968. @see add
  7969. */
  7970. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  7971. int startIndex = 0,
  7972. int numElementsToAdd = -1) throw()
  7973. {
  7974. arrayToAddFrom.lockArray();
  7975. const ScopedLockType lock (getLock());
  7976. if (startIndex < 0)
  7977. {
  7978. jassertfalse;
  7979. startIndex = 0;
  7980. }
  7981. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  7982. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  7983. if (numElementsToAdd > 0)
  7984. {
  7985. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  7986. while (--numElementsToAdd >= 0)
  7987. add (arrayToAddFrom.getUnchecked (startIndex++));
  7988. }
  7989. arrayToAddFrom.unlockArray();
  7990. }
  7991. /** Inserts a new object into the array assuming that the array is sorted.
  7992. This will use a comparator to find the position at which the new object
  7993. should go. If the array isn't sorted, the behaviour of this
  7994. method will be unpredictable.
  7995. @param comparator the comparator object to use to compare the elements - see the
  7996. sort() method for details about this object's form
  7997. @param newObject the new object to insert to the array
  7998. @see add, sort
  7999. */
  8000. template <class ElementComparator>
  8001. void addSorted (ElementComparator& comparator,
  8002. ObjectClass* newObject) throw()
  8003. {
  8004. const ScopedLockType lock (getLock());
  8005. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  8006. }
  8007. /** Inserts or replaces an object in the array, assuming it is sorted.
  8008. This is similar to addSorted, but if a matching element already exists, then it will be
  8009. replaced by the new one, rather than the new one being added as well.
  8010. */
  8011. template <class ElementComparator>
  8012. void addOrReplaceSorted (ElementComparator& comparator,
  8013. ObjectClass* newObject) throw()
  8014. {
  8015. const ScopedLockType lock (getLock());
  8016. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  8017. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  8018. set (index - 1, newObject); // replace an existing object that matches
  8019. else
  8020. insert (index, newObject); // no match, so insert the new one
  8021. }
  8022. /** Removes an object from the array.
  8023. This will remove the object at a given index and move back all the
  8024. subsequent objects to close the gap.
  8025. If the index passed in is out-of-range, nothing will happen.
  8026. The object that is removed will have its reference count decreased,
  8027. and may be deleted if not referenced from elsewhere.
  8028. @param indexToRemove the index of the element to remove
  8029. @see removeObject, removeRange
  8030. */
  8031. void remove (const int indexToRemove)
  8032. {
  8033. const ScopedLockType lock (getLock());
  8034. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8035. {
  8036. ObjectClass** const e = data.elements + indexToRemove;
  8037. if (*e != 0)
  8038. (*e)->decReferenceCount();
  8039. --numUsed;
  8040. const int numberToShift = numUsed - indexToRemove;
  8041. if (numberToShift > 0)
  8042. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8043. if ((numUsed << 1) < data.numAllocated)
  8044. minimiseStorageOverheads();
  8045. }
  8046. }
  8047. /** Removes the first occurrence of a specified object from the array.
  8048. If the item isn't found, no action is taken. If it is found, it is
  8049. removed and has its reference count decreased.
  8050. @param objectToRemove the object to try to remove
  8051. @see remove, removeRange
  8052. */
  8053. void removeObject (ObjectClass* const objectToRemove)
  8054. {
  8055. const ScopedLockType lock (getLock());
  8056. remove (indexOf (objectToRemove));
  8057. }
  8058. /** Removes a range of objects from the array.
  8059. This will remove a set of objects, starting from the given index,
  8060. and move any subsequent elements down to close the gap.
  8061. If the range extends beyond the bounds of the array, it will
  8062. be safely clipped to the size of the array.
  8063. The objects that are removed will have their reference counts decreased,
  8064. and may be deleted if not referenced from elsewhere.
  8065. @param startIndex the index of the first object to remove
  8066. @param numberToRemove how many objects should be removed
  8067. @see remove, removeObject
  8068. */
  8069. void removeRange (const int startIndex,
  8070. const int numberToRemove)
  8071. {
  8072. const ScopedLockType lock (getLock());
  8073. const int start = jlimit (0, numUsed, startIndex);
  8074. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8075. if (end > start)
  8076. {
  8077. int i;
  8078. for (i = start; i < end; ++i)
  8079. {
  8080. if (data.elements[i] != 0)
  8081. {
  8082. data.elements[i]->decReferenceCount();
  8083. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8084. }
  8085. }
  8086. const int rangeSize = end - start;
  8087. ObjectClass** e = data.elements + start;
  8088. i = numUsed - end;
  8089. numUsed -= rangeSize;
  8090. while (--i >= 0)
  8091. {
  8092. *e = e [rangeSize];
  8093. ++e;
  8094. }
  8095. if ((numUsed << 1) < data.numAllocated)
  8096. minimiseStorageOverheads();
  8097. }
  8098. }
  8099. /** Removes the last n objects from the array.
  8100. The objects that are removed will have their reference counts decreased,
  8101. and may be deleted if not referenced from elsewhere.
  8102. @param howManyToRemove how many objects to remove from the end of the array
  8103. @see remove, removeObject, removeRange
  8104. */
  8105. void removeLast (int howManyToRemove = 1)
  8106. {
  8107. const ScopedLockType lock (getLock());
  8108. if (howManyToRemove > numUsed)
  8109. howManyToRemove = numUsed;
  8110. while (--howManyToRemove >= 0)
  8111. remove (numUsed - 1);
  8112. }
  8113. /** Swaps a pair of objects in the array.
  8114. If either of the indexes passed in is out-of-range, nothing will happen,
  8115. otherwise the two objects at these positions will be exchanged.
  8116. */
  8117. void swap (const int index1,
  8118. const int index2) throw()
  8119. {
  8120. const ScopedLockType lock (getLock());
  8121. if (((unsigned int) index1) < (unsigned int) numUsed
  8122. && ((unsigned int) index2) < (unsigned int) numUsed)
  8123. {
  8124. swapVariables (data.elements [index1],
  8125. data.elements [index2]);
  8126. }
  8127. }
  8128. /** Moves one of the objects to a different position.
  8129. This will move the object to a specified index, shuffling along
  8130. any intervening elements as required.
  8131. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8132. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8133. @param currentIndex the index of the object to be moved. If this isn't a
  8134. valid index, then nothing will be done
  8135. @param newIndex the index at which you'd like this object to end up. If this
  8136. is less than zero, it will be moved to the end of the array
  8137. */
  8138. void move (const int currentIndex,
  8139. int newIndex) throw()
  8140. {
  8141. if (currentIndex != newIndex)
  8142. {
  8143. const ScopedLockType lock (getLock());
  8144. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8145. {
  8146. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8147. newIndex = numUsed - 1;
  8148. ObjectClass* const value = data.elements [currentIndex];
  8149. if (newIndex > currentIndex)
  8150. {
  8151. memmove (data.elements + currentIndex,
  8152. data.elements + currentIndex + 1,
  8153. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8154. }
  8155. else
  8156. {
  8157. memmove (data.elements + newIndex + 1,
  8158. data.elements + newIndex,
  8159. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8160. }
  8161. data.elements [newIndex] = value;
  8162. }
  8163. }
  8164. }
  8165. /** This swaps the contents of this array with those of another array.
  8166. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8167. because it just swaps their internal pointers.
  8168. */
  8169. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  8170. {
  8171. const ScopedLockType lock1 (getLock());
  8172. const ScopedLockType lock2 (otherArray.getLock());
  8173. data.swapWith (otherArray.data);
  8174. swapVariables (numUsed, otherArray.numUsed);
  8175. }
  8176. /** Compares this array to another one.
  8177. @returns true only if the other array contains the same objects in the same order
  8178. */
  8179. bool operator== (const ReferenceCountedArray& other) const throw()
  8180. {
  8181. const ScopedLockType lock2 (other.getLock());
  8182. const ScopedLockType lock1 (getLock());
  8183. if (numUsed != other.numUsed)
  8184. return false;
  8185. for (int i = numUsed; --i >= 0;)
  8186. if (data.elements [i] != other.data.elements [i])
  8187. return false;
  8188. return true;
  8189. }
  8190. /** Compares this array to another one.
  8191. @see operator==
  8192. */
  8193. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8194. {
  8195. return ! operator== (other);
  8196. }
  8197. /** Sorts the elements in the array.
  8198. This will use a comparator object to sort the elements into order. The object
  8199. passed must have a method of the form:
  8200. @code
  8201. int compareElements (ElementType first, ElementType second);
  8202. @endcode
  8203. ..and this method must return:
  8204. - a value of < 0 if the first comes before the second
  8205. - a value of 0 if the two objects are equivalent
  8206. - a value of > 0 if the second comes before the first
  8207. To improve performance, the compareElements() method can be declared as static or const.
  8208. @param comparator the comparator to use for comparing elements.
  8209. @param retainOrderOfEquivalentItems if this is true, then items
  8210. which the comparator says are equivalent will be
  8211. kept in the order in which they currently appear
  8212. in the array. This is slower to perform, but may
  8213. be important in some cases. If it's false, a faster
  8214. algorithm is used, but equivalent elements may be
  8215. rearranged.
  8216. @see sortArray
  8217. */
  8218. template <class ElementComparator>
  8219. void sort (ElementComparator& comparator,
  8220. const bool retainOrderOfEquivalentItems = false) const throw()
  8221. {
  8222. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8223. // avoids getting warning messages about the parameter being unused
  8224. const ScopedLockType lock (getLock());
  8225. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8226. }
  8227. /** Reduces the amount of storage being used by the array.
  8228. Arrays typically allocate slightly more storage than they need, and after
  8229. removing elements, they may have quite a lot of unused space allocated.
  8230. This method will reduce the amount of allocated storage to a minimum.
  8231. */
  8232. void minimiseStorageOverheads() throw()
  8233. {
  8234. const ScopedLockType lock (getLock());
  8235. data.shrinkToNoMoreThan (numUsed);
  8236. }
  8237. /** Returns the CriticalSection that locks this array.
  8238. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8239. an object of ScopedLockType as an RAII lock for it.
  8240. */
  8241. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8242. /** Returns the type of scoped lock to use for locking this array */
  8243. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8244. juce_UseDebuggingNewOperator
  8245. private:
  8246. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8247. int numUsed;
  8248. };
  8249. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8250. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  8251. #endif
  8252. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8253. #endif
  8254. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8255. #endif
  8256. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8257. /*** Start of inlined file: juce_SortedSet.h ***/
  8258. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8259. #define __JUCE_SORTEDSET_JUCEHEADER__
  8260. #if JUCE_MSVC
  8261. #pragma warning (push)
  8262. #pragma warning (disable: 4512)
  8263. #endif
  8264. /**
  8265. Holds a set of unique primitive objects, such as ints or doubles.
  8266. A set can only hold one item with a given value, so if for example it's a
  8267. set of integers, attempting to add the same integer twice will do nothing
  8268. the second time.
  8269. Internally, the list of items is kept sorted (which means that whatever
  8270. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8271. to determine the order), and searching the set for known values is very fast
  8272. because it uses a binary-chop method.
  8273. Note that if you're using a class or struct as the element type, it must be
  8274. capable of being copied or moved with a straightforward memcpy, rather than
  8275. needing construction and destruction code.
  8276. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8277. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8278. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8279. */
  8280. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8281. class SortedSet
  8282. {
  8283. public:
  8284. /** Creates an empty set. */
  8285. SortedSet() throw()
  8286. : numUsed (0)
  8287. {
  8288. }
  8289. /** Creates a copy of another set.
  8290. @param other the set to copy
  8291. */
  8292. SortedSet (const SortedSet& other) throw()
  8293. {
  8294. const ScopedLockType lock (other.getLock());
  8295. numUsed = other.numUsed;
  8296. data.setAllocatedSize (other.numUsed);
  8297. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8298. }
  8299. /** Destructor. */
  8300. ~SortedSet() throw()
  8301. {
  8302. }
  8303. /** Copies another set over this one.
  8304. @param other the set to copy
  8305. */
  8306. SortedSet& operator= (const SortedSet& other) throw()
  8307. {
  8308. if (this != &other)
  8309. {
  8310. const ScopedLockType lock1 (other.getLock());
  8311. const ScopedLockType lock2 (getLock());
  8312. data.ensureAllocatedSize (other.size());
  8313. numUsed = other.numUsed;
  8314. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8315. minimiseStorageOverheads();
  8316. }
  8317. return *this;
  8318. }
  8319. /** Compares this set to another one.
  8320. Two sets are considered equal if they both contain the same set of
  8321. elements.
  8322. @param other the other set to compare with
  8323. */
  8324. bool operator== (const SortedSet<ElementType>& other) const throw()
  8325. {
  8326. const ScopedLockType lock (getLock());
  8327. if (numUsed != other.numUsed)
  8328. return false;
  8329. for (int i = numUsed; --i >= 0;)
  8330. if (data.elements[i] != other.data.elements[i])
  8331. return false;
  8332. return true;
  8333. }
  8334. /** Compares this set to another one.
  8335. Two sets are considered equal if they both contain the same set of
  8336. elements.
  8337. @param other the other set to compare with
  8338. */
  8339. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8340. {
  8341. return ! operator== (other);
  8342. }
  8343. /** Removes all elements from the set.
  8344. This will remove all the elements, and free any storage that the set is
  8345. using. To clear it without freeing the storage, use the clearQuick()
  8346. method instead.
  8347. @see clearQuick
  8348. */
  8349. void clear() throw()
  8350. {
  8351. const ScopedLockType lock (getLock());
  8352. data.setAllocatedSize (0);
  8353. numUsed = 0;
  8354. }
  8355. /** Removes all elements from the set without freeing the array's allocated storage.
  8356. @see clear
  8357. */
  8358. void clearQuick() throw()
  8359. {
  8360. const ScopedLockType lock (getLock());
  8361. numUsed = 0;
  8362. }
  8363. /** Returns the current number of elements in the set.
  8364. */
  8365. inline int size() const throw()
  8366. {
  8367. return numUsed;
  8368. }
  8369. /** Returns one of the elements in the set.
  8370. If the index passed in is beyond the range of valid elements, this
  8371. will return zero.
  8372. If you're certain that the index will always be a valid element, you
  8373. can call getUnchecked() instead, which is faster.
  8374. @param index the index of the element being requested (0 is the first element in the set)
  8375. @see getUnchecked, getFirst, getLast
  8376. */
  8377. inline ElementType operator[] (const int index) const throw()
  8378. {
  8379. const ScopedLockType lock (getLock());
  8380. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  8381. : ElementType();
  8382. }
  8383. /** Returns one of the elements in the set, without checking the index passed in.
  8384. Unlike the operator[] method, this will try to return an element without
  8385. checking that the index is within the bounds of the set, so should only
  8386. be used when you're confident that it will always be a valid index.
  8387. @param index the index of the element being requested (0 is the first element in the set)
  8388. @see operator[], getFirst, getLast
  8389. */
  8390. inline ElementType getUnchecked (const int index) const throw()
  8391. {
  8392. const ScopedLockType lock (getLock());
  8393. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8394. return data.elements [index];
  8395. }
  8396. /** Returns the first element in the set, or 0 if the set is empty.
  8397. @see operator[], getUnchecked, getLast
  8398. */
  8399. inline ElementType getFirst() const throw()
  8400. {
  8401. const ScopedLockType lock (getLock());
  8402. return numUsed > 0 ? data.elements [0] : ElementType();
  8403. }
  8404. /** Returns the last element in the set, or 0 if the set is empty.
  8405. @see operator[], getUnchecked, getFirst
  8406. */
  8407. inline ElementType getLast() const throw()
  8408. {
  8409. const ScopedLockType lock (getLock());
  8410. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  8411. }
  8412. /** Finds the index of the first element which matches the value passed in.
  8413. This will search the set for the given object, and return the index
  8414. of its first occurrence. If the object isn't found, the method will return -1.
  8415. @param elementToLookFor the value or object to look for
  8416. @returns the index of the object, or -1 if it's not found
  8417. */
  8418. int indexOf (const ElementType elementToLookFor) const throw()
  8419. {
  8420. const ScopedLockType lock (getLock());
  8421. int start = 0;
  8422. int end = numUsed;
  8423. for (;;)
  8424. {
  8425. if (start >= end)
  8426. {
  8427. return -1;
  8428. }
  8429. else if (elementToLookFor == data.elements [start])
  8430. {
  8431. return start;
  8432. }
  8433. else
  8434. {
  8435. const int halfway = (start + end) >> 1;
  8436. if (halfway == start)
  8437. return -1;
  8438. else if (elementToLookFor >= data.elements [halfway])
  8439. start = halfway;
  8440. else
  8441. end = halfway;
  8442. }
  8443. }
  8444. }
  8445. /** Returns true if the set contains at least one occurrence of an object.
  8446. @param elementToLookFor the value or object to look for
  8447. @returns true if the item is found
  8448. */
  8449. bool contains (const ElementType elementToLookFor) const throw()
  8450. {
  8451. const ScopedLockType lock (getLock());
  8452. int start = 0;
  8453. int end = numUsed;
  8454. for (;;)
  8455. {
  8456. if (start >= end)
  8457. {
  8458. return false;
  8459. }
  8460. else if (elementToLookFor == data.elements [start])
  8461. {
  8462. return true;
  8463. }
  8464. else
  8465. {
  8466. const int halfway = (start + end) >> 1;
  8467. if (halfway == start)
  8468. return false;
  8469. else if (elementToLookFor >= data.elements [halfway])
  8470. start = halfway;
  8471. else
  8472. end = halfway;
  8473. }
  8474. }
  8475. }
  8476. /** Adds a new element to the set, (as long as it's not already in there).
  8477. @param newElement the new object to add to the set
  8478. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8479. */
  8480. void add (const ElementType newElement) throw()
  8481. {
  8482. const ScopedLockType lock (getLock());
  8483. int start = 0;
  8484. int end = numUsed;
  8485. for (;;)
  8486. {
  8487. if (start >= end)
  8488. {
  8489. jassert (start <= end);
  8490. insertInternal (start, newElement);
  8491. break;
  8492. }
  8493. else if (newElement == data.elements [start])
  8494. {
  8495. break;
  8496. }
  8497. else
  8498. {
  8499. const int halfway = (start + end) >> 1;
  8500. if (halfway == start)
  8501. {
  8502. if (newElement >= data.elements [halfway])
  8503. insertInternal (start + 1, newElement);
  8504. else
  8505. insertInternal (start, newElement);
  8506. break;
  8507. }
  8508. else if (newElement >= data.elements [halfway])
  8509. start = halfway;
  8510. else
  8511. end = halfway;
  8512. }
  8513. }
  8514. }
  8515. /** Adds elements from an array to this set.
  8516. @param elementsToAdd the array of elements to add
  8517. @param numElementsToAdd how many elements are in this other array
  8518. @see add
  8519. */
  8520. void addArray (const ElementType* elementsToAdd,
  8521. int numElementsToAdd) throw()
  8522. {
  8523. const ScopedLockType lock (getLock());
  8524. while (--numElementsToAdd >= 0)
  8525. add (*elementsToAdd++);
  8526. }
  8527. /** Adds elements from another set to this one.
  8528. @param setToAddFrom the set from which to copy the elements
  8529. @param startIndex the first element of the other set to start copying from
  8530. @param numElementsToAdd how many elements to add from the other set. If this
  8531. value is negative or greater than the number of available elements,
  8532. all available elements will be copied.
  8533. @see add
  8534. */
  8535. template <class OtherSetType>
  8536. void addSet (const OtherSetType& setToAddFrom,
  8537. int startIndex = 0,
  8538. int numElementsToAdd = -1) throw()
  8539. {
  8540. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  8541. const ScopedLockType lock2 (getLock());
  8542. jassert (this != &setToAddFrom);
  8543. if (this != &setToAddFrom)
  8544. {
  8545. if (startIndex < 0)
  8546. {
  8547. jassertfalse;
  8548. startIndex = 0;
  8549. }
  8550. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8551. numElementsToAdd = setToAddFrom.size() - startIndex;
  8552. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8553. }
  8554. }
  8555. /** Removes an element from the set.
  8556. This will remove the element at a given index.
  8557. If the index passed in is out-of-range, nothing will happen.
  8558. @param indexToRemove the index of the element to remove
  8559. @returns the element that has been removed
  8560. @see removeValue, removeRange
  8561. */
  8562. ElementType remove (const int indexToRemove) throw()
  8563. {
  8564. const ScopedLockType lock (getLock());
  8565. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8566. {
  8567. --numUsed;
  8568. ElementType* const e = data.elements + indexToRemove;
  8569. ElementType const removed = *e;
  8570. const int numberToShift = numUsed - indexToRemove;
  8571. if (numberToShift > 0)
  8572. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8573. if ((numUsed << 1) < data.numAllocated)
  8574. minimiseStorageOverheads();
  8575. return removed;
  8576. }
  8577. return 0;
  8578. }
  8579. /** Removes an item from the set.
  8580. This will remove the given element from the set, if it's there.
  8581. @param valueToRemove the object to try to remove
  8582. @see remove, removeRange
  8583. */
  8584. void removeValue (const ElementType valueToRemove) throw()
  8585. {
  8586. const ScopedLockType lock (getLock());
  8587. remove (indexOf (valueToRemove));
  8588. }
  8589. /** Removes any elements which are also in another set.
  8590. @param otherSet the other set in which to look for elements to remove
  8591. @see removeValuesNotIn, remove, removeValue, removeRange
  8592. */
  8593. template <class OtherSetType>
  8594. void removeValuesIn (const OtherSetType& otherSet) throw()
  8595. {
  8596. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8597. const ScopedLockType lock2 (getLock());
  8598. if (this == &otherSet)
  8599. {
  8600. clear();
  8601. }
  8602. else
  8603. {
  8604. if (otherSet.size() > 0)
  8605. {
  8606. for (int i = numUsed; --i >= 0;)
  8607. if (otherSet.contains (data.elements [i]))
  8608. remove (i);
  8609. }
  8610. }
  8611. }
  8612. /** Removes any elements which are not found in another set.
  8613. Only elements which occur in this other set will be retained.
  8614. @param otherSet the set in which to look for elements NOT to remove
  8615. @see removeValuesIn, remove, removeValue, removeRange
  8616. */
  8617. template <class OtherSetType>
  8618. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8619. {
  8620. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8621. const ScopedLockType lock2 (getLock());
  8622. if (this != &otherSet)
  8623. {
  8624. if (otherSet.size() <= 0)
  8625. {
  8626. clear();
  8627. }
  8628. else
  8629. {
  8630. for (int i = numUsed; --i >= 0;)
  8631. if (! otherSet.contains (data.elements [i]))
  8632. remove (i);
  8633. }
  8634. }
  8635. }
  8636. /** Reduces the amount of storage being used by the set.
  8637. Sets typically allocate slightly more storage than they need, and after
  8638. removing elements, they may have quite a lot of unused space allocated.
  8639. This method will reduce the amount of allocated storage to a minimum.
  8640. */
  8641. void minimiseStorageOverheads() throw()
  8642. {
  8643. const ScopedLockType lock (getLock());
  8644. data.shrinkToNoMoreThan (numUsed);
  8645. }
  8646. /** Returns the CriticalSection that locks this array.
  8647. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8648. an object of ScopedLockType as an RAII lock for it.
  8649. */
  8650. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8651. /** Returns the type of scoped lock to use for locking this array */
  8652. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8653. juce_UseDebuggingNewOperator
  8654. private:
  8655. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  8656. int numUsed;
  8657. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8658. {
  8659. data.ensureAllocatedSize (numUsed + 1);
  8660. ElementType* const insertPos = data.elements + indexToInsertAt;
  8661. const int numberToMove = numUsed - indexToInsertAt;
  8662. if (numberToMove > 0)
  8663. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8664. *insertPos = newElement;
  8665. ++numUsed;
  8666. }
  8667. };
  8668. #if JUCE_MSVC
  8669. #pragma warning (pop)
  8670. #endif
  8671. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8672. /*** End of inlined file: juce_SortedSet.h ***/
  8673. #endif
  8674. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8675. /*** Start of inlined file: juce_SparseSet.h ***/
  8676. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8677. #define __JUCE_SPARSESET_JUCEHEADER__
  8678. /**
  8679. Holds a set of primitive values, storing them as a set of ranges.
  8680. This container acts like an array, but can efficiently hold large continguous
  8681. ranges of values. It's quite a specialised class, mostly useful for things
  8682. like keeping the set of selected rows in a listbox.
  8683. The type used as a template paramter must be an integer type, such as int, short,
  8684. int64, etc.
  8685. */
  8686. template <class Type>
  8687. class SparseSet
  8688. {
  8689. public:
  8690. /** Creates a new empty set. */
  8691. SparseSet()
  8692. {
  8693. }
  8694. /** Creates a copy of another SparseSet. */
  8695. SparseSet (const SparseSet<Type>& other)
  8696. : values (other.values)
  8697. {
  8698. }
  8699. /** Destructor. */
  8700. ~SparseSet()
  8701. {
  8702. }
  8703. /** Clears the set. */
  8704. void clear()
  8705. {
  8706. values.clear();
  8707. }
  8708. /** Checks whether the set is empty.
  8709. This is much quicker than using (size() == 0).
  8710. */
  8711. bool isEmpty() const throw()
  8712. {
  8713. return values.size() == 0;
  8714. }
  8715. /** Returns the number of values in the set.
  8716. Because of the way the data is stored, this method can take longer if there
  8717. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8718. are any items.
  8719. */
  8720. Type size() const
  8721. {
  8722. Type total (0);
  8723. for (int i = 0; i < values.size(); i += 2)
  8724. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  8725. return total;
  8726. }
  8727. /** Returns one of the values in the set.
  8728. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8729. @returns the value at this index, or 0 if it's out-of-range
  8730. */
  8731. Type operator[] (Type index) const
  8732. {
  8733. for (int i = 0; i < values.size(); i += 2)
  8734. {
  8735. const Type start (values.getUnchecked (i));
  8736. const Type len (values.getUnchecked (i + 1) - start);
  8737. if (index < len)
  8738. return start + index;
  8739. index -= len;
  8740. }
  8741. return Type (0);
  8742. }
  8743. /** Checks whether a particular value is in the set. */
  8744. bool contains (const Type valueToLookFor) const
  8745. {
  8746. for (int i = 0; i < values.size(); ++i)
  8747. if (valueToLookFor < values.getUnchecked(i))
  8748. return (i & 1) != 0;
  8749. return false;
  8750. }
  8751. /** Returns the number of contiguous blocks of values.
  8752. @see getRange
  8753. */
  8754. int getNumRanges() const throw()
  8755. {
  8756. return values.size() >> 1;
  8757. }
  8758. /** Returns one of the contiguous ranges of values stored.
  8759. @param rangeIndex the index of the range to look up, between 0
  8760. and (getNumRanges() - 1)
  8761. @see getTotalRange
  8762. */
  8763. const Range<Type> getRange (const int rangeIndex) const
  8764. {
  8765. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8766. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  8767. values.getUnchecked ((rangeIndex << 1) + 1));
  8768. else
  8769. return Range<Type>();
  8770. }
  8771. /** Returns the range between the lowest and highest values in the set.
  8772. @see getRange
  8773. */
  8774. const Range<Type> getTotalRange() const
  8775. {
  8776. if (values.size() > 0)
  8777. {
  8778. jassert ((values.size() & 1) == 0);
  8779. return Range<Type> (values.getUnchecked (0),
  8780. values.getUnchecked (values.size() - 1));
  8781. }
  8782. return Range<Type>();
  8783. }
  8784. /** Adds a range of contiguous values to the set.
  8785. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  8786. */
  8787. void addRange (const Range<Type>& range)
  8788. {
  8789. jassert (range.getLength() >= 0);
  8790. if (range.getLength() > 0)
  8791. {
  8792. removeRange (range);
  8793. values.addUsingDefaultSort (range.getStart());
  8794. values.addUsingDefaultSort (range.getEnd());
  8795. simplify();
  8796. }
  8797. }
  8798. /** Removes a range of values from the set.
  8799. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  8800. */
  8801. void removeRange (const Range<Type>& rangeToRemove)
  8802. {
  8803. jassert (rangeToRemove.getLength() >= 0);
  8804. if (rangeToRemove.getLength() > 0
  8805. && values.size() > 0
  8806. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  8807. && values.getUnchecked(0) < rangeToRemove.getEnd())
  8808. {
  8809. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  8810. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  8811. const bool onAtEnd = contains (lastValue);
  8812. for (int i = values.size(); --i >= 0;)
  8813. {
  8814. if (values.getUnchecked(i) <= lastValue)
  8815. {
  8816. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  8817. {
  8818. values.remove (i);
  8819. if (--i < 0)
  8820. break;
  8821. }
  8822. break;
  8823. }
  8824. }
  8825. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  8826. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  8827. simplify();
  8828. }
  8829. }
  8830. /** Does an XOR of the values in a given range. */
  8831. void invertRange (const Range<Type>& range)
  8832. {
  8833. SparseSet newItems;
  8834. newItems.addRange (range);
  8835. int i;
  8836. for (i = getNumRanges(); --i >= 0;)
  8837. newItems.removeRange (getRange (i));
  8838. removeRange (range);
  8839. for (i = newItems.getNumRanges(); --i >= 0;)
  8840. addRange (newItems.getRange(i));
  8841. }
  8842. /** Checks whether any part of a given range overlaps any part of this set. */
  8843. bool overlapsRange (const Range<Type>& range)
  8844. {
  8845. if (range.getLength() > 0)
  8846. {
  8847. for (int i = getNumRanges(); --i >= 0;)
  8848. {
  8849. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8850. return false;
  8851. if (values.getUnchecked (i << 1) < range.getEnd())
  8852. return true;
  8853. }
  8854. }
  8855. return false;
  8856. }
  8857. /** Checks whether the whole of a given range is contained within this one. */
  8858. bool containsRange (const Range<Type>& range)
  8859. {
  8860. if (range.getLength() > 0)
  8861. {
  8862. for (int i = getNumRanges(); --i >= 0;)
  8863. {
  8864. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8865. return false;
  8866. if (values.getUnchecked (i << 1) <= range.getStart()
  8867. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  8868. return true;
  8869. }
  8870. }
  8871. return false;
  8872. }
  8873. bool operator== (const SparseSet<Type>& other) throw()
  8874. {
  8875. return values == other.values;
  8876. }
  8877. bool operator!= (const SparseSet<Type>& other) throw()
  8878. {
  8879. return values != other.values;
  8880. }
  8881. juce_UseDebuggingNewOperator
  8882. private:
  8883. // alternating start/end values of ranges of values that are present.
  8884. Array<Type, DummyCriticalSection> values;
  8885. void simplify()
  8886. {
  8887. jassert ((values.size() & 1) == 0);
  8888. for (int i = values.size(); --i > 0;)
  8889. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  8890. values.removeRange (--i, 2);
  8891. }
  8892. };
  8893. #endif // __JUCE_SPARSESET_JUCEHEADER__
  8894. /*** End of inlined file: juce_SparseSet.h ***/
  8895. #endif
  8896. #ifndef __JUCE_VALUE_JUCEHEADER__
  8897. /*** Start of inlined file: juce_Value.h ***/
  8898. #ifndef __JUCE_VALUE_JUCEHEADER__
  8899. #define __JUCE_VALUE_JUCEHEADER__
  8900. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  8901. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  8902. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  8903. /*** Start of inlined file: juce_MessageListener.h ***/
  8904. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  8905. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  8906. /*** Start of inlined file: juce_Message.h ***/
  8907. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  8908. #define __JUCE_MESSAGE_JUCEHEADER__
  8909. class MessageListener;
  8910. class MessageManager;
  8911. /** The base class for objects that can be delivered to a MessageListener.
  8912. The simplest Message object contains a few integer and pointer parameters
  8913. that the user can set, and this is enough for a lot of purposes. For passing more
  8914. complex data, subclasses of Message can also be used.
  8915. @see MessageListener, MessageManager, ActionListener, ChangeListener
  8916. */
  8917. class JUCE_API Message
  8918. {
  8919. public:
  8920. /** Creates an uninitialised message.
  8921. The class's variables will also be left uninitialised.
  8922. */
  8923. Message() throw();
  8924. /** Creates a message object, filling in the member variables.
  8925. The corresponding public member variables will be set from the parameters
  8926. passed in.
  8927. */
  8928. Message (int intParameter1,
  8929. int intParameter2,
  8930. int intParameter3,
  8931. void* pointerParameter) throw();
  8932. /** Destructor. */
  8933. virtual ~Message() throw();
  8934. // These values can be used for carrying simple data that the application needs to
  8935. // pass around. For more complex messages, just create a subclass.
  8936. int intParameter1; /**< user-defined integer value. */
  8937. int intParameter2; /**< user-defined integer value. */
  8938. int intParameter3; /**< user-defined integer value. */
  8939. void* pointerParameter; /**< user-defined pointer value. */
  8940. juce_UseDebuggingNewOperator
  8941. private:
  8942. friend class MessageListener;
  8943. friend class MessageManager;
  8944. MessageListener* messageRecipient;
  8945. Message (const Message&);
  8946. Message& operator= (const Message&);
  8947. };
  8948. #endif // __JUCE_MESSAGE_JUCEHEADER__
  8949. /*** End of inlined file: juce_Message.h ***/
  8950. /**
  8951. MessageListener subclasses can post and receive Message objects.
  8952. @see Message, MessageManager, ActionListener, ChangeListener
  8953. */
  8954. class JUCE_API MessageListener
  8955. {
  8956. protected:
  8957. /** Creates a MessageListener. */
  8958. MessageListener() throw();
  8959. public:
  8960. /** Destructor.
  8961. When a MessageListener is deleted, it removes itself from a global list
  8962. of registered listeners, so that the isValidMessageListener() method
  8963. will no longer return true.
  8964. */
  8965. virtual ~MessageListener();
  8966. /** This is the callback method that receives incoming messages.
  8967. This is called by the MessageManager from its dispatch loop.
  8968. @see postMessage
  8969. */
  8970. virtual void handleMessage (const Message& message) = 0;
  8971. /** Sends a message to the message queue, for asynchronous delivery to this listener
  8972. later on.
  8973. This method can be called safely by any thread.
  8974. @param message the message object to send - this will be deleted
  8975. automatically by the message queue, so don't keep any
  8976. references to it after calling this method.
  8977. @see handleMessage
  8978. */
  8979. void postMessage (Message* message) const throw();
  8980. /** Checks whether this MessageListener has been deleted.
  8981. Although not foolproof, this method is safe to call on dangling or null
  8982. pointers. A list of active MessageListeners is kept internally, so this
  8983. checks whether the object is on this list or not.
  8984. Note that it's possible to get a false-positive here, if an object is
  8985. deleted and another is subsequently created that happens to be at the
  8986. exact same memory location, but I can't think of a good way of avoiding
  8987. this.
  8988. */
  8989. bool isValidMessageListener() const throw();
  8990. };
  8991. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  8992. /*** End of inlined file: juce_MessageListener.h ***/
  8993. /**
  8994. Has a callback method that is triggered asynchronously.
  8995. This object allows an asynchronous callback function to be triggered, for
  8996. tasks such as coalescing multiple updates into a single callback later on.
  8997. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  8998. message thread calling handleAsyncUpdate() as soon as it can.
  8999. */
  9000. class JUCE_API AsyncUpdater
  9001. {
  9002. public:
  9003. /** Creates an AsyncUpdater object. */
  9004. AsyncUpdater() throw();
  9005. /** Destructor.
  9006. If there are any pending callbacks when the object is deleted, these are lost.
  9007. */
  9008. virtual ~AsyncUpdater();
  9009. /** Causes the callback to be triggered at a later time.
  9010. This method returns immediately, having made sure that a callback
  9011. to the handleAsyncUpdate() method will occur as soon as possible.
  9012. If an update callback is already pending but hasn't happened yet, calls
  9013. to this method will be ignored.
  9014. It's thread-safe to call this method from any number of threads without
  9015. needing to worry about locking.
  9016. */
  9017. void triggerAsyncUpdate() throw();
  9018. /** This will stop any pending updates from happening.
  9019. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  9020. callback happens, this will cancel the handleAsyncUpdate() callback.
  9021. */
  9022. void cancelPendingUpdate() throw();
  9023. /** If an update has been triggered and is pending, this will invoke it
  9024. synchronously.
  9025. Use this as a kind of "flush" operation - if an update is pending, the
  9026. handleAsyncUpdate() method will be called immediately; if no update is
  9027. pending, then nothing will be done.
  9028. */
  9029. void handleUpdateNowIfNeeded();
  9030. /** Called back to do whatever your class needs to do.
  9031. This method is called by the message thread at the next convenient time
  9032. after the triggerAsyncUpdate() method has been called.
  9033. */
  9034. virtual void handleAsyncUpdate() = 0;
  9035. private:
  9036. class AsyncUpdaterInternal : public MessageListener
  9037. {
  9038. public:
  9039. AsyncUpdaterInternal() throw() {}
  9040. ~AsyncUpdaterInternal() {}
  9041. void handleMessage (const Message&);
  9042. AsyncUpdater* owner;
  9043. private:
  9044. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  9045. AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  9046. };
  9047. AsyncUpdaterInternal internalAsyncHandler;
  9048. bool asyncMessagePending;
  9049. };
  9050. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  9051. /*** End of inlined file: juce_AsyncUpdater.h ***/
  9052. /*** Start of inlined file: juce_ListenerList.h ***/
  9053. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  9054. #define __JUCE_LISTENERLIST_JUCEHEADER__
  9055. /**
  9056. Holds a set of objects and can invoke a member function callback on each object
  9057. in the set with a single call.
  9058. Use a ListenerList to manage a set of objects which need a callback, and you
  9059. can invoke a member function by simply calling call() or callChecked().
  9060. E.g.
  9061. @code
  9062. class MyListenerType
  9063. {
  9064. public:
  9065. void myCallbackMethod (int foo, bool bar);
  9066. };
  9067. ListenerList <MyListenerType> listeners;
  9068. listeners.add (someCallbackObjects...);
  9069. // This will invoke myCallbackMethod (1234, true) on each of the objects
  9070. // in the list...
  9071. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  9072. @endcode
  9073. If you add or remove listeners from the list during one of the callbacks - i.e. while
  9074. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  9075. will be mistakenly called after they've been removed, but it may mean that some of the
  9076. listeners could be called more than once, or not at all, depending on the list's order.
  9077. Sometimes, there's a chance that invoking one of the callbacks might result in the
  9078. list itself being deleted while it's still iterating - to survive this situation, you can
  9079. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  9080. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  9081. the list will check this after each callback to determine whether it should abort the
  9082. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  9083. which can be used to check when a Component has been deleted. See also
  9084. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  9085. */
  9086. template <class ListenerClass,
  9087. class ArrayType = Array <ListenerClass*> >
  9088. class ListenerList
  9089. {
  9090. // Horrible macros required to support VC6/7..
  9091. #if defined (_MSC_VER) && _MSC_VER <= 1400
  9092. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  9093. #define LL_PARAM(a) Q##a& param##a
  9094. #else
  9095. #define LL_TEMPLATE(a) typename P##a
  9096. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  9097. #endif
  9098. public:
  9099. /** Creates an empty list. */
  9100. ListenerList()
  9101. {
  9102. }
  9103. /** Destructor. */
  9104. ~ListenerList()
  9105. {
  9106. }
  9107. /** Adds a listener to the list.
  9108. A listener can only be added once, so if the listener is already in the list,
  9109. this method has no effect.
  9110. @see remove
  9111. */
  9112. void add (ListenerClass* const listenerToAdd)
  9113. {
  9114. // Listeners can't be null pointers!
  9115. jassert (listenerToAdd != 0);
  9116. if (listenerToAdd != 0)
  9117. listeners.addIfNotAlreadyThere (listenerToAdd);
  9118. }
  9119. /** Removes a listener from the list.
  9120. If the listener wasn't in the list, this has no effect.
  9121. */
  9122. void remove (ListenerClass* const listenerToRemove)
  9123. {
  9124. // Listeners can't be null pointers!
  9125. jassert (listenerToRemove != 0);
  9126. listeners.removeValue (listenerToRemove);
  9127. }
  9128. /** Returns the number of registered listeners. */
  9129. int size() const throw()
  9130. {
  9131. return listeners.size();
  9132. }
  9133. /** Returns true if any listeners are registered. */
  9134. bool isEmpty() const throw()
  9135. {
  9136. return listeners.size() == 0;
  9137. }
  9138. /** Returns true if the specified listener has been added to the list. */
  9139. bool contains (ListenerClass* const listener) const throw()
  9140. {
  9141. return listeners.contains (listener);
  9142. }
  9143. /** Calls a member function on each listener in the list, with no parameters. */
  9144. void call (void (ListenerClass::*callbackFunction) ())
  9145. {
  9146. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  9147. }
  9148. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  9149. See the class description for info about writing a bail-out checker. */
  9150. template <class BailOutCheckerType>
  9151. void callChecked (const BailOutCheckerType& bailOutChecker,
  9152. void (ListenerClass::*callbackFunction) ())
  9153. {
  9154. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9155. (iter.getListener()->*callbackFunction) ();
  9156. }
  9157. /** Calls a member function on each listener in the list, with 1 parameter. */
  9158. template <LL_TEMPLATE(1)>
  9159. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  9160. {
  9161. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9162. (iter.getListener()->*callbackFunction) (param1);
  9163. }
  9164. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  9165. See the class description for info about writing a bail-out checker. */
  9166. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  9167. void callChecked (const BailOutCheckerType& bailOutChecker,
  9168. void (ListenerClass::*callbackFunction) (P1),
  9169. LL_PARAM(1))
  9170. {
  9171. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9172. (iter.getListener()->*callbackFunction) (param1);
  9173. }
  9174. /** Calls a member function on each listener in the list, with 2 parameters. */
  9175. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9176. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  9177. LL_PARAM(1), LL_PARAM(2))
  9178. {
  9179. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9180. (iter.getListener()->*callbackFunction) (param1, param2);
  9181. }
  9182. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  9183. See the class description for info about writing a bail-out checker. */
  9184. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9185. void callChecked (const BailOutCheckerType& bailOutChecker,
  9186. void (ListenerClass::*callbackFunction) (P1, P2),
  9187. LL_PARAM(1), LL_PARAM(2))
  9188. {
  9189. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9190. (iter.getListener()->*callbackFunction) (param1, param2);
  9191. }
  9192. /** Calls a member function on each listener in the list, with 3 parameters. */
  9193. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9194. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9195. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9196. {
  9197. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9198. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9199. }
  9200. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  9201. See the class description for info about writing a bail-out checker. */
  9202. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9203. void callChecked (const BailOutCheckerType& bailOutChecker,
  9204. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9205. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9206. {
  9207. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9208. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9209. }
  9210. /** Calls a member function on each listener in the list, with 4 parameters. */
  9211. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9212. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9213. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9214. {
  9215. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9216. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9217. }
  9218. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  9219. See the class description for info about writing a bail-out checker. */
  9220. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9221. void callChecked (const BailOutCheckerType& bailOutChecker,
  9222. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9223. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9224. {
  9225. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9226. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9227. }
  9228. /** Calls a member function on each listener in the list, with 5 parameters. */
  9229. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9230. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9231. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9232. {
  9233. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9234. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9235. }
  9236. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  9237. See the class description for info about writing a bail-out checker. */
  9238. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9239. void callChecked (const BailOutCheckerType& bailOutChecker,
  9240. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9241. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9242. {
  9243. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9244. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9245. }
  9246. /** A dummy bail-out checker that always returns false.
  9247. See the ListenerList notes for more info about bail-out checkers.
  9248. */
  9249. class DummyBailOutChecker
  9250. {
  9251. public:
  9252. inline bool shouldBailOut() const throw() { return false; }
  9253. };
  9254. /** Iterates the listeners in a ListenerList. */
  9255. template <class BailOutCheckerType, class ListType>
  9256. class Iterator
  9257. {
  9258. public:
  9259. Iterator (const ListType& list_, const BailOutCheckerType& bailOutChecker_)
  9260. : list (list_), bailOutChecker (bailOutChecker_), index (list_.size())
  9261. {}
  9262. ~Iterator() {}
  9263. bool next()
  9264. {
  9265. if (index <= 0 || bailOutChecker.shouldBailOut())
  9266. return false;
  9267. const int listSize = list.size();
  9268. if (--index < listSize)
  9269. return true;
  9270. index = listSize - 1;
  9271. return index >= 0;
  9272. }
  9273. typename ListType::ListenerType* getListener() const throw()
  9274. {
  9275. return list.getListeners().getUnchecked (index);
  9276. }
  9277. private:
  9278. const ListType& list;
  9279. const BailOutCheckerType& bailOutChecker;
  9280. int index;
  9281. Iterator (const Iterator&);
  9282. Iterator& operator= (const Iterator&);
  9283. };
  9284. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  9285. typedef ListenerClass ListenerType;
  9286. const ArrayType& getListeners() const throw() { return listeners; }
  9287. private:
  9288. ArrayType listeners;
  9289. ListenerList (const ListenerList&);
  9290. ListenerList& operator= (const ListenerList&);
  9291. #undef LL_TEMPLATE
  9292. #undef LL_PARAM
  9293. };
  9294. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  9295. /*** End of inlined file: juce_ListenerList.h ***/
  9296. /**
  9297. Represents a shared variant value.
  9298. A Value object contains a reference to a var object, and can get and set its value.
  9299. Listeners can be attached to be told when the value is changed.
  9300. The Value class is a wrapper around a shared, reference-counted underlying data
  9301. object - this means that multiple Value objects can all refer to the same piece of
  9302. data, allowing all of them to be notified when any of them changes it.
  9303. When you create a Value with its default constructor, it acts as a wrapper around a
  9304. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  9305. you can map the Value onto any kind of underlying data.
  9306. */
  9307. class JUCE_API Value
  9308. {
  9309. public:
  9310. /** Creates an empty Value, containing a void var. */
  9311. Value();
  9312. /** Creates a Value that refers to the same value as another one.
  9313. Note that this doesn't make a copy of the other value - both this and the other
  9314. Value will share the same underlying value, so that when either one alters it, both
  9315. will see it change.
  9316. */
  9317. Value (const Value& other);
  9318. /** Creates a Value that is set to the specified value. */
  9319. explicit Value (const var& initialValue);
  9320. /** Destructor. */
  9321. ~Value();
  9322. /** Returns the current value. */
  9323. const var getValue() const;
  9324. /** Returns the current value. */
  9325. operator const var() const;
  9326. /** Returns the value as a string.
  9327. This is alternative to writing things like "myValue.getValue().toString()".
  9328. */
  9329. const String toString() const;
  9330. /** Sets the current value.
  9331. You can also use operator= to set the value.
  9332. If there are any listeners registered, they will be notified of the
  9333. change asynchronously.
  9334. */
  9335. void setValue (const var& newValue);
  9336. /** Sets the current value.
  9337. This is the same as calling setValue().
  9338. If there are any listeners registered, they will be notified of the
  9339. change asynchronously.
  9340. */
  9341. Value& operator= (const var& newValue);
  9342. /** Makes this object refer to the same underlying ValueSource as another one.
  9343. Once this object has been connected to another one, changing either one
  9344. will update the other.
  9345. Existing listeners will still be registered after you call this method, and
  9346. they'll continue to receive messages when the new value changes.
  9347. */
  9348. void referTo (const Value& valueToReferTo);
  9349. /** Returns true if this value and the other one are references to the same value.
  9350. */
  9351. bool refersToSameSourceAs (const Value& other) const;
  9352. /** Compares two values.
  9353. This is a compare-by-value comparison, so is effectively the same as
  9354. saying (this->getValue() == other.getValue()).
  9355. */
  9356. bool operator== (const Value& other) const;
  9357. /** Compares two values.
  9358. This is a compare-by-value comparison, so is effectively the same as
  9359. saying (this->getValue() != other.getValue()).
  9360. */
  9361. bool operator!= (const Value& other) const;
  9362. /** Receives callbacks when a Value object changes.
  9363. @see Value::addListener
  9364. */
  9365. class JUCE_API Listener
  9366. {
  9367. public:
  9368. Listener() {}
  9369. virtual ~Listener() {}
  9370. /** Called when a Value object is changed.
  9371. Note that the Value object passed as a parameter may not be exactly the same
  9372. object that you registered the listener with - it might be a copy that refers
  9373. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  9374. */
  9375. virtual void valueChanged (Value& value) = 0;
  9376. };
  9377. /** Adds a listener to receive callbacks when the value changes.
  9378. The listener is added to this specific Value object, and not to the shared
  9379. object that it refers to. When this object is deleted, all the listeners will
  9380. be lost, even if other references to the same Value still exist. So when you're
  9381. adding a listener, make sure that you add it to a ValueTree instance that will last
  9382. for as long as you need the listener. In general, you'd never want to add a listener
  9383. to a local stack-based ValueTree, but more likely to one that's a member variable.
  9384. @see removeListener
  9385. */
  9386. void addListener (Listener* listener);
  9387. /** Removes a listener that was previously added with addListener(). */
  9388. void removeListener (Listener* listener);
  9389. /**
  9390. Used internally by the Value class as the base class for its shared value objects.
  9391. The Value class is essentially a reference-counted pointer to a shared instance
  9392. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  9393. ValueSource classes to allow Value objects to represent your own custom data items.
  9394. */
  9395. class JUCE_API ValueSource : public ReferenceCountedObject,
  9396. public AsyncUpdater
  9397. {
  9398. public:
  9399. ValueSource();
  9400. virtual ~ValueSource();
  9401. /** Returns the current value of this object. */
  9402. virtual const var getValue() const = 0;
  9403. /** Changes the current value.
  9404. This must also trigger a change message if the value actually changes.
  9405. */
  9406. virtual void setValue (const var& newValue) = 0;
  9407. /** Delivers a change message to all the listeners that are registered with
  9408. this value.
  9409. If dispatchSynchronously is true, the method will call all the listeners
  9410. before returning; otherwise it'll dispatch a message and make the call later.
  9411. */
  9412. void sendChangeMessage (bool dispatchSynchronously);
  9413. juce_UseDebuggingNewOperator
  9414. protected:
  9415. friend class Value;
  9416. SortedSet <Value*> valuesWithListeners;
  9417. void handleAsyncUpdate();
  9418. ValueSource (const ValueSource&);
  9419. ValueSource& operator= (const ValueSource&);
  9420. };
  9421. /** Creates a Value object that uses this valueSource object as its underlying data. */
  9422. explicit Value (ValueSource* valueSource);
  9423. /** Returns the ValueSource that this value is referring to. */
  9424. ValueSource& getValueSource() throw() { return *value; }
  9425. juce_UseDebuggingNewOperator
  9426. private:
  9427. friend class ValueSource;
  9428. ReferenceCountedObjectPtr <ValueSource> value;
  9429. ListenerList <Listener> listeners;
  9430. void callListeners();
  9431. // This is disallowed to avoid confusion about whether it should
  9432. // do a by-value or by-reference copy.
  9433. Value& operator= (const Value& other);
  9434. };
  9435. /** Writes a Value to an OutputStream as a UTF8 string. */
  9436. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  9437. #endif // __JUCE_VALUE_JUCEHEADER__
  9438. /*** End of inlined file: juce_Value.h ***/
  9439. #endif
  9440. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9441. /*** Start of inlined file: juce_ValueTree.h ***/
  9442. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9443. #define __JUCE_VALUETREE_JUCEHEADER__
  9444. /*** Start of inlined file: juce_UndoManager.h ***/
  9445. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  9446. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  9447. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  9448. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9449. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9450. /*** Start of inlined file: juce_ChangeListenerList.h ***/
  9451. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9452. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9453. /*** Start of inlined file: juce_ChangeListener.h ***/
  9454. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  9455. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  9456. /**
  9457. Receives callbacks about changes to some kind of object.
  9458. Many objects use a ChangeListenerList to keep a set of listeners which they
  9459. will inform when something changes. A subclass of ChangeListener
  9460. is used to receive these callbacks.
  9461. Note that the major difference between an ActionListener and a ChangeListener
  9462. is that for a ChangeListener, multiple changes will be coalesced into fewer
  9463. callbacks, but ActionListeners perform one callback for every event posted.
  9464. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  9465. */
  9466. class JUCE_API ChangeListener
  9467. {
  9468. public:
  9469. /** Destructor. */
  9470. virtual ~ChangeListener() {}
  9471. /** Overridden by your subclass to receive the callback.
  9472. @param objectThatHasChanged the value that was passed to the
  9473. ChangeListenerList::sendChangeMessage() method
  9474. */
  9475. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  9476. };
  9477. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  9478. /*** End of inlined file: juce_ChangeListener.h ***/
  9479. /*** Start of inlined file: juce_ScopedLock.h ***/
  9480. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  9481. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  9482. /**
  9483. Automatically locks and unlocks a CriticalSection object.
  9484. Use one of these as a local variable to control access to a CriticalSection.
  9485. e.g. @code
  9486. CriticalSection myCriticalSection;
  9487. for (;;)
  9488. {
  9489. const ScopedLock myScopedLock (myCriticalSection);
  9490. // myCriticalSection is now locked
  9491. ...do some stuff...
  9492. // myCriticalSection gets unlocked here.
  9493. }
  9494. @endcode
  9495. @see CriticalSection, ScopedUnlock
  9496. */
  9497. class JUCE_API ScopedLock
  9498. {
  9499. public:
  9500. /** Creates a ScopedLock.
  9501. As soon as it is created, this will lock the CriticalSection, and
  9502. when the ScopedLock object is deleted, the CriticalSection will
  9503. be unlocked.
  9504. Make sure this object is created and deleted by the same thread,
  9505. otherwise there are no guarantees what will happen! Best just to use it
  9506. as a local stack object, rather than creating one with the new() operator.
  9507. */
  9508. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  9509. /** Destructor.
  9510. The CriticalSection will be unlocked when the destructor is called.
  9511. Make sure this object is created and deleted by the same thread,
  9512. otherwise there are no guarantees what will happen!
  9513. */
  9514. inline ~ScopedLock() throw() { lock_.exit(); }
  9515. private:
  9516. const CriticalSection& lock_;
  9517. ScopedLock (const ScopedLock&);
  9518. ScopedLock& operator= (const ScopedLock&);
  9519. };
  9520. /**
  9521. Automatically unlocks and re-locks a CriticalSection object.
  9522. This is the reverse of a ScopedLock object - instead of locking the critical
  9523. section for the lifetime of this object, it unlocks it.
  9524. Make sure you don't try to unlock critical sections that aren't actually locked!
  9525. e.g. @code
  9526. CriticalSection myCriticalSection;
  9527. for (;;)
  9528. {
  9529. const ScopedLock myScopedLock (myCriticalSection);
  9530. // myCriticalSection is now locked
  9531. ... do some stuff with it locked ..
  9532. while (xyz)
  9533. {
  9534. ... do some stuff with it locked ..
  9535. const ScopedUnlock unlocker (myCriticalSection);
  9536. // myCriticalSection is now unlocked for the remainder of this block,
  9537. // and re-locked at the end.
  9538. ...do some stuff with it unlocked ...
  9539. }
  9540. // myCriticalSection gets unlocked here.
  9541. }
  9542. @endcode
  9543. @see CriticalSection, ScopedLock
  9544. */
  9545. class ScopedUnlock
  9546. {
  9547. public:
  9548. /** Creates a ScopedUnlock.
  9549. As soon as it is created, this will unlock the CriticalSection, and
  9550. when the ScopedLock object is deleted, the CriticalSection will
  9551. be re-locked.
  9552. Make sure this object is created and deleted by the same thread,
  9553. otherwise there are no guarantees what will happen! Best just to use it
  9554. as a local stack object, rather than creating one with the new() operator.
  9555. */
  9556. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  9557. /** Destructor.
  9558. The CriticalSection will be unlocked when the destructor is called.
  9559. Make sure this object is created and deleted by the same thread,
  9560. otherwise there are no guarantees what will happen!
  9561. */
  9562. inline ~ScopedUnlock() throw() { lock_.enter(); }
  9563. private:
  9564. const CriticalSection& lock_;
  9565. ScopedUnlock (const ScopedLock&);
  9566. ScopedUnlock& operator= (const ScopedUnlock&);
  9567. };
  9568. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  9569. /*** End of inlined file: juce_ScopedLock.h ***/
  9570. /**
  9571. A set of ChangeListeners.
  9572. Listeners can be added and removed from the list, and change messages can be
  9573. broadcast to all the listeners.
  9574. @see ChangeListener, ChangeBroadcaster
  9575. */
  9576. class JUCE_API ChangeListenerList : public MessageListener
  9577. {
  9578. public:
  9579. /** Creates an empty list. */
  9580. ChangeListenerList() throw();
  9581. /** Destructor. */
  9582. ~ChangeListenerList() throw();
  9583. /** Adds a listener to the list.
  9584. (Trying to add a listener that's already on the list will have no effect).
  9585. */
  9586. void addChangeListener (ChangeListener* listener) throw();
  9587. /** Removes a listener from the list.
  9588. If the listener isn't on the list, this won't have any effect.
  9589. */
  9590. void removeChangeListener (ChangeListener* listener) throw();
  9591. /** Removes all listeners from the list. */
  9592. void removeAllChangeListeners() throw();
  9593. /** Posts an asynchronous change message to all the listeners.
  9594. If a message has already been sent and hasn't yet been delivered, this
  9595. method won't send another - in this way it coalesces multiple frequent
  9596. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  9597. with the ActionListener, which posts a new event for every call to its
  9598. sendActionMessage() method.
  9599. Only listeners which are on the list when the change event is delivered
  9600. will receive the event - and this may include listeners that weren't on
  9601. the list when the change message was sent.
  9602. @param objectThatHasChanged this pointer is passed to the
  9603. ChangeListener::changeListenerCallback() method,
  9604. and can be any value the application needs
  9605. @see sendSynchronousChangeMessage
  9606. */
  9607. void sendChangeMessage (void* objectThatHasChanged) throw();
  9608. /** This will synchronously callback all the ChangeListeners.
  9609. Use this if you need to synchronously force a call to all the
  9610. listeners' ChangeListener::changeListenerCallback() methods.
  9611. */
  9612. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9613. /** If a change message has been sent but not yet dispatched, this will
  9614. use sendSynchronousChangeMessage() to make the callback immediately.
  9615. */
  9616. void dispatchPendingMessages();
  9617. /** @internal */
  9618. void handleMessage (const Message&);
  9619. juce_UseDebuggingNewOperator
  9620. private:
  9621. SortedSet <void*> listeners;
  9622. CriticalSection lock;
  9623. void* lastChangedObject;
  9624. bool messagePending;
  9625. ChangeListenerList (const ChangeListenerList&);
  9626. ChangeListenerList& operator= (const ChangeListenerList&);
  9627. };
  9628. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9629. /*** End of inlined file: juce_ChangeListenerList.h ***/
  9630. /** Manages a list of ChangeListeners, and can send them messages.
  9631. To quickly add methods to your class that can add/remove change
  9632. listeners and broadcast to them, you can derive from this.
  9633. @see ChangeListenerList, ChangeListener
  9634. */
  9635. class JUCE_API ChangeBroadcaster
  9636. {
  9637. public:
  9638. /** Creates an ChangeBroadcaster. */
  9639. ChangeBroadcaster() throw();
  9640. /** Destructor. */
  9641. virtual ~ChangeBroadcaster();
  9642. /** Adds a listener to the list.
  9643. (Trying to add a listener that's already on the list will have no effect).
  9644. */
  9645. void addChangeListener (ChangeListener* listener) throw();
  9646. /** Removes a listener from the list.
  9647. If the listener isn't on the list, this won't have any effect.
  9648. */
  9649. void removeChangeListener (ChangeListener* listener) throw();
  9650. /** Removes all listeners from the list. */
  9651. void removeAllChangeListeners() throw();
  9652. /** Broadcasts a change message to all the registered listeners.
  9653. The message will be delivered asynchronously by the event thread, so this
  9654. method will not directly call any of the listeners. For a synchronous
  9655. message, use sendSynchronousChangeMessage().
  9656. @see ChangeListenerList::sendActionMessage
  9657. */
  9658. void sendChangeMessage (void* objectThatHasChanged) throw();
  9659. /** Sends a synchronous change message to all the registered listeners.
  9660. @see ChangeListenerList::sendSynchronousChangeMessage
  9661. */
  9662. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9663. /** If a change message has been sent but not yet dispatched, this will
  9664. use sendSynchronousChangeMessage() to make the callback immediately.
  9665. */
  9666. void dispatchPendingMessages();
  9667. private:
  9668. ChangeListenerList changeListenerList;
  9669. ChangeBroadcaster (const ChangeBroadcaster&);
  9670. ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  9671. };
  9672. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9673. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  9674. /*** Start of inlined file: juce_UndoableAction.h ***/
  9675. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  9676. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  9677. /**
  9678. Used by the UndoManager class to store an action which can be done
  9679. and undone.
  9680. @see UndoManager
  9681. */
  9682. class JUCE_API UndoableAction
  9683. {
  9684. protected:
  9685. /** Creates an action. */
  9686. UndoableAction() throw() {}
  9687. public:
  9688. /** Destructor. */
  9689. virtual ~UndoableAction() {}
  9690. /** Overridden by a subclass to perform the action.
  9691. This method is called by the UndoManager, and shouldn't be used directly by
  9692. applications.
  9693. Be careful not to make any calls in a perform() method that could call
  9694. recursively back into the UndoManager::perform() method
  9695. @returns true if the action could be performed.
  9696. @see UndoManager::perform
  9697. */
  9698. virtual bool perform() = 0;
  9699. /** Overridden by a subclass to undo the action.
  9700. This method is called by the UndoManager, and shouldn't be used directly by
  9701. applications.
  9702. Be careful not to make any calls in an undo() method that could call
  9703. recursively back into the UndoManager::perform() method
  9704. @returns true if the action could be undone without any errors.
  9705. @see UndoManager::perform
  9706. */
  9707. virtual bool undo() = 0;
  9708. /** Returns a value to indicate how much memory this object takes up.
  9709. Because the UndoManager keeps a list of UndoableActions, this is used
  9710. to work out how much space each one will take up, so that the UndoManager
  9711. can work out how many to keep.
  9712. The default value returned here is 10 - units are arbitrary and
  9713. don't have to be accurate.
  9714. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9715. UndoManager::setMaxNumberOfStoredUnits
  9716. */
  9717. virtual int getSizeInUnits() { return 10; }
  9718. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  9719. If possible, this method should create and return a single action that does the same job as
  9720. this one followed by the supplied action.
  9721. If it's not possible to merge the two actions, the method should return zero.
  9722. */
  9723. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  9724. };
  9725. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9726. /*** End of inlined file: juce_UndoableAction.h ***/
  9727. /**
  9728. Manages a list of undo/redo commands.
  9729. An UndoManager object keeps a list of past actions and can use these actions
  9730. to move backwards and forwards through an undo history.
  9731. To use it, create subclasses of UndoableAction which perform all the
  9732. actions you need, then when you need to actually perform an action, create one
  9733. and pass it to the UndoManager's perform() method.
  9734. The manager also uses the concept of 'transactions' to group the actions
  9735. together - all actions performed between calls to beginNewTransaction() are
  9736. grouped together and are all undone/redone as a group.
  9737. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9738. when actions are performed or undone.
  9739. @see UndoableAction
  9740. */
  9741. class JUCE_API UndoManager : public ChangeBroadcaster
  9742. {
  9743. public:
  9744. /** Creates an UndoManager.
  9745. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9746. to indicate how much storage it takes up
  9747. (UndoableAction::getSizeInUnits()), so this
  9748. lets you specify the maximum total number of
  9749. units that the undomanager is allowed to
  9750. keep in memory before letting the older actions
  9751. drop off the end of the list.
  9752. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9753. that will be kept, even if this involves exceeding
  9754. the amount of space specified in maxNumberOfUnitsToKeep
  9755. */
  9756. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  9757. int minimumTransactionsToKeep = 30);
  9758. /** Destructor. */
  9759. ~UndoManager();
  9760. /** Deletes all stored actions in the list. */
  9761. void clearUndoHistory();
  9762. /** Returns the current amount of space to use for storing UndoableAction objects.
  9763. @see setMaxNumberOfStoredUnits
  9764. */
  9765. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9766. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9767. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9768. to indicate how much storage it takes up
  9769. (UndoableAction::getSizeInUnits()), so this
  9770. lets you specify the maximum total number of
  9771. units that the undomanager is allowed to
  9772. keep in memory before letting the older actions
  9773. drop off the end of the list.
  9774. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9775. that will be kept, even if this involves exceeding
  9776. the amount of space specified in maxNumberOfUnitsToKeep
  9777. @see getNumberOfUnitsTakenUpByStoredCommands
  9778. */
  9779. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  9780. int minimumTransactionsToKeep);
  9781. /** Performs an action and adds it to the undo history list.
  9782. @param action the action to perform - this will be deleted by the UndoManager
  9783. when no longer needed
  9784. @param actionName if this string is non-empty, the current transaction will be
  9785. given this name; if it's empty, the current transaction name will
  9786. be left unchanged. See setCurrentTransactionName()
  9787. @returns true if the command succeeds - see UndoableAction::perform
  9788. @see beginNewTransaction
  9789. */
  9790. bool perform (UndoableAction* action,
  9791. const String& actionName = String::empty);
  9792. /** Starts a new group of actions that together will be treated as a single transaction.
  9793. All actions that are passed to the perform() method between calls to this
  9794. method are grouped together and undone/redone together by a single call to
  9795. undo() or redo().
  9796. @param actionName a description of the transaction that is about to be
  9797. performed
  9798. */
  9799. void beginNewTransaction (const String& actionName = String::empty);
  9800. /** Changes the name stored for the current transaction.
  9801. Each transaction is given a name when the beginNewTransaction() method is
  9802. called, but this can be used to change that name without starting a new
  9803. transaction.
  9804. */
  9805. void setCurrentTransactionName (const String& newName);
  9806. /** Returns true if there's at least one action in the list to undo.
  9807. @see getUndoDescription, undo, canRedo
  9808. */
  9809. bool canUndo() const;
  9810. /** Returns the description of the transaction that would be next to get undone.
  9811. The description returned is the one that was passed into beginNewTransaction
  9812. before the set of actions was performed.
  9813. @see undo
  9814. */
  9815. const String getUndoDescription() const;
  9816. /** Tries to roll-back the last transaction.
  9817. @returns true if the transaction can be undone, and false if it fails, or
  9818. if there aren't any transactions to undo
  9819. */
  9820. bool undo();
  9821. /** Tries to roll-back any actions that were added to the current transaction.
  9822. This will perform an undo() only if there are some actions in the undo list
  9823. that were added after the last call to beginNewTransaction().
  9824. This is useful because it lets you call beginNewTransaction(), then
  9825. perform an operation which may or may not actually perform some actions, and
  9826. then call this method to get rid of any actions that might have been done
  9827. without it rolling back the previous transaction if nothing was actually
  9828. done.
  9829. @returns true if any actions were undone.
  9830. */
  9831. bool undoCurrentTransactionOnly();
  9832. /** Returns a list of the UndoableAction objects that have been performed during the
  9833. transaction that is currently open.
  9834. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9835. were to be called now.
  9836. The first item in the list is the earliest action performed.
  9837. */
  9838. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9839. /** Returns the number of UndoableAction objects that have been performed during the
  9840. transaction that is currently open.
  9841. @see getActionsInCurrentTransaction
  9842. */
  9843. int getNumActionsInCurrentTransaction() const;
  9844. /** Returns true if there's at least one action in the list to redo.
  9845. @see getRedoDescription, redo, canUndo
  9846. */
  9847. bool canRedo() const;
  9848. /** Returns the description of the transaction that would be next to get redone.
  9849. The description returned is the one that was passed into beginNewTransaction
  9850. before the set of actions was performed.
  9851. @see redo
  9852. */
  9853. const String getRedoDescription() const;
  9854. /** Tries to redo the last transaction that was undone.
  9855. @returns true if the transaction can be redone, and false if it fails, or
  9856. if there aren't any transactions to redo
  9857. */
  9858. bool redo();
  9859. juce_UseDebuggingNewOperator
  9860. private:
  9861. OwnedArray <OwnedArray <UndoableAction> > transactions;
  9862. StringArray transactionNames;
  9863. String currentTransactionName;
  9864. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  9865. bool newTransaction, reentrancyCheck;
  9866. // disallow copy constructor
  9867. UndoManager (const UndoManager&);
  9868. UndoManager& operator= (const UndoManager&);
  9869. };
  9870. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  9871. /*** End of inlined file: juce_UndoManager.h ***/
  9872. /**
  9873. A powerful tree structure that can be used to hold free-form data, and which can
  9874. handle its own undo and redo behaviour.
  9875. A ValueTree contains a list of named properties as var objects, and also holds
  9876. any number of sub-trees.
  9877. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  9878. they're simply a lightweight reference to a shared data container. Creating a copy
  9879. of another ValueTree simply creates a new reference to the same underlying object - to
  9880. make a separate, deep copy of a tree you should explicitly call createCopy().
  9881. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  9882. and much of the structure of a ValueTree is similar to an XmlElement tree.
  9883. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  9884. contain text elements, the conversion works well and makes a good serialisation
  9885. format. They can also be serialised to a binary format, which is very fast and compact.
  9886. All the methods that change data take an optional UndoManager, which will be used
  9887. to track any changes to the object. For this to work, you have to be careful to
  9888. consistently always use the same UndoManager for all operations to any node inside
  9889. the tree.
  9890. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  9891. one tree to another, be careful to always remove it first, before adding it. This
  9892. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  9893. assertions if you try to do anything dangerous, but there are still plenty of ways it
  9894. could go wrong.
  9895. Listeners can be added to a ValueTree to be told when properies change and when
  9896. nodes are added or removed.
  9897. @see var, XmlElement
  9898. */
  9899. class JUCE_API ValueTree
  9900. {
  9901. public:
  9902. /** Creates an empty, invalid ValueTree.
  9903. A ValueTree that is created with this constructor can't actually be used for anything,
  9904. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  9905. To create a real one, use the constructor that takes a string.
  9906. @see ValueTree::invalid
  9907. */
  9908. ValueTree() throw();
  9909. /** Creates an empty ValueTree with the given type name.
  9910. Like an XmlElement, each ValueTree node has a type, which you can access with
  9911. getType() and hasType().
  9912. */
  9913. explicit ValueTree (const Identifier& type);
  9914. /** Creates a reference to another ValueTree. */
  9915. ValueTree (const ValueTree& other);
  9916. /** Makes this object reference another node. */
  9917. ValueTree& operator= (const ValueTree& other);
  9918. /** Destructor. */
  9919. ~ValueTree();
  9920. /** Returns true if both this and the other tree node refer to the same underlying structure.
  9921. Note that this isn't a value comparison - two independently-created trees which
  9922. contain identical data are not considered equal.
  9923. */
  9924. bool operator== (const ValueTree& other) const throw();
  9925. /** Returns true if this and the other node refer to different underlying structures.
  9926. Note that this isn't a value comparison - two independently-created trees which
  9927. contain identical data are not considered equal.
  9928. */
  9929. bool operator!= (const ValueTree& other) const throw();
  9930. /** Performs a deep comparison between the properties and children of two trees.
  9931. If all the properties and children of the two trees are the same (recursively), this
  9932. returns true.
  9933. The normal operator==() only checks whether two trees refer to the same shared data
  9934. structure, so use this method if you need to do a proper value comparison.
  9935. */
  9936. bool isEquivalentTo (const ValueTree& other) const;
  9937. /** Returns true if this node refers to some valid data.
  9938. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  9939. call to getChild().
  9940. */
  9941. bool isValid() const { return object != 0; }
  9942. /** Returns a deep copy of this tree and all its sub-nodes. */
  9943. ValueTree createCopy() const;
  9944. /** Returns the type of this node.
  9945. The type is specified when the ValueTree is created.
  9946. @see hasType
  9947. */
  9948. const Identifier getType() const;
  9949. /** Returns true if the node has this type.
  9950. The comparison is case-sensitive.
  9951. */
  9952. bool hasType (const Identifier& typeName) const;
  9953. /** Returns the value of a named property.
  9954. If no such property has been set, this will return a void variant.
  9955. You can also use operator[] to get a property.
  9956. @see var, setProperty, hasProperty
  9957. */
  9958. const var& getProperty (const Identifier& name) const;
  9959. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  9960. If no such property has been set, this will return the value of defaultReturnValue.
  9961. You can also use operator[] and getProperty to get a property.
  9962. @see var, getProperty, setProperty, hasProperty
  9963. */
  9964. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  9965. /** Returns the value of a named property.
  9966. If no such property has been set, this will return a void variant. This is the same as
  9967. calling getProperty().
  9968. @see getProperty
  9969. */
  9970. const var& operator[] (const Identifier& name) const;
  9971. /** Changes a named property of the node.
  9972. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9973. so that this change can be undone.
  9974. @see var, getProperty, removeProperty
  9975. */
  9976. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  9977. /** Returns true if the node contains a named property. */
  9978. bool hasProperty (const Identifier& name) const;
  9979. /** Removes a property from the node.
  9980. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9981. so that this change can be undone.
  9982. */
  9983. void removeProperty (const Identifier& name, UndoManager* undoManager);
  9984. /** Removes all properties from the node.
  9985. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  9986. so that this change can be undone.
  9987. */
  9988. void removeAllProperties (UndoManager* undoManager);
  9989. /** Returns the total number of properties that the node contains.
  9990. @see getProperty.
  9991. */
  9992. int getNumProperties() const;
  9993. /** Returns the identifier of the property with a given index.
  9994. @see getNumProperties
  9995. */
  9996. const Identifier getPropertyName (int index) const;
  9997. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  9998. The Value object will maintain a reference to this tree, and will use the undo manager when
  9999. it needs to change the value. Attaching a Value::Listener to the value object will provide
  10000. callbacks whenever the property changes.
  10001. */
  10002. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  10003. /** Returns the number of child nodes belonging to this one.
  10004. @see getChild
  10005. */
  10006. int getNumChildren() const;
  10007. /** Returns one of this node's child nodes.
  10008. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  10009. whether a node is valid).
  10010. */
  10011. ValueTree getChild (int index) const;
  10012. /** Looks for a child node with the speficied type name.
  10013. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10014. whether a node is valid).
  10015. */
  10016. ValueTree getChildWithName (const Identifier& type) const;
  10017. /** Looks for the first child node that has the speficied property value.
  10018. This will scan the child nodes in order, until it finds one that has property that matches
  10019. the specified value.
  10020. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10021. whether a node is valid).
  10022. */
  10023. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10024. /** Adds a child to this node.
  10025. Make sure that the child is removed from any former parent node before calling this, or
  10026. you'll hit an assertion.
  10027. If the index is < 0 or greater than the current number of child nodes, the new node will
  10028. be added at the end of the list.
  10029. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10030. so that this change can be undone.
  10031. */
  10032. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  10033. /** Removes the specified child from this node's child-list.
  10034. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10035. so that this change can be undone.
  10036. */
  10037. void removeChild (const ValueTree& child, UndoManager* undoManager);
  10038. /** Removes a child from this node's child-list.
  10039. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10040. so that this change can be undone.
  10041. */
  10042. void removeChild (int childIndex, UndoManager* undoManager);
  10043. /** Removes all child-nodes from this node.
  10044. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10045. so that this change can be undone.
  10046. */
  10047. void removeAllChildren (UndoManager* undoManager);
  10048. /** Moves one of the children to a different index.
  10049. This will move the child to a specified index, shuffling along any intervening
  10050. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  10051. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10052. @param currentIndex the index of the item to be moved. If this isn't a
  10053. valid index, then nothing will be done
  10054. @param newIndex the index at which you'd like this item to end up. If this
  10055. is less than zero, the value will be moved to the end
  10056. of the list
  10057. @param undoManager the optional UndoManager to use to store this transaction
  10058. */
  10059. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  10060. /** Returns true if this node is anywhere below the specified parent node.
  10061. This returns true if the node is a child-of-a-child, as well as a direct child.
  10062. */
  10063. bool isAChildOf (const ValueTree& possibleParent) const;
  10064. /** Returns the index of a child item in this parent.
  10065. If the child isn't found, this returns -1.
  10066. */
  10067. int indexOf (const ValueTree& child) const;
  10068. /** Returns the parent node that contains this one.
  10069. If the node has no parent, this will return an invalid node. (See isValid() to find out
  10070. whether a node is valid).
  10071. */
  10072. ValueTree getParent() const;
  10073. /** Creates an XmlElement that holds a complete image of this node and all its children.
  10074. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  10075. be used to recreate a similar node by calling fromXml()
  10076. @see fromXml
  10077. */
  10078. XmlElement* createXml() const;
  10079. /** Tries to recreate a node from its XML representation.
  10080. This isn't designed to cope with random XML data - for a sensible result, it should only
  10081. be fed XML that was created by the createXml() method.
  10082. */
  10083. static ValueTree fromXml (const XmlElement& xml);
  10084. /** Stores this tree (and all its children) in a binary format.
  10085. Once written, the data can be read back with readFromStream().
  10086. It's much faster to load/save your tree in binary form than as XML, but
  10087. obviously isn't human-readable.
  10088. */
  10089. void writeToStream (OutputStream& output);
  10090. /** Reloads a tree from a stream that was written with writeToStream(). */
  10091. static ValueTree readFromStream (InputStream& input);
  10092. /** Reloads a tree from a data block that was written with writeToStream(). */
  10093. static ValueTree readFromData (const void* data, size_t numBytes);
  10094. /** Listener class for events that happen to a ValueTree.
  10095. To get events from a ValueTree, make your class implement this interface, and use
  10096. ValueTree::addListener() and ValueTree::removeListener() to register it.
  10097. */
  10098. class JUCE_API Listener
  10099. {
  10100. public:
  10101. /** Destructor. */
  10102. virtual ~Listener() {}
  10103. /** This method is called when a property of this node (or of one of its sub-nodes) has
  10104. changed.
  10105. The tree parameter indicates which tree has had its property changed, and the property
  10106. parameter indicates the property.
  10107. Note that when you register a listener to a tree, it will receive this callback for
  10108. property changes in that tree, and also for any of its children, (recursively, at any depth).
  10109. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10110. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10111. */
  10112. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  10113. const Identifier& property) = 0;
  10114. /** This method is called when a child sub-tree is added or removed.
  10115. The tree parameter indicates the tree whose child was added or removed.
  10116. Note that when you register a listener to a tree, it will receive this callback for
  10117. child changes in that tree, and also in any of its children, (recursively, at any depth).
  10118. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10119. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10120. */
  10121. virtual void valueTreeChildrenChanged (ValueTree& treeWhoseChildHasChanged) = 0;
  10122. /** This method is called when a tree has been added or removed from a parent node.
  10123. This callback happens when the tree to which the listener was registered is added or
  10124. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  10125. the listener is registered, and not to any of its children.
  10126. */
  10127. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  10128. };
  10129. /** Adds a listener to receive callbacks when this node is changed.
  10130. The listener is added to this specific ValueTree object, and not to the shared
  10131. object that it refers to. When this object is deleted, all the listeners will
  10132. be lost, even if other references to the same ValueTree still exist. And if you
  10133. use the operator= to make this refer to a different ValueTree, any listeners will
  10134. begin listening to changes to the new tree instead of the old one.
  10135. When you're adding a listener, make sure that you add it to a ValueTree instance that
  10136. will last for as long as you need the listener. In general, you'd never want to add a
  10137. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  10138. @see removeListener
  10139. */
  10140. void addListener (Listener* listener);
  10141. /** Removes a listener that was previously added with addListener(). */
  10142. void removeListener (Listener* listener);
  10143. /** This method uses a comparator object to sort the tree's children into order.
  10144. The object provided must have a method of the form:
  10145. @code
  10146. int compareElements (const ValueTree& first, const ValueTree& second);
  10147. @endcode
  10148. ..and this method must return:
  10149. - a value of < 0 if the first comes before the second
  10150. - a value of 0 if the two objects are equivalent
  10151. - a value of > 0 if the second comes before the first
  10152. To improve performance, the compareElements() method can be declared as static or const.
  10153. @param comparator the comparator to use for comparing elements.
  10154. @param retainOrderOfEquivalentItems if this is true, then items
  10155. which the comparator says are equivalent will be
  10156. kept in the order in which they currently appear
  10157. in the array. This is slower to perform, but may
  10158. be important in some cases. If it's false, a faster
  10159. algorithm is used, but equivalent elements may be
  10160. rearranged.
  10161. */
  10162. template <typename ElementComparator>
  10163. void sort (ElementComparator& comparator, const bool retainOrderOfEquivalentItems = false)
  10164. {
  10165. if (object != 0)
  10166. {
  10167. ComparatorAdapter <ElementComparator> adapter (comparator);
  10168. object->children.sort (adapter, retainOrderOfEquivalentItems);
  10169. object->sendChildChangeMessage();
  10170. }
  10171. }
  10172. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  10173. This invalid object is equivalent to ValueTree created with its default constructor.
  10174. */
  10175. static const ValueTree invalid;
  10176. juce_UseDebuggingNewOperator
  10177. private:
  10178. class SetPropertyAction;
  10179. friend class SetPropertyAction;
  10180. class AddOrRemoveChildAction;
  10181. friend class AddOrRemoveChildAction;
  10182. class MoveChildAction;
  10183. friend class MoveChildAction;
  10184. class JUCE_API SharedObject : public ReferenceCountedObject
  10185. {
  10186. public:
  10187. explicit SharedObject (const Identifier& type);
  10188. SharedObject (const SharedObject& other);
  10189. ~SharedObject();
  10190. const Identifier type;
  10191. NamedValueSet properties;
  10192. ReferenceCountedArray <SharedObject> children;
  10193. SortedSet <ValueTree*> valueTreesWithListeners;
  10194. SharedObject* parent;
  10195. void sendPropertyChangeMessage (const Identifier& property);
  10196. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  10197. void sendChildChangeMessage();
  10198. void sendChildChangeMessage (ValueTree& tree);
  10199. void sendParentChangeMessage();
  10200. const var& getProperty (const Identifier& name) const;
  10201. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10202. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  10203. bool hasProperty (const Identifier& name) const;
  10204. void removeProperty (const Identifier& name, UndoManager*);
  10205. void removeAllProperties (UndoManager*);
  10206. bool isAChildOf (const SharedObject* possibleParent) const;
  10207. int indexOf (const ValueTree& child) const;
  10208. ValueTree getChildWithName (const Identifier& type) const;
  10209. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10210. void addChild (SharedObject* child, int index, UndoManager*);
  10211. void removeChild (int childIndex, UndoManager*);
  10212. void removeAllChildren (UndoManager*);
  10213. void moveChild (int currentIndex, int newIndex, UndoManager*);
  10214. bool isEquivalentTo (const SharedObject& other) const;
  10215. XmlElement* createXml() const;
  10216. juce_UseDebuggingNewOperator
  10217. private:
  10218. SharedObject& operator= (const SharedObject&);
  10219. };
  10220. template <typename ElementComparator>
  10221. class ComparatorAdapter
  10222. {
  10223. public:
  10224. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  10225. int compareElements (SharedObject* const first, SharedObject* const second)
  10226. {
  10227. return comparator.compareElements (ValueTree (first), ValueTree (second));
  10228. }
  10229. private:
  10230. ElementComparator& comparator;
  10231. ComparatorAdapter (const ComparatorAdapter&);
  10232. ComparatorAdapter& operator= (const ComparatorAdapter&);
  10233. };
  10234. friend class SharedObject;
  10235. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  10236. SharedObjectPtr object;
  10237. ListenerList <Listener> listeners;
  10238. #if JUCE_MSVC && ! DOXYGEN
  10239. public: // (workaround for VC6)
  10240. #endif
  10241. explicit ValueTree (SharedObject*);
  10242. };
  10243. #endif // __JUCE_VALUETREE_JUCEHEADER__
  10244. /*** End of inlined file: juce_ValueTree.h ***/
  10245. #endif
  10246. #ifndef __JUCE_VARIANT_JUCEHEADER__
  10247. #endif
  10248. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  10249. #endif
  10250. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  10251. #endif
  10252. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10253. /*** Start of inlined file: juce_FileLogger.h ***/
  10254. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10255. #define __JUCE_FILELOGGER_JUCEHEADER__
  10256. /**
  10257. A simple implemenation of a Logger that writes to a file.
  10258. @see Logger
  10259. */
  10260. class JUCE_API FileLogger : public Logger
  10261. {
  10262. public:
  10263. /** Creates a FileLogger for a given file.
  10264. @param fileToWriteTo the file that to use - new messages will be appended
  10265. to the file. If the file doesn't exist, it will be created,
  10266. along with any parent directories that are needed.
  10267. @param welcomeMessage when opened, the logger will write a header to the log, along
  10268. with the current date and time, and this welcome message
  10269. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  10270. but is larger than this number of bytes, then the start of the
  10271. file will be truncated to keep the size down. This prevents a log
  10272. file getting ridiculously large over time. The file will be truncated
  10273. at a new-line boundary. If this value is less than zero, no size limit
  10274. will be imposed; if it's zero, the file will always be deleted. Note that
  10275. the size is only checked once when this object is created - any logging
  10276. that is done later will be appended without any checking
  10277. */
  10278. FileLogger (const File& fileToWriteTo,
  10279. const String& welcomeMessage,
  10280. const int maxInitialFileSizeBytes = 128 * 1024);
  10281. /** Destructor. */
  10282. ~FileLogger();
  10283. void logMessage (const String& message);
  10284. const File getLogFile() const { return logFile; }
  10285. /** Helper function to create a log file in the correct place for this platform.
  10286. On Windows this will return a logger with a path such as:
  10287. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  10288. On the Mac it'll create something like:
  10289. ~/Library/Logs/[logFileName]
  10290. The method might return 0 if the file can't be created for some reason.
  10291. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  10292. it's best to use the something like the name of your application here.
  10293. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  10294. call it "log.txt" because if it goes in a directory with logs
  10295. from other applications (as it will do on the Mac) then no-one
  10296. will know which one is yours!
  10297. @param welcomeMessage a message that will be written to the log when it's opened.
  10298. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  10299. */
  10300. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  10301. const String& logFileName,
  10302. const String& welcomeMessage,
  10303. const int maxInitialFileSizeBytes = 128 * 1024);
  10304. juce_UseDebuggingNewOperator
  10305. private:
  10306. File logFile;
  10307. CriticalSection logLock;
  10308. ScopedPointer <FileOutputStream> logStream;
  10309. void trimFileSize (int maxFileSizeBytes) const;
  10310. FileLogger (const FileLogger&);
  10311. FileLogger& operator= (const FileLogger&);
  10312. };
  10313. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  10314. /*** End of inlined file: juce_FileLogger.h ***/
  10315. #endif
  10316. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10317. /*** Start of inlined file: juce_Initialisation.h ***/
  10318. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10319. #define __JUCE_INITIALISATION_JUCEHEADER__
  10320. /** Initialises Juce's GUI classes.
  10321. If you're embedding Juce into an application that uses its own event-loop rather
  10322. than using the START_JUCE_APPLICATION macro, call this function before making any
  10323. Juce calls, to make sure things are initialised correctly.
  10324. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10325. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10326. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  10327. */
  10328. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  10329. /** Clears up any static data being used by Juce's GUI classes.
  10330. If you're embedding Juce into an application that uses its own event-loop rather
  10331. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  10332. code to clean up any juce objects that might be lying around.
  10333. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  10334. */
  10335. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  10336. /** Initialises the core parts of Juce.
  10337. If you're embedding Juce into either a command-line program, call this function
  10338. at the start of your main() function to make sure that Juce is initialised correctly.
  10339. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10340. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10341. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  10342. */
  10343. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  10344. /** Clears up any static data being used by Juce's non-gui core classes.
  10345. If you're embedding Juce into either a command-line program, call this function
  10346. at the end of your main() function if you want to make sure any Juce objects are
  10347. cleaned up correctly.
  10348. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  10349. */
  10350. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  10351. /** A utility object that helps you initialise and shutdown Juce correctly
  10352. using an RAII pattern.
  10353. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  10354. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  10355. make sure that these functions are matched correctly.
  10356. This class is particularly handy to use at the beginning of a console app's
  10357. main() function, because it'll take care of shutting down whenever you return
  10358. from the main() call.
  10359. @see ScopedJuceInitialiser_GUI
  10360. */
  10361. class ScopedJuceInitialiser_NonGUI
  10362. {
  10363. public:
  10364. /** The constructor simply calls initialiseJuce_NonGUI(). */
  10365. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  10366. /** The destructor simply calls shutdownJuce_NonGUI(). */
  10367. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  10368. };
  10369. /** A utility object that helps you initialise and shutdown Juce correctly
  10370. using an RAII pattern.
  10371. When an instance of this class is created, it calls initialiseJuce_GUI(),
  10372. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  10373. make sure that these functions are matched correctly.
  10374. This class is particularly handy to use at the beginning of a console app's
  10375. main() function, because it'll take care of shutting down whenever you return
  10376. from the main() call.
  10377. @see ScopedJuceInitialiser_NonGUI
  10378. */
  10379. class ScopedJuceInitialiser_GUI
  10380. {
  10381. public:
  10382. /** The constructor simply calls initialiseJuce_GUI(). */
  10383. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  10384. /** The destructor simply calls shutdownJuce_GUI(). */
  10385. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  10386. };
  10387. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  10388. /*** End of inlined file: juce_Initialisation.h ***/
  10389. #endif
  10390. #ifndef __JUCE_LOGGER_JUCEHEADER__
  10391. #endif
  10392. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  10393. #endif
  10394. #ifndef __JUCE_MEMORY_JUCEHEADER__
  10395. #endif
  10396. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10397. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  10398. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10399. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10400. /** A timer for measuring performance of code and dumping the results to a file.
  10401. e.g. @code
  10402. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  10403. for (;;)
  10404. {
  10405. pc.start();
  10406. doSomethingFishy();
  10407. pc.stop();
  10408. }
  10409. @endcode
  10410. In this example, the time of each period between calling start/stop will be
  10411. measured and averaged over 50 runs, and the results printed to a file
  10412. every 50 times round the loop.
  10413. */
  10414. class JUCE_API PerformanceCounter
  10415. {
  10416. public:
  10417. /** Creates a PerformanceCounter object.
  10418. @param counterName the name used when printing out the statistics
  10419. @param runsPerPrintout the number of start/stop iterations before calling
  10420. printStatistics()
  10421. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  10422. the results are just written to the debugger output
  10423. */
  10424. PerformanceCounter (const String& counterName,
  10425. int runsPerPrintout = 100,
  10426. const File& loggingFile = File::nonexistent);
  10427. /** Destructor. */
  10428. ~PerformanceCounter();
  10429. /** Starts timing.
  10430. @see stop
  10431. */
  10432. void start();
  10433. /** Stops timing and prints out the results.
  10434. The number of iterations before doing a printout of the
  10435. results is set in the constructor.
  10436. @see start
  10437. */
  10438. void stop();
  10439. /** Dumps the current metrics to the debugger output and to a file.
  10440. As well as using Logger::outputDebugString to print the results,
  10441. this will write then to the file specified in the constructor (if
  10442. this was valid).
  10443. */
  10444. void printStatistics();
  10445. juce_UseDebuggingNewOperator
  10446. private:
  10447. String name;
  10448. int numRuns, runsPerPrint;
  10449. double totalTime;
  10450. int64 started;
  10451. File outputFile;
  10452. };
  10453. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10454. /*** End of inlined file: juce_PerformanceCounter.h ***/
  10455. #endif
  10456. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  10457. #endif
  10458. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10459. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  10460. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10461. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10462. /**
  10463. A collection of miscellaneous platform-specific utilities.
  10464. */
  10465. class JUCE_API PlatformUtilities
  10466. {
  10467. public:
  10468. /** Plays the operating system's default alert 'beep' sound. */
  10469. static void beep();
  10470. /** Tries to launch the system's default reader for a given file or URL. */
  10471. static bool openDocument (const String& documentURL, const String& parameters);
  10472. /** Tries to launch the system's default email app to let the user create an email.
  10473. */
  10474. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  10475. const String& emailSubject,
  10476. const String& bodyText,
  10477. const StringArray& filesToAttach);
  10478. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  10479. /** MAC ONLY - Turns a Core CF String into a juce one. */
  10480. static const String cfStringToJuceString (CFStringRef cfString);
  10481. /** MAC ONLY - Turns a juce string into a Core CF one. */
  10482. static CFStringRef juceStringToCFString (const String& s);
  10483. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  10484. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  10485. /** MAC ONLY - Turns an FSRef into a juce string path. */
  10486. static const String makePathFromFSRef (FSRef* file);
  10487. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  10488. their precomposed equivalents.
  10489. */
  10490. static const String convertToPrecomposedUnicode (const String& s);
  10491. /** MAC ONLY - Gets the type of a file from the file's resources. */
  10492. static OSType getTypeOfFile (const String& filename);
  10493. /** MAC ONLY - Returns true if this file is actually a bundle. */
  10494. static bool isBundle (const String& filename);
  10495. /** MAC ONLY - Adds an item to the dock */
  10496. static void addItemToDock (const File& file);
  10497. /** MAC ONLY - Returns the current OS version number.
  10498. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  10499. */
  10500. static int getOSXMinorVersionNumber();
  10501. #endif
  10502. #if JUCE_WINDOWS || DOXYGEN
  10503. // Some registry helper functions:
  10504. /** WIN32 ONLY - Returns a string from the registry.
  10505. The path is a string for the entire path of a value in the registry,
  10506. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  10507. */
  10508. static const String getRegistryValue (const String& regValuePath,
  10509. const String& defaultValue = String::empty);
  10510. /** WIN32 ONLY - Sets a registry value as a string.
  10511. This will take care of creating any groups needed to get to the given
  10512. registry value.
  10513. */
  10514. static void setRegistryValue (const String& regValuePath,
  10515. const String& value);
  10516. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  10517. static bool registryValueExists (const String& regValuePath);
  10518. /** WIN32 ONLY - Deletes a registry value. */
  10519. static void deleteRegistryValue (const String& regValuePath);
  10520. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  10521. static void deleteRegistryKey (const String& regKeyPath);
  10522. /** WIN32 ONLY - Creates a file association in the registry.
  10523. This lets you set the exe that should be launched by a given file extension.
  10524. @param fileExtension the file extension to associate, including the
  10525. initial dot, e.g. ".txt"
  10526. @param symbolicDescription a space-free short token to identify the file type
  10527. @param fullDescription a human-readable description of the file type
  10528. @param targetExecutable the executable that should be launched
  10529. @param iconResourceNumber the icon that gets displayed for the file type will be
  10530. found by looking up this resource number in the
  10531. executable. Pass 0 here to not use an icon
  10532. */
  10533. static void registerFileAssociation (const String& fileExtension,
  10534. const String& symbolicDescription,
  10535. const String& fullDescription,
  10536. const File& targetExecutable,
  10537. int iconResourceNumber);
  10538. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  10539. In a normal Juce application this will be set to the module handle
  10540. of the application executable.
  10541. If you're writing a DLL using Juce and plan to use any Juce messaging or
  10542. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  10543. to set the correct module handle in your DllMain() function, because
  10544. the win32 system relies on the correct instance handle when opening windows.
  10545. */
  10546. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  10547. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  10548. @see getCurrentModuleInstanceHandle()
  10549. */
  10550. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10551. /** WIN32 ONLY - Gets the command-line params as a string.
  10552. This is needed to avoid unicode problems with the argc type params.
  10553. */
  10554. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  10555. #endif
  10556. /** Clears the floating point unit's flags.
  10557. Only has an effect under win32, currently.
  10558. */
  10559. static void fpuReset();
  10560. #if JUCE_LINUX || JUCE_WINDOWS
  10561. /** Loads a dynamically-linked library into the process's address space.
  10562. @param pathOrFilename the platform-dependent name and search path
  10563. @returns a handle which can be used by getProcedureEntryPoint(), or
  10564. zero if it fails.
  10565. @see freeDynamicLibrary, getProcedureEntryPoint
  10566. */
  10567. static void* loadDynamicLibrary (const String& pathOrFilename);
  10568. /** Frees a dynamically-linked library.
  10569. @param libraryHandle a handle created by loadDynamicLibrary
  10570. @see loadDynamicLibrary, getProcedureEntryPoint
  10571. */
  10572. static void freeDynamicLibrary (void* libraryHandle);
  10573. /** Finds a procedure call in a dynamically-linked library.
  10574. @param libraryHandle a library handle returned by loadDynamicLibrary
  10575. @param procedureName the name of the procedure call to try to load
  10576. @returns a pointer to the function if found, or 0 if it fails
  10577. @see loadDynamicLibrary
  10578. */
  10579. static void* getProcedureEntryPoint (void* libraryHandle,
  10580. const String& procedureName);
  10581. #endif
  10582. #if JUCE_LINUX || DOXYGEN
  10583. #endif
  10584. private:
  10585. PlatformUtilities();
  10586. PlatformUtilities (const PlatformUtilities&);
  10587. PlatformUtilities& operator= (const PlatformUtilities&);
  10588. };
  10589. #if JUCE_MAC || JUCE_IPHONE
  10590. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10591. using RAII.
  10592. */
  10593. class ScopedAutoReleasePool
  10594. {
  10595. public:
  10596. ScopedAutoReleasePool();
  10597. ~ScopedAutoReleasePool();
  10598. private:
  10599. void* pool;
  10600. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  10601. ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  10602. };
  10603. #endif
  10604. #if JUCE_LINUX
  10605. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  10606. using an RAII approach.
  10607. */
  10608. class ScopedXLock
  10609. {
  10610. public:
  10611. /** Creating a ScopedXLock object locks the X display.
  10612. This uses XLockDisplay() to grab the display that Juce is using.
  10613. */
  10614. ScopedXLock();
  10615. /** Deleting a ScopedXLock object unlocks the X display.
  10616. This calls XUnlockDisplay() to release the lock.
  10617. */
  10618. ~ScopedXLock();
  10619. };
  10620. #endif
  10621. #if JUCE_MAC
  10622. /**
  10623. A wrapper class for picking up events from an Apple IR remote control device.
  10624. To use it, just create a subclass of this class, implementing the buttonPressed()
  10625. callback, then call start() and stop() to start or stop receiving events.
  10626. */
  10627. class JUCE_API AppleRemoteDevice
  10628. {
  10629. public:
  10630. AppleRemoteDevice();
  10631. virtual ~AppleRemoteDevice();
  10632. /** The set of buttons that may be pressed.
  10633. @see buttonPressed
  10634. */
  10635. enum ButtonType
  10636. {
  10637. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10638. playButton, /**< The play button. */
  10639. plusButton, /**< The plus or volume-up button. */
  10640. minusButton, /**< The minus or volume-down button. */
  10641. rightButton, /**< The right button (if it's held for a short time). */
  10642. leftButton, /**< The left button (if it's held for a short time). */
  10643. rightButton_Long, /**< The right button (if it's held for a long time). */
  10644. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10645. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10646. playButtonSleepMode,
  10647. switched
  10648. };
  10649. /** Override this method to receive the callback about a button press.
  10650. The callback will happen on the application's message thread.
  10651. Some buttons trigger matching up and down events, in which the isDown parameter
  10652. will be true and then false. Others only send a single event when the
  10653. button is pressed.
  10654. */
  10655. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10656. /** Starts the device running and responding to events.
  10657. Returns true if it managed to open the device.
  10658. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10659. and will not be available to any other part of the system. If
  10660. false, it will be shared with other apps.
  10661. @see stop
  10662. */
  10663. bool start (const bool inExclusiveMode);
  10664. /** Stops the device running.
  10665. @see start
  10666. */
  10667. void stop();
  10668. /** Returns true if the device has been started successfully.
  10669. */
  10670. bool isActive() const;
  10671. /** Returns the ID number of the remote, if it has sent one.
  10672. */
  10673. int getRemoteId() const { return remoteId; }
  10674. juce_UseDebuggingNewOperator
  10675. /** @internal */
  10676. void handleCallbackInternal();
  10677. private:
  10678. void* device;
  10679. void* queue;
  10680. int remoteId;
  10681. bool open (const bool openInExclusiveMode);
  10682. AppleRemoteDevice (const AppleRemoteDevice&);
  10683. AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  10684. };
  10685. #endif
  10686. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10687. /*** End of inlined file: juce_PlatformUtilities.h ***/
  10688. #endif
  10689. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10690. /*** Start of inlined file: juce_Random.h ***/
  10691. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10692. #define __JUCE_RANDOM_JUCEHEADER__
  10693. /**
  10694. A simple pseudo-random number generator.
  10695. */
  10696. class JUCE_API Random
  10697. {
  10698. public:
  10699. /** Creates a Random object based on a seed value.
  10700. For a given seed value, the subsequent numbers generated by this object
  10701. will be predictable, so a good idea is to set this value based
  10702. on the time, e.g.
  10703. new Random (Time::currentTimeMillis())
  10704. */
  10705. explicit Random (int64 seedValue) throw();
  10706. /** Destructor. */
  10707. ~Random() throw();
  10708. /** Returns the next random 32 bit integer.
  10709. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  10710. */
  10711. int nextInt() throw();
  10712. /** Returns the next random number, limited to a given range.
  10713. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  10714. */
  10715. int nextInt (int maxValue) throw();
  10716. /** Returns the next 64-bit random number.
  10717. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  10718. */
  10719. int64 nextInt64() throw();
  10720. /** Returns the next random floating-point number.
  10721. @returns a random value in the range 0 to 1.0
  10722. */
  10723. float nextFloat() throw();
  10724. /** Returns the next random floating-point number.
  10725. @returns a random value in the range 0 to 1.0
  10726. */
  10727. double nextDouble() throw();
  10728. /** Returns the next random boolean value.
  10729. */
  10730. bool nextBool() throw();
  10731. /** Returns a BigInteger containing a random number.
  10732. @returns a random value in the range 0 to (maximumValue - 1).
  10733. */
  10734. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  10735. /** Sets a range of bits in a BigInteger to random values. */
  10736. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  10737. /** To avoid the overhead of having to create a new Random object whenever
  10738. you need a number, this is a shared application-wide object that
  10739. can be used.
  10740. It's not thread-safe though, so threads should use their own Random object.
  10741. */
  10742. static Random& getSystemRandom() throw();
  10743. /** Resets this Random object to a given seed value. */
  10744. void setSeed (int64 newSeed) throw();
  10745. /** Merges this object's seed with another value.
  10746. This sets the seed to be a value created by combining the current seed and this
  10747. new value.
  10748. */
  10749. void combineSeed (int64 seedValue) throw();
  10750. /** Reseeds this generator using a value generated from various semi-random system
  10751. properties like the current time, etc.
  10752. Because this function convolves the time with the last seed value, calling
  10753. it repeatedly will increase the randomness of the final result.
  10754. */
  10755. void setSeedRandomly();
  10756. juce_UseDebuggingNewOperator
  10757. private:
  10758. int64 seed;
  10759. };
  10760. #endif // __JUCE_RANDOM_JUCEHEADER__
  10761. /*** End of inlined file: juce_Random.h ***/
  10762. #endif
  10763. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  10764. #endif
  10765. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10766. /*** Start of inlined file: juce_Singleton.h ***/
  10767. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10768. #define __JUCE_SINGLETON_JUCEHEADER__
  10769. /**
  10770. Macro to declare member variables and methods for a singleton class.
  10771. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  10772. to the class's definition.
  10773. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  10774. implementation code.
  10775. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  10776. destructor, in case it is deleted by other means than deleteInstance()
  10777. Clients can then call the static method MyClass::getInstance() to get a pointer
  10778. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  10779. no instance currently exists.
  10780. e.g. @code
  10781. class MySingleton
  10782. {
  10783. public:
  10784. MySingleton()
  10785. {
  10786. }
  10787. ~MySingleton()
  10788. {
  10789. // this ensures that no dangling pointers are left when the
  10790. // singleton is deleted.
  10791. clearSingletonInstance();
  10792. }
  10793. juce_DeclareSingleton (MySingleton, false)
  10794. };
  10795. juce_ImplementSingleton (MySingleton)
  10796. // example of usage:
  10797. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  10798. ...
  10799. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  10800. @endcode
  10801. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10802. than once during the process's lifetime - i.e. after you've created and deleted the
  10803. object, getInstance() will refuse to create another one. This can be useful to stop
  10804. objects being accidentally re-created during your app's shutdown code.
  10805. If you know that your object will only be created and deleted by a single thread, you
  10806. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  10807. of this one.
  10808. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  10809. */
  10810. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  10811. \
  10812. static classname* _singletonInstance; \
  10813. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  10814. \
  10815. static classname* getInstance() \
  10816. { \
  10817. if (_singletonInstance == 0) \
  10818. {\
  10819. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10820. \
  10821. if (_singletonInstance == 0) \
  10822. { \
  10823. static bool alreadyInside = false; \
  10824. static bool createdOnceAlready = false; \
  10825. \
  10826. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10827. jassert (! problem); \
  10828. if (! problem) \
  10829. { \
  10830. createdOnceAlready = true; \
  10831. alreadyInside = true; \
  10832. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10833. alreadyInside = false; \
  10834. \
  10835. _singletonInstance = newObject; \
  10836. } \
  10837. } \
  10838. } \
  10839. \
  10840. return _singletonInstance; \
  10841. } \
  10842. \
  10843. static inline classname* getInstanceWithoutCreating() throw() \
  10844. { \
  10845. return _singletonInstance; \
  10846. } \
  10847. \
  10848. static void deleteInstance() \
  10849. { \
  10850. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10851. if (_singletonInstance != 0) \
  10852. { \
  10853. classname* const old = _singletonInstance; \
  10854. _singletonInstance = 0; \
  10855. delete old; \
  10856. } \
  10857. } \
  10858. \
  10859. void clearSingletonInstance() throw() \
  10860. { \
  10861. if (_singletonInstance == this) \
  10862. _singletonInstance = 0; \
  10863. }
  10864. /** This is a counterpart to the juce_DeclareSingleton macro.
  10865. After adding the juce_DeclareSingleton to the class definition, this macro has
  10866. to be used in the cpp file.
  10867. */
  10868. #define juce_ImplementSingleton(classname) \
  10869. \
  10870. classname* classname::_singletonInstance = 0; \
  10871. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  10872. /**
  10873. Macro to declare member variables and methods for a singleton class.
  10874. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  10875. section to make access to it thread-safe. If you know that your object will
  10876. only ever be created or deleted by a single thread, then this is a
  10877. more efficient version to use.
  10878. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10879. than once during the process's lifetime - i.e. after you've created and deleted the
  10880. object, getInstance() will refuse to create another one. This can be useful to stop
  10881. objects being accidentally re-created during your app's shutdown code.
  10882. See the documentation for juce_DeclareSingleton for more information about
  10883. how to use it, the only difference being that you have to use
  10884. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  10885. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  10886. */
  10887. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  10888. \
  10889. static classname* _singletonInstance; \
  10890. \
  10891. static classname* getInstance() \
  10892. { \
  10893. if (_singletonInstance == 0) \
  10894. { \
  10895. static bool alreadyInside = false; \
  10896. static bool createdOnceAlready = false; \
  10897. \
  10898. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10899. jassert (! problem); \
  10900. if (! problem) \
  10901. { \
  10902. createdOnceAlready = true; \
  10903. alreadyInside = true; \
  10904. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10905. alreadyInside = false; \
  10906. \
  10907. _singletonInstance = newObject; \
  10908. } \
  10909. } \
  10910. \
  10911. return _singletonInstance; \
  10912. } \
  10913. \
  10914. static inline classname* getInstanceWithoutCreating() throw() \
  10915. { \
  10916. return _singletonInstance; \
  10917. } \
  10918. \
  10919. static void deleteInstance() \
  10920. { \
  10921. if (_singletonInstance != 0) \
  10922. { \
  10923. classname* const old = _singletonInstance; \
  10924. _singletonInstance = 0; \
  10925. delete old; \
  10926. } \
  10927. } \
  10928. \
  10929. void clearSingletonInstance() throw() \
  10930. { \
  10931. if (_singletonInstance == this) \
  10932. _singletonInstance = 0; \
  10933. }
  10934. /**
  10935. Macro to declare member variables and methods for a singleton class.
  10936. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  10937. for recursion or repeated instantiation. It's intended for use as a lightweight
  10938. version of a singleton, where you're using it in very straightforward
  10939. circumstances and don't need the extra checking.
  10940. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  10941. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  10942. See the documentation for juce_DeclareSingleton for more information about
  10943. how to use it, the only difference being that you have to use
  10944. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  10945. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  10946. */
  10947. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  10948. \
  10949. static classname* _singletonInstance; \
  10950. \
  10951. static classname* getInstance() \
  10952. { \
  10953. if (_singletonInstance == 0) \
  10954. _singletonInstance = new classname(); \
  10955. \
  10956. return _singletonInstance; \
  10957. } \
  10958. \
  10959. static inline classname* getInstanceWithoutCreating() throw() \
  10960. { \
  10961. return _singletonInstance; \
  10962. } \
  10963. \
  10964. static void deleteInstance() \
  10965. { \
  10966. if (_singletonInstance != 0) \
  10967. { \
  10968. classname* const old = _singletonInstance; \
  10969. _singletonInstance = 0; \
  10970. delete old; \
  10971. } \
  10972. } \
  10973. \
  10974. void clearSingletonInstance() throw() \
  10975. { \
  10976. if (_singletonInstance == this) \
  10977. _singletonInstance = 0; \
  10978. }
  10979. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  10980. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  10981. to the class definition, this macro has to be used somewhere in the cpp file.
  10982. */
  10983. #define juce_ImplementSingleton_SingleThreaded(classname) \
  10984. \
  10985. classname* classname::_singletonInstance = 0;
  10986. #endif // __JUCE_SINGLETON_JUCEHEADER__
  10987. /*** End of inlined file: juce_Singleton.h ***/
  10988. #endif
  10989. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  10990. #endif
  10991. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  10992. /*** Start of inlined file: juce_SystemStats.h ***/
  10993. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  10994. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  10995. /**
  10996. Contains methods for finding out about the current hardware and OS configuration.
  10997. */
  10998. class JUCE_API SystemStats
  10999. {
  11000. public:
  11001. /** Returns the current version of JUCE,
  11002. (just in case you didn't already know at compile-time.)
  11003. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  11004. */
  11005. static const String getJUCEVersion();
  11006. /** The set of possible results of the getOperatingSystemType() method.
  11007. */
  11008. enum OperatingSystemType
  11009. {
  11010. UnknownOS = 0,
  11011. MacOSX = 0x1000,
  11012. Linux = 0x2000,
  11013. Win95 = 0x4001,
  11014. Win98 = 0x4002,
  11015. WinNT351 = 0x4103,
  11016. WinNT40 = 0x4104,
  11017. Win2000 = 0x4105,
  11018. WinXP = 0x4106,
  11019. WinVista = 0x4107,
  11020. Windows7 = 0x4108,
  11021. Windows = 0x4000, /**< To test whether any version of Windows is running,
  11022. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  11023. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  11024. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  11025. };
  11026. /** Returns the type of operating system we're running on.
  11027. @returns one of the values from the OperatingSystemType enum.
  11028. @see getOperatingSystemName
  11029. */
  11030. static OperatingSystemType getOperatingSystemType();
  11031. /** Returns the name of the type of operating system we're running on.
  11032. @returns a string describing the OS type.
  11033. @see getOperatingSystemType
  11034. */
  11035. static const String getOperatingSystemName();
  11036. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  11037. */
  11038. static bool isOperatingSystem64Bit();
  11039. /** Returns the current user's name, if available.
  11040. @see getFullUserName()
  11041. */
  11042. static const String getLogonName();
  11043. /** Returns the current user's full name, if available.
  11044. On some OSes, this may just return the same value as getLogonName().
  11045. @see getLogonName()
  11046. */
  11047. static const String getFullUserName();
  11048. // CPU and memory information..
  11049. /** Returns the approximate CPU speed.
  11050. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  11051. what year you're reading this...)
  11052. */
  11053. static int getCpuSpeedInMegaherz();
  11054. /** Returns a string to indicate the CPU vendor.
  11055. Might not be known on some systems.
  11056. */
  11057. static const String getCpuVendor();
  11058. /** Checks whether Intel MMX instructions are available. */
  11059. static bool hasMMX();
  11060. /** Checks whether Intel SSE instructions are available. */
  11061. static bool hasSSE();
  11062. /** Checks whether Intel SSE2 instructions are available. */
  11063. static bool hasSSE2();
  11064. /** Checks whether AMD 3DNOW instructions are available. */
  11065. static bool has3DNow();
  11066. /** Returns the number of CPUs.
  11067. */
  11068. static int getNumCpus();
  11069. /** Finds out how much RAM is in the machine.
  11070. @returns the approximate number of megabytes of memory, or zero if
  11071. something goes wrong when finding out.
  11072. */
  11073. static int getMemorySizeInMegabytes();
  11074. /** Returns the system page-size.
  11075. This is only used by programmers with beards.
  11076. */
  11077. static int getPageSize();
  11078. /** Returns a list of MAC addresses found on this machine.
  11079. @param addresses an array into which the MAC addresses should be copied
  11080. @param maxNum the number of elements in this array
  11081. @param littleEndian the endianness of the numbers to return. If this is true,
  11082. the least-significant byte of each number is the first byte
  11083. of the mac address. If false, the least significant byte is
  11084. the last number. Note that the default values of this parameter
  11085. are different on Mac/PC to avoid breaking old software that was
  11086. written before this parameter was added (when the two systems
  11087. defaulted to using different endiannesses). In newer
  11088. software you probably want to specify an explicit value
  11089. for this.
  11090. @returns the number of MAC addresses that were found
  11091. */
  11092. static int getMACAddresses (int64* addresses, int maxNum,
  11093. #if JUCE_MAC
  11094. bool littleEndian = true);
  11095. #else
  11096. bool littleEndian = false);
  11097. #endif
  11098. /** Returns a list of MAC addresses found on this machine.
  11099. @returns an array of strings containing the MAC addresses that were found
  11100. */
  11101. static const StringArray getMACAddressStrings();
  11102. // not-for-public-use platform-specific method gets called at startup to initialise things.
  11103. static void initialiseStats();
  11104. private:
  11105. SystemStats();
  11106. SystemStats (const SystemStats&);
  11107. SystemStats& operator= (const SystemStats&);
  11108. };
  11109. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  11110. /*** End of inlined file: juce_SystemStats.h ***/
  11111. #endif
  11112. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  11113. #endif
  11114. #ifndef __JUCE_TIME_JUCEHEADER__
  11115. #endif
  11116. #ifndef __JUCE_UUID_JUCEHEADER__
  11117. /*** Start of inlined file: juce_Uuid.h ***/
  11118. #ifndef __JUCE_UUID_JUCEHEADER__
  11119. #define __JUCE_UUID_JUCEHEADER__
  11120. /**
  11121. A universally unique 128-bit identifier.
  11122. This class generates very random unique numbers based on the system time
  11123. and MAC addresses if any are available. It's extremely unlikely that two identical
  11124. UUIDs would ever be created by chance.
  11125. The class includes methods for saving the ID as a string or as raw binary data.
  11126. */
  11127. class JUCE_API Uuid
  11128. {
  11129. public:
  11130. /** Creates a new unique ID. */
  11131. Uuid();
  11132. /** Destructor. */
  11133. ~Uuid() throw();
  11134. /** Creates a copy of another UUID. */
  11135. Uuid (const Uuid& other);
  11136. /** Copies another UUID. */
  11137. Uuid& operator= (const Uuid& other);
  11138. /** Returns true if the ID is zero. */
  11139. bool isNull() const throw();
  11140. /** Compares two UUIDs. */
  11141. bool operator== (const Uuid& other) const;
  11142. /** Compares two UUIDs. */
  11143. bool operator!= (const Uuid& other) const;
  11144. /** Returns a stringified version of this UUID.
  11145. A Uuid object can later be reconstructed from this string using operator= or
  11146. the constructor that takes a string parameter.
  11147. @returns a 32 character hex string.
  11148. */
  11149. const String toString() const;
  11150. /** Creates an ID from an encoded string version.
  11151. @see toString
  11152. */
  11153. Uuid (const String& uuidString);
  11154. /** Copies from a stringified UUID.
  11155. The string passed in should be one that was created with the toString() method.
  11156. */
  11157. Uuid& operator= (const String& uuidString);
  11158. /** Returns a pointer to the internal binary representation of the ID.
  11159. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  11160. the constructor or operator= method that takes an array of uint8s.
  11161. */
  11162. const uint8* getRawData() const throw() { return value.asBytes; }
  11163. /** Creates a UUID from a 16-byte array.
  11164. @see getRawData
  11165. */
  11166. Uuid (const uint8* const rawData);
  11167. /** Sets this UUID from 16-bytes of raw data. */
  11168. Uuid& operator= (const uint8* const rawData);
  11169. juce_UseDebuggingNewOperator
  11170. private:
  11171. union
  11172. {
  11173. uint8 asBytes [16];
  11174. int asInt[4];
  11175. int64 asInt64[2];
  11176. } value;
  11177. };
  11178. #endif // __JUCE_UUID_JUCEHEADER__
  11179. /*** End of inlined file: juce_Uuid.h ***/
  11180. #endif
  11181. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11182. /*** Start of inlined file: juce_BlowFish.h ***/
  11183. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11184. #define __JUCE_BLOWFISH_JUCEHEADER__
  11185. /**
  11186. BlowFish encryption class.
  11187. */
  11188. class JUCE_API BlowFish
  11189. {
  11190. public:
  11191. /** Creates an object that can encode/decode based on the specified key.
  11192. The key data can be up to 72 bytes long.
  11193. */
  11194. BlowFish (const void* keyData, int keyBytes);
  11195. /** Creates a copy of another blowfish object. */
  11196. BlowFish (const BlowFish& other);
  11197. /** Copies another blowfish object. */
  11198. BlowFish& operator= (const BlowFish& other);
  11199. /** Destructor. */
  11200. ~BlowFish();
  11201. /** Encrypts a pair of 32-bit integers. */
  11202. void encrypt (uint32& data1, uint32& data2) const throw();
  11203. /** Decrypts a pair of 32-bit integers. */
  11204. void decrypt (uint32& data1, uint32& data2) const throw();
  11205. juce_UseDebuggingNewOperator
  11206. private:
  11207. uint32 p[18];
  11208. HeapBlock <uint32> s[4];
  11209. uint32 F (uint32 x) const throw();
  11210. };
  11211. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  11212. /*** End of inlined file: juce_BlowFish.h ***/
  11213. #endif
  11214. #ifndef __JUCE_MD5_JUCEHEADER__
  11215. /*** Start of inlined file: juce_MD5.h ***/
  11216. #ifndef __JUCE_MD5_JUCEHEADER__
  11217. #define __JUCE_MD5_JUCEHEADER__
  11218. /**
  11219. MD5 checksum class.
  11220. Create one of these with a block of source data or a string, and it calculates the
  11221. MD5 checksum of that data.
  11222. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  11223. */
  11224. class JUCE_API MD5
  11225. {
  11226. public:
  11227. /** Creates a null MD5 object. */
  11228. MD5();
  11229. /** Creates a copy of another MD5. */
  11230. MD5 (const MD5& other);
  11231. /** Copies another MD5. */
  11232. MD5& operator= (const MD5& other);
  11233. /** Creates a checksum for a block of binary data. */
  11234. explicit MD5 (const MemoryBlock& data);
  11235. /** Creates a checksum for a block of binary data. */
  11236. MD5 (const void* data, const size_t numBytes);
  11237. /** Creates a checksum for a string.
  11238. Note that this operates on the string as a block of unicode characters, so the
  11239. result you get will differ from the value you'd get if the string was treated
  11240. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  11241. of this method with a checksum created by a different framework, which may have
  11242. used a different encoding.
  11243. */
  11244. explicit MD5 (const String& text);
  11245. /** Creates a checksum for the input from a stream.
  11246. This will read up to the given number of bytes from the stream, and produce the
  11247. checksum of that. If the number of bytes to read is negative, it'll read
  11248. until the stream is exhausted.
  11249. */
  11250. MD5 (InputStream& input, int64 numBytesToRead = -1);
  11251. /** Creates a checksum for a file. */
  11252. explicit MD5 (const File& file);
  11253. /** Destructor. */
  11254. ~MD5();
  11255. /** Returns the checksum as a 16-byte block of data. */
  11256. const MemoryBlock getRawChecksumData() const;
  11257. /** Returns the checksum as a 32-digit hex string. */
  11258. const String toHexString() const;
  11259. /** Compares this to another MD5. */
  11260. bool operator== (const MD5& other) const;
  11261. /** Compares this to another MD5. */
  11262. bool operator!= (const MD5& other) const;
  11263. juce_UseDebuggingNewOperator
  11264. private:
  11265. uint8 result [16];
  11266. struct ProcessContext
  11267. {
  11268. uint8 buffer [64];
  11269. uint32 state [4];
  11270. uint32 count [2];
  11271. ProcessContext();
  11272. void processBlock (const void* data, size_t dataSize);
  11273. void transform (const void* buffer);
  11274. void finish (void* const result);
  11275. };
  11276. void processStream (InputStream& input, int64 numBytesToRead);
  11277. };
  11278. #endif // __JUCE_MD5_JUCEHEADER__
  11279. /*** End of inlined file: juce_MD5.h ***/
  11280. #endif
  11281. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11282. /*** Start of inlined file: juce_Primes.h ***/
  11283. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11284. #define __JUCE_PRIMES_JUCEHEADER__
  11285. /**
  11286. Prime number creation class.
  11287. This class contains static methods for generating and testing prime numbers.
  11288. @see BigInteger
  11289. */
  11290. class JUCE_API Primes
  11291. {
  11292. public:
  11293. /** Creates a random prime number with a given bit-length.
  11294. The certainty parameter specifies how many iterations to use when testing
  11295. for primality. A safe value might be anything over about 20-30.
  11296. The randomSeeds parameter lets you optionally pass it a set of values with
  11297. which to seed the random number generation, improving the security of the
  11298. keys generated.
  11299. */
  11300. static const BigInteger createProbablePrime (int bitLength,
  11301. int certainty,
  11302. const int* randomSeeds = 0,
  11303. int numRandomSeeds = 0);
  11304. /** Tests a number to see if it's prime.
  11305. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  11306. whether the number is prime.
  11307. The certainty parameter specifies how many iterations to use when testing - a
  11308. safe value might be anything over about 20-30.
  11309. */
  11310. static bool isProbablyPrime (const BigInteger& number, int certainty);
  11311. private:
  11312. Primes();
  11313. Primes (const Primes&);
  11314. Primes& operator= (const Primes&);
  11315. };
  11316. #endif // __JUCE_PRIMES_JUCEHEADER__
  11317. /*** End of inlined file: juce_Primes.h ***/
  11318. #endif
  11319. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11320. /*** Start of inlined file: juce_RSAKey.h ***/
  11321. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11322. #define __JUCE_RSAKEY_JUCEHEADER__
  11323. /**
  11324. RSA public/private key-pair encryption class.
  11325. An object of this type makes up one half of a public/private RSA key pair. Use the
  11326. createKeyPair() method to create a matching pair for encoding/decoding.
  11327. */
  11328. class JUCE_API RSAKey
  11329. {
  11330. public:
  11331. /** Creates a null key object.
  11332. Initialise a pair of objects for use with the createKeyPair() method.
  11333. */
  11334. RSAKey();
  11335. /** Loads a key from an encoded string representation.
  11336. This reloads a key from a string created by the toString() method.
  11337. */
  11338. explicit RSAKey (const String& stringRepresentation);
  11339. /** Destructor. */
  11340. ~RSAKey();
  11341. /** Turns the key into a string representation.
  11342. This can be reloaded using the constructor that takes a string.
  11343. */
  11344. const String toString() const;
  11345. /** Encodes or decodes a value.
  11346. Call this on the public key object to encode some data, then use the matching
  11347. private key object to decode it.
  11348. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  11349. initialised correctly.
  11350. NOTE: This method dumbly applies this key to this data. If you encode some data
  11351. and then try to decode it with a key that doesn't match, this method will still
  11352. happily do its job and return true, but the result won't be what you were expecting.
  11353. It's your responsibility to check that the result is what you wanted.
  11354. */
  11355. bool applyToValue (BigInteger& value) const;
  11356. /** Creates a public/private key-pair.
  11357. Each key will perform one-way encryption that can only be reversed by
  11358. using the other key.
  11359. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  11360. sizes are more secure, but this method will take longer to execute.
  11361. The randomSeeds parameter lets you optionally pass it a set of values with
  11362. which to seed the random number generation, improving the security of the
  11363. keys generated.
  11364. */
  11365. static void createKeyPair (RSAKey& publicKey,
  11366. RSAKey& privateKey,
  11367. int numBits,
  11368. const int* randomSeeds = 0,
  11369. int numRandomSeeds = 0);
  11370. juce_UseDebuggingNewOperator
  11371. protected:
  11372. BigInteger part1, part2;
  11373. };
  11374. #endif // __JUCE_RSAKEY_JUCEHEADER__
  11375. /*** End of inlined file: juce_RSAKey.h ***/
  11376. #endif
  11377. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11378. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  11379. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11380. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11381. /**
  11382. Searches through a the files in a directory, returning each file that is found.
  11383. A DirectoryIterator will search through a directory and its subdirectories using
  11384. a wildcard filepattern match.
  11385. If you may be finding a large number of files, this is better than
  11386. using File::findChildFiles() because it doesn't block while it finds them
  11387. all, and this is more memory-efficient.
  11388. It can also guess how far it's got using a wildly inaccurate algorithm.
  11389. */
  11390. class JUCE_API DirectoryIterator
  11391. {
  11392. public:
  11393. /** Creates a DirectoryIterator for a given directory.
  11394. After creating one of these, call its next() method to get the
  11395. first file - e.g. @code
  11396. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  11397. while (iter.next())
  11398. {
  11399. File theFileItFound (iter.getFile());
  11400. ... etc
  11401. }
  11402. @endcode
  11403. @param directory the directory to search in
  11404. @param isRecursive whether all the subdirectories should also be searched
  11405. @param wildCard the file pattern to match
  11406. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  11407. whether to look for files, directories, or both.
  11408. */
  11409. DirectoryIterator (const File& directory,
  11410. bool isRecursive,
  11411. const String& wildCard = "*",
  11412. int whatToLookFor = File::findFiles);
  11413. /** Destructor. */
  11414. ~DirectoryIterator();
  11415. /** Moves the iterator along to the next file.
  11416. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11417. false if there are no more matching files.
  11418. */
  11419. bool next();
  11420. /** Moves the iterator along to the next file, and returns various properties of that file.
  11421. If you need to find out details about the file, it's more efficient to call this method than
  11422. to call the normal next() method and then find out the details afterwards.
  11423. All the parameters are optional, so pass null pointers for any items that you're not
  11424. interested in.
  11425. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11426. false if there are no more matching files. If it returns false, then none of the
  11427. parameters will be filled-in.
  11428. */
  11429. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  11430. Time* modTime, Time* creationTime, bool* isReadOnly);
  11431. /** Returns the file that the iterator is currently pointing at.
  11432. The result of this call is only valid after a call to next() has returned true.
  11433. */
  11434. const File getFile() const;
  11435. /** Returns a guess of how far through the search the iterator has got.
  11436. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  11437. very accurate.
  11438. */
  11439. float getEstimatedProgress() const;
  11440. juce_UseDebuggingNewOperator
  11441. private:
  11442. friend class File;
  11443. class NativeIterator
  11444. {
  11445. public:
  11446. NativeIterator (const File& directory, const String& wildCard);
  11447. ~NativeIterator();
  11448. bool next (String& filenameFound,
  11449. bool* isDirectory, bool* isHidden, int64* fileSize,
  11450. Time* modTime, Time* creationTime, bool* isReadOnly);
  11451. class Pimpl;
  11452. juce_UseDebuggingNewOperator
  11453. private:
  11454. friend class DirectoryIterator;
  11455. friend class ScopedPointer<Pimpl>;
  11456. ScopedPointer<Pimpl> pimpl;
  11457. NativeIterator (const NativeIterator&);
  11458. NativeIterator& operator= (const NativeIterator&);
  11459. };
  11460. friend class ScopedPointer<NativeIterator::Pimpl>;
  11461. NativeIterator fileFinder;
  11462. String wildCard, path;
  11463. int index;
  11464. mutable int totalNumFiles;
  11465. const int whatToLookFor;
  11466. const bool isRecursive;
  11467. ScopedPointer <DirectoryIterator> subIterator;
  11468. File currentFile;
  11469. DirectoryIterator (const DirectoryIterator&);
  11470. DirectoryIterator& operator= (const DirectoryIterator&);
  11471. };
  11472. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11473. /*** End of inlined file: juce_DirectoryIterator.h ***/
  11474. #endif
  11475. #ifndef __JUCE_FILE_JUCEHEADER__
  11476. #endif
  11477. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11478. /*** Start of inlined file: juce_FileInputStream.h ***/
  11479. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11480. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11481. /**
  11482. An input stream that reads from a local file.
  11483. @see InputStream, FileOutputStream, File::createInputStream
  11484. */
  11485. class JUCE_API FileInputStream : public InputStream
  11486. {
  11487. public:
  11488. /** Creates a FileInputStream.
  11489. @param fileToRead the file to read from - if the file can't be accessed for some
  11490. reason, then the stream will just contain no data
  11491. */
  11492. explicit FileInputStream (const File& fileToRead);
  11493. /** Destructor. */
  11494. ~FileInputStream();
  11495. const File& getFile() const throw() { return file; }
  11496. int64 getTotalLength();
  11497. int read (void* destBuffer, int maxBytesToRead);
  11498. bool isExhausted();
  11499. int64 getPosition();
  11500. bool setPosition (int64 pos);
  11501. juce_UseDebuggingNewOperator
  11502. private:
  11503. File file;
  11504. void* fileHandle;
  11505. int64 currentPosition, totalSize;
  11506. bool needToSeek;
  11507. FileInputStream (const FileInputStream&);
  11508. FileInputStream& operator= (const FileInputStream&);
  11509. };
  11510. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11511. /*** End of inlined file: juce_FileInputStream.h ***/
  11512. #endif
  11513. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11514. /*** Start of inlined file: juce_FileOutputStream.h ***/
  11515. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11516. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11517. /**
  11518. An output stream that writes into a local file.
  11519. @see OutputStream, FileInputStream, File::createOutputStream
  11520. */
  11521. class JUCE_API FileOutputStream : public OutputStream
  11522. {
  11523. public:
  11524. /** Creates a FileOutputStream.
  11525. If the file doesn't exist, it will first be created. If the file can't be
  11526. created or opened, the failedToOpen() method will return
  11527. true.
  11528. If the file already exists when opened, the stream's write-postion will
  11529. be set to the end of the file. To overwrite an existing file,
  11530. use File::deleteFile() before opening the stream, or use setPosition(0)
  11531. after it's opened (although this won't truncate the file).
  11532. It's better to use File::createOutputStream() to create one of these, rather
  11533. than using the class directly.
  11534. @see TemporaryFile
  11535. */
  11536. FileOutputStream (const File& fileToWriteTo,
  11537. int bufferSizeToUse = 16384);
  11538. /** Destructor. */
  11539. ~FileOutputStream();
  11540. /** Returns the file that this stream is writing to.
  11541. */
  11542. const File& getFile() const { return file; }
  11543. /** Returns true if the stream couldn't be opened for some reason.
  11544. */
  11545. bool failedToOpen() const { return fileHandle == 0; }
  11546. void flush();
  11547. int64 getPosition();
  11548. bool setPosition (int64 pos);
  11549. bool write (const void* data, int numBytes);
  11550. juce_UseDebuggingNewOperator
  11551. private:
  11552. File file;
  11553. void* fileHandle;
  11554. int64 currentPosition;
  11555. int bufferSize, bytesInBuffer;
  11556. HeapBlock <char> buffer;
  11557. void flushInternal();
  11558. int64 getPositionInternal() const;
  11559. FileOutputStream (const FileOutputStream&);
  11560. FileOutputStream& operator= (const FileOutputStream&);
  11561. };
  11562. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11563. /*** End of inlined file: juce_FileOutputStream.h ***/
  11564. #endif
  11565. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11566. /*** Start of inlined file: juce_FileSearchPath.h ***/
  11567. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11568. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  11569. /**
  11570. Encapsulates a set of folders that make up a search path.
  11571. @see File
  11572. */
  11573. class JUCE_API FileSearchPath
  11574. {
  11575. public:
  11576. /** Creates an empty search path. */
  11577. FileSearchPath();
  11578. /** Creates a search path from a string of pathnames.
  11579. The path can be semicolon- or comma-separated, e.g.
  11580. "/foo/bar;/foo/moose;/fish/moose"
  11581. The separate folders are tokenised and added to the search path.
  11582. */
  11583. FileSearchPath (const String& path);
  11584. /** Creates a copy of another search path. */
  11585. FileSearchPath (const FileSearchPath& other);
  11586. /** Destructor. */
  11587. ~FileSearchPath();
  11588. /** Uses a string containing a list of pathnames to re-initialise this list.
  11589. This search path is cleared and the semicolon- or comma-separated folders
  11590. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  11591. */
  11592. FileSearchPath& operator= (const String& path);
  11593. /** Returns the number of folders in this search path.
  11594. @see operator[]
  11595. */
  11596. int getNumPaths() const;
  11597. /** Returns one of the folders in this search path.
  11598. The file returned isn't guaranteed to actually be a valid directory.
  11599. @see getNumPaths
  11600. */
  11601. const File operator[] (int index) const;
  11602. /** Returns the search path as a semicolon-separated list of directories. */
  11603. const String toString() const;
  11604. /** Adds a new directory to the search path.
  11605. The new directory is added to the end of the list if the insertIndex parameter is
  11606. less than zero, otherwise it is inserted at the given index.
  11607. */
  11608. void add (const File& directoryToAdd,
  11609. int insertIndex = -1);
  11610. /** Adds a new directory to the search path if it's not already in there. */
  11611. void addIfNotAlreadyThere (const File& directoryToAdd);
  11612. /** Removes a directory from the search path. */
  11613. void remove (int indexToRemove);
  11614. /** Merges another search path into this one.
  11615. This will remove any duplicate directories.
  11616. */
  11617. void addPath (const FileSearchPath& other);
  11618. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  11619. If the search is intended to be recursive, there's no point having nested folders in the search
  11620. path, because they'll just get searched twice and you'll get duplicate results.
  11621. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  11622. */
  11623. void removeRedundantPaths();
  11624. /** Removes any directories that don't actually exist. */
  11625. void removeNonExistentPaths();
  11626. /** Searches the path for a wildcard.
  11627. This will search all the directories in the search path in order, adding any
  11628. matching files to the results array.
  11629. @param results an array to append the results to
  11630. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  11631. return files, directories, or both.
  11632. @param searchRecursively whether to recursively search the subdirectories too
  11633. @param wildCardPattern a pattern to match against the filenames
  11634. @returns the number of files added to the array
  11635. @see File::findChildFiles
  11636. */
  11637. int findChildFiles (Array<File>& results,
  11638. int whatToLookFor,
  11639. bool searchRecursively,
  11640. const String& wildCardPattern = "*") const;
  11641. /** Finds out whether a file is inside one of the path's directories.
  11642. This will return true if the specified file is a child of one of the
  11643. directories specified by this path. Note that this doesn't actually do any
  11644. searching or check that the files exist - it just looks at the pathnames
  11645. to work out whether the file would be inside a directory.
  11646. @param fileToCheck the file to look for
  11647. @param checkRecursively if true, then this will return true if the file is inside a
  11648. subfolder of one of the path's directories (at any depth). If false
  11649. it will only return true if the file is actually a direct child
  11650. of one of the directories.
  11651. @see File::isAChildOf
  11652. */
  11653. bool isFileInPath (const File& fileToCheck,
  11654. bool checkRecursively) const;
  11655. juce_UseDebuggingNewOperator
  11656. private:
  11657. StringArray directories;
  11658. void init (const String& path);
  11659. };
  11660. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  11661. /*** End of inlined file: juce_FileSearchPath.h ***/
  11662. #endif
  11663. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11664. /*** Start of inlined file: juce_NamedPipe.h ***/
  11665. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11666. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  11667. /**
  11668. A cross-process pipe that can have data written to and read from it.
  11669. Two or more processes can use these for inter-process communication.
  11670. @see InterprocessConnection
  11671. */
  11672. class JUCE_API NamedPipe
  11673. {
  11674. public:
  11675. /** Creates a NamedPipe. */
  11676. NamedPipe();
  11677. /** Destructor. */
  11678. ~NamedPipe();
  11679. /** Tries to open a pipe that already exists.
  11680. Returns true if it succeeds.
  11681. */
  11682. bool openExisting (const String& pipeName);
  11683. /** Tries to create a new pipe.
  11684. Returns true if it succeeds.
  11685. */
  11686. bool createNewPipe (const String& pipeName);
  11687. /** Closes the pipe, if it's open. */
  11688. void close();
  11689. /** True if the pipe is currently open. */
  11690. bool isOpen() const;
  11691. /** Returns the last name that was used to try to open this pipe. */
  11692. const String getName() const;
  11693. /** Reads data from the pipe.
  11694. This will block until another thread has written enough data into the pipe to fill
  11695. the number of bytes specified, or until another thread calls the cancelPendingReads()
  11696. method.
  11697. If the operation fails, it returns -1, otherwise, it will return the number of
  11698. bytes read.
  11699. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  11700. this is a maximum timeout for reading from the pipe.
  11701. */
  11702. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  11703. /** Writes some data to the pipe.
  11704. If the operation fails, it returns -1, otherwise, it will return the number of
  11705. bytes written.
  11706. */
  11707. int write (const void* sourceBuffer, int numBytesToWrite,
  11708. int timeOutMilliseconds = 2000);
  11709. /** If any threads are currently blocked on a read operation, this tells them to abort.
  11710. */
  11711. void cancelPendingReads();
  11712. juce_UseDebuggingNewOperator
  11713. private:
  11714. void* internal;
  11715. String currentPipeName;
  11716. CriticalSection lock;
  11717. NamedPipe (const NamedPipe&);
  11718. NamedPipe& operator= (const NamedPipe&);
  11719. bool openInternal (const String& pipeName, const bool createPipe);
  11720. };
  11721. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  11722. /*** End of inlined file: juce_NamedPipe.h ***/
  11723. #endif
  11724. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11725. /*** Start of inlined file: juce_TemporaryFile.h ***/
  11726. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11727. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  11728. /**
  11729. Manages a temporary file, which will be deleted when this object is deleted.
  11730. This object is intended to be used as a stack based object, using its scope
  11731. to make sure the temporary file isn't left lying around.
  11732. For example:
  11733. @code
  11734. {
  11735. File myTargetFile ("~/myfile.txt");
  11736. // this will choose a file called something like "~/myfile_temp239348.txt"
  11737. // which definitely doesn't exist at the time the constructor is called.
  11738. TemporaryFile temp (myTargetFile);
  11739. // create a stream to the temporary file, and write some data to it...
  11740. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  11741. if (out != 0)
  11742. {
  11743. out->write ( ...etc )
  11744. out->flush();
  11745. out = 0; // (deletes the stream)
  11746. // ..now we've finished writing, this will rename the temp file to
  11747. // make it replace the target file we specified above.
  11748. bool succeeded = temp.overwriteTargetFileWithTemporary();
  11749. }
  11750. // ..and even if something went wrong and our overwrite failed,
  11751. // as the TemporaryFile object goes out of scope here, it'll make sure
  11752. // that the temp file gets deleted.
  11753. }
  11754. @endcode
  11755. @see File, FileOutputStream
  11756. */
  11757. class JUCE_API TemporaryFile
  11758. {
  11759. public:
  11760. enum OptionFlags
  11761. {
  11762. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  11763. i.e. its name should start with a dot. */
  11764. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  11765. the file is unique, they should go in brackets rather
  11766. than just being appended (see File::getNonexistentSibling() )*/
  11767. };
  11768. /** Creates a randomly-named temporary file in the default temp directory.
  11769. @param suffix a file suffix to use for the file
  11770. @param optionFlags a combination of the values listed in the OptionFlags enum
  11771. The file will not be created until you write to it. And remember that when
  11772. this object is deleted, the file will also be deleted!
  11773. */
  11774. TemporaryFile (const String& suffix = String::empty,
  11775. int optionFlags = 0);
  11776. /** Creates a temporary file in the same directory as a specified file.
  11777. This is useful if you have a file that you want to overwrite, but don't
  11778. want to harm the original file if the write operation fails. You can
  11779. use this to create a temporary file next to the target file, then
  11780. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  11781. to replace the target file with the one you've just written.
  11782. This class won't create any files until you actually write to them. And remember
  11783. that when this object is deleted, the temporary file will also be deleted!
  11784. @param targetFile the file that you intend to overwrite - the temporary
  11785. file will be created in the same directory as this
  11786. @param optionFlags a combination of the values listed in the OptionFlags enum
  11787. */
  11788. TemporaryFile (const File& targetFile,
  11789. int optionFlags = 0);
  11790. /** Destructor.
  11791. When this object is deleted it will make sure that its temporary file is
  11792. also deleted! If the operation fails, it'll throw an assertion in debug
  11793. mode.
  11794. */
  11795. ~TemporaryFile();
  11796. /** Returns the temporary file. */
  11797. const File getFile() const { return temporaryFile; }
  11798. /** Returns the target file that was specified in the constructor. */
  11799. const File getTargetFile() const { return targetFile; }
  11800. /** Tries to move the temporary file to overwrite the target file that was
  11801. specified in the constructor.
  11802. If you used the constructor that specified a target file, this will attempt
  11803. to replace that file with the temporary one.
  11804. Before calling this, make sure:
  11805. - that you've actually written to the temporary file
  11806. - that you've closed any open streams that you were using to write to it
  11807. - and that you don't have any streams open to the target file, which would
  11808. prevent it being overwritten
  11809. If the file move succeeds, this returns false, and the temporary file will
  11810. have disappeared. If it fails, the temporary file will probably still exist,
  11811. but will be deleted when this object is destroyed.
  11812. */
  11813. bool overwriteTargetFileWithTemporary() const;
  11814. juce_UseDebuggingNewOperator
  11815. private:
  11816. File temporaryFile, targetFile;
  11817. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  11818. TemporaryFile (const TemporaryFile&);
  11819. TemporaryFile& operator= (const TemporaryFile&);
  11820. };
  11821. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  11822. /*** End of inlined file: juce_TemporaryFile.h ***/
  11823. #endif
  11824. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11825. /*** Start of inlined file: juce_ZipFile.h ***/
  11826. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11827. #define __JUCE_ZIPFILE_JUCEHEADER__
  11828. /*** Start of inlined file: juce_InputSource.h ***/
  11829. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  11830. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  11831. /**
  11832. A lightweight object that can create a stream to read some kind of resource.
  11833. This may be used to refer to a file, or some other kind of source, allowing a
  11834. caller to create an input stream that can read from it when required.
  11835. @see FileInputSource
  11836. */
  11837. class JUCE_API InputSource
  11838. {
  11839. public:
  11840. InputSource() throw() {}
  11841. /** Destructor. */
  11842. virtual ~InputSource() {}
  11843. /** Returns a new InputStream to read this item.
  11844. @returns an inputstream that the caller will delete, or 0 if
  11845. the filename isn't found.
  11846. */
  11847. virtual InputStream* createInputStream() = 0;
  11848. /** Returns a new InputStream to read an item, relative.
  11849. @param relatedItemPath the relative pathname of the resource that is required
  11850. @returns an inputstream that the caller will delete, or 0 if
  11851. the item isn't found.
  11852. */
  11853. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  11854. /** Returns a hash code that uniquely represents this item.
  11855. */
  11856. virtual int64 hashCode() const = 0;
  11857. juce_UseDebuggingNewOperator
  11858. };
  11859. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  11860. /*** End of inlined file: juce_InputSource.h ***/
  11861. /**
  11862. Decodes a ZIP file from a stream.
  11863. This can enumerate the items in a ZIP file and can create suitable stream objects
  11864. to read each one.
  11865. */
  11866. class JUCE_API ZipFile
  11867. {
  11868. public:
  11869. /** Creates a ZipFile for a given stream.
  11870. @param inputStream the stream to read from
  11871. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  11872. will be deleted when this ZipFile object is deleted
  11873. */
  11874. ZipFile (InputStream* inputStream,
  11875. bool deleteStreamWhenDestroyed) throw();
  11876. /** Creates a ZipFile based for a file. */
  11877. ZipFile (const File& file);
  11878. /** Creates a ZipFile for an input source.
  11879. The inputSource object will be owned by the zip file, which will delete
  11880. it later when not needed.
  11881. */
  11882. ZipFile (InputSource* inputSource);
  11883. /** Destructor. */
  11884. ~ZipFile() throw();
  11885. /**
  11886. Contains information about one of the entries in a ZipFile.
  11887. @see ZipFile::getEntry
  11888. */
  11889. struct ZipEntry
  11890. {
  11891. /** The name of the file, which may also include a partial pathname. */
  11892. String filename;
  11893. /** The file's original size. */
  11894. unsigned int uncompressedSize;
  11895. /** The last time the file was modified. */
  11896. Time fileTime;
  11897. };
  11898. /** Returns the number of items in the zip file. */
  11899. int getNumEntries() const throw();
  11900. /** Returns a structure that describes one of the entries in the zip file.
  11901. This may return zero if the index is out of range.
  11902. @see ZipFile::ZipEntry
  11903. */
  11904. const ZipEntry* getEntry (int index) const throw();
  11905. /** Returns the index of the first entry with a given filename.
  11906. This uses a case-sensitive comparison to look for a filename in the
  11907. list of entries. It might return -1 if no match is found.
  11908. @see ZipFile::ZipEntry
  11909. */
  11910. int getIndexOfFileName (const String& fileName) const throw();
  11911. /** Returns a structure that describes one of the entries in the zip file.
  11912. This uses a case-sensitive comparison to look for a filename in the
  11913. list of entries. It might return 0 if no match is found.
  11914. @see ZipFile::ZipEntry
  11915. */
  11916. const ZipEntry* getEntry (const String& fileName) const throw();
  11917. /** Sorts the list of entries, based on the filename.
  11918. */
  11919. void sortEntriesByFilename();
  11920. /** Creates a stream that can read from one of the zip file's entries.
  11921. The stream that is returned must be deleted by the caller (and
  11922. zero might be returned if a stream can't be opened for some reason).
  11923. The stream must not be used after the ZipFile object that created
  11924. has been deleted.
  11925. */
  11926. InputStream* createStreamForEntry (int index);
  11927. /** Uncompresses all of the files in the zip file.
  11928. This will expand all the entires into a target directory. The relative
  11929. paths of the entries are used.
  11930. @param targetDirectory the root folder to uncompress to
  11931. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  11932. */
  11933. void uncompressTo (const File& targetDirectory,
  11934. bool shouldOverwriteFiles = true);
  11935. juce_UseDebuggingNewOperator
  11936. private:
  11937. class ZipInputStream;
  11938. class ZipFilenameComparator;
  11939. class ZipEntryInfo;
  11940. friend class ZipInputStream;
  11941. friend class ZipFilenameComparator;
  11942. friend class ZipEntryInfo;
  11943. OwnedArray <ZipEntryInfo> entries;
  11944. CriticalSection lock;
  11945. InputStream* inputStream;
  11946. ScopedPointer <InputStream> streamToDelete;
  11947. ScopedPointer <InputSource> inputSource;
  11948. #if JUCE_DEBUG
  11949. int numOpenStreams;
  11950. #endif
  11951. void init();
  11952. int findEndOfZipEntryTable (InputStream* in, int& numEntries);
  11953. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  11954. ZipFile (const ZipFile&);
  11955. ZipFile& operator= (const ZipFile&);
  11956. };
  11957. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  11958. /*** End of inlined file: juce_ZipFile.h ***/
  11959. #endif
  11960. #ifndef __JUCE_SOCKET_JUCEHEADER__
  11961. /*** Start of inlined file: juce_Socket.h ***/
  11962. #ifndef __JUCE_SOCKET_JUCEHEADER__
  11963. #define __JUCE_SOCKET_JUCEHEADER__
  11964. /**
  11965. A wrapper for a streaming (TCP) socket.
  11966. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  11967. sockets, you could also try the InterprocessConnection class.
  11968. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  11969. */
  11970. class JUCE_API StreamingSocket
  11971. {
  11972. public:
  11973. /** Creates an uninitialised socket.
  11974. To connect it, use the connect() method, after which you can read() or write()
  11975. to it.
  11976. To wait for other sockets to connect to this one, the createListener() method
  11977. enters "listener" mode, and can be used to spawn new sockets for each connection
  11978. that comes along.
  11979. */
  11980. StreamingSocket();
  11981. /** Destructor. */
  11982. ~StreamingSocket();
  11983. /** Binds the socket to the specified local port.
  11984. @returns true on success; false may indicate that another socket is already bound
  11985. on the same port
  11986. */
  11987. bool bindToPort (int localPortNumber);
  11988. /** Tries to connect the socket to hostname:port.
  11989. If timeOutMillisecs is 0, then this method will block until the operating system
  11990. rejects the connection (which could take a long time).
  11991. @returns true if it succeeds.
  11992. @see isConnected
  11993. */
  11994. bool connect (const String& remoteHostname,
  11995. int remotePortNumber,
  11996. int timeOutMillisecs = 3000);
  11997. /** True if the socket is currently connected. */
  11998. bool isConnected() const throw() { return connected; }
  11999. /** Closes the connection. */
  12000. void close();
  12001. /** Returns the name of the currently connected host. */
  12002. const String& getHostName() const throw() { return hostName; }
  12003. /** Returns the port number that's currently open. */
  12004. int getPort() const throw() { return portNumber; }
  12005. /** True if the socket is connected to this machine rather than over the network. */
  12006. bool isLocal() const throw();
  12007. /** Waits until the socket is ready for reading or writing.
  12008. If readyForReading is true, it will wait until the socket is ready for
  12009. reading; if false, it will wait until it's ready for writing.
  12010. If the timeout is < 0, it will wait forever, or else will give up after
  12011. the specified time.
  12012. If the socket is ready on return, this returns 1. If it times-out before
  12013. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12014. */
  12015. int waitUntilReady (bool readyForReading,
  12016. int timeoutMsecs) const;
  12017. /** Reads bytes from the socket.
  12018. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12019. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12020. flag is false, the method will return as much data as is currently available
  12021. without blocking.
  12022. @returns the number of bytes read, or -1 if there was an error.
  12023. @see waitUntilReady
  12024. */
  12025. int read (void* destBuffer, int maxBytesToRead,
  12026. bool blockUntilSpecifiedAmountHasArrived);
  12027. /** Writes bytes to the socket from a buffer.
  12028. Note that this method will block unless you have checked the socket is ready
  12029. for writing before calling it (see the waitUntilReady() method).
  12030. @returns the number of bytes written, or -1 if there was an error.
  12031. */
  12032. int write (const void* sourceBuffer, int numBytesToWrite);
  12033. /** Puts this socket into "listener" mode.
  12034. When in this mode, your thread can call waitForNextConnection() repeatedly,
  12035. which will spawn new sockets for each new connection, so that these can
  12036. be handled in parallel by other threads.
  12037. @param portNumber the port number to listen on
  12038. @param localHostName the interface address to listen on - pass an empty
  12039. string to listen on all addresses
  12040. @returns true if it manages to open the socket successfully.
  12041. @see waitForNextConnection
  12042. */
  12043. bool createListener (int portNumber, const String& localHostName = String::empty);
  12044. /** When in "listener" mode, this waits for a connection and spawns it as a new
  12045. socket.
  12046. The object that gets returned will be owned by the caller.
  12047. This method can only be called after using createListener().
  12048. @see createListener
  12049. */
  12050. StreamingSocket* waitForNextConnection() const;
  12051. juce_UseDebuggingNewOperator
  12052. private:
  12053. String hostName;
  12054. int volatile portNumber, handle;
  12055. bool connected, isListener;
  12056. StreamingSocket (const String& hostname, int portNumber, int handle);
  12057. StreamingSocket (const StreamingSocket&);
  12058. StreamingSocket& operator= (const StreamingSocket&);
  12059. };
  12060. /**
  12061. A wrapper for a datagram (UDP) socket.
  12062. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12063. sockets, you could also try the InterprocessConnection class.
  12064. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  12065. */
  12066. class JUCE_API DatagramSocket
  12067. {
  12068. public:
  12069. /**
  12070. Creates an (uninitialised) datagram socket.
  12071. The localPortNumber is the port on which to bind this socket. If this value is 0,
  12072. the port number is assigned by the operating system.
  12073. To use the socket for sending, call the connect() method. This will not immediately
  12074. make a connection, but will save the destination you've provided. After this, you can
  12075. call read() or write().
  12076. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  12077. (may require extra privileges on linux)
  12078. To wait for other sockets to connect to this one, call waitForNextConnection().
  12079. */
  12080. DatagramSocket (int localPortNumber,
  12081. bool enableBroadcasting = false);
  12082. /** Destructor. */
  12083. ~DatagramSocket();
  12084. /** Binds the socket to the specified local port.
  12085. @returns true on success; false may indicate that another socket is already bound
  12086. on the same port
  12087. */
  12088. bool bindToPort (int localPortNumber);
  12089. /** Tries to connect the socket to hostname:port.
  12090. If timeOutMillisecs is 0, then this method will block until the operating system
  12091. rejects the connection (which could take a long time).
  12092. @returns true if it succeeds.
  12093. @see isConnected
  12094. */
  12095. bool connect (const String& remoteHostname,
  12096. int remotePortNumber,
  12097. int timeOutMillisecs = 3000);
  12098. /** True if the socket is currently connected. */
  12099. bool isConnected() const throw() { return connected; }
  12100. /** Closes the connection. */
  12101. void close();
  12102. /** Returns the name of the currently connected host. */
  12103. const String& getHostName() const throw() { return hostName; }
  12104. /** Returns the port number that's currently open. */
  12105. int getPort() const throw() { return portNumber; }
  12106. /** True if the socket is connected to this machine rather than over the network. */
  12107. bool isLocal() const throw();
  12108. /** Waits until the socket is ready for reading or writing.
  12109. If readyForReading is true, it will wait until the socket is ready for
  12110. reading; if false, it will wait until it's ready for writing.
  12111. If the timeout is < 0, it will wait forever, or else will give up after
  12112. the specified time.
  12113. If the socket is ready on return, this returns 1. If it times-out before
  12114. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12115. */
  12116. int waitUntilReady (bool readyForReading,
  12117. int timeoutMsecs) const;
  12118. /** Reads bytes from the socket.
  12119. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12120. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12121. flag is false, the method will return as much data as is currently available
  12122. without blocking.
  12123. @returns the number of bytes read, or -1 if there was an error.
  12124. @see waitUntilReady
  12125. */
  12126. int read (void* destBuffer, int maxBytesToRead,
  12127. bool blockUntilSpecifiedAmountHasArrived);
  12128. /** Writes bytes to the socket from a buffer.
  12129. Note that this method will block unless you have checked the socket is ready
  12130. for writing before calling it (see the waitUntilReady() method).
  12131. @returns the number of bytes written, or -1 if there was an error.
  12132. */
  12133. int write (const void* sourceBuffer, int numBytesToWrite);
  12134. /** This waits for incoming data to be sent, and returns a socket that can be used
  12135. to read it.
  12136. The object that gets returned is owned by the caller, and can't be used for
  12137. sending, but can be used to read the data.
  12138. */
  12139. DatagramSocket* waitForNextConnection() const;
  12140. juce_UseDebuggingNewOperator
  12141. private:
  12142. String hostName;
  12143. int volatile portNumber, handle;
  12144. bool connected, allowBroadcast;
  12145. void* serverAddress;
  12146. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  12147. DatagramSocket (const DatagramSocket&);
  12148. DatagramSocket& operator= (const DatagramSocket&);
  12149. };
  12150. #endif // __JUCE_SOCKET_JUCEHEADER__
  12151. /*** End of inlined file: juce_Socket.h ***/
  12152. #endif
  12153. #ifndef __JUCE_URL_JUCEHEADER__
  12154. /*** Start of inlined file: juce_URL.h ***/
  12155. #ifndef __JUCE_URL_JUCEHEADER__
  12156. #define __JUCE_URL_JUCEHEADER__
  12157. /**
  12158. Represents a URL and has a bunch of useful functions to manipulate it.
  12159. This class can be used to launch URLs in browsers, and also to create
  12160. InputStreams that can read from remote http or ftp sources.
  12161. */
  12162. class JUCE_API URL
  12163. {
  12164. public:
  12165. /** Creates an empty URL. */
  12166. URL();
  12167. /** Creates a URL from a string. */
  12168. URL (const String& url);
  12169. /** Creates a copy of another URL. */
  12170. URL (const URL& other);
  12171. /** Destructor. */
  12172. ~URL();
  12173. /** Copies this URL from another one. */
  12174. URL& operator= (const URL& other);
  12175. /** Returns a string version of the URL.
  12176. If includeGetParameters is true and any parameters have been set with the
  12177. withParameter() method, then the string will have these appended on the
  12178. end and url-encoded.
  12179. */
  12180. const String toString (bool includeGetParameters) const;
  12181. /** True if it seems to be valid. */
  12182. bool isWellFormed() const;
  12183. /** Returns just the domain part of the URL.
  12184. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  12185. */
  12186. const String getDomain() const;
  12187. /** Returns the path part of the URL.
  12188. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  12189. */
  12190. const String getSubPath() const;
  12191. /** Returns the scheme of the URL.
  12192. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  12193. include the colon).
  12194. */
  12195. const String getScheme() const;
  12196. /** Returns a new version of this URL that uses a different sub-path.
  12197. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  12198. "bar", it'll return "http://www.xyz.com/bar?x=1".
  12199. */
  12200. const URL withNewSubPath (const String& newPath) const;
  12201. /** Returns a copy of this URL, with a GET parameter added to the end.
  12202. Any control characters in the value will be encoded.
  12203. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  12204. would produce a new url whose toString(true) method would return
  12205. "www.fish.com?amount=some+fish".
  12206. */
  12207. const URL withParameter (const String& parameterName,
  12208. const String& parameterValue) const;
  12209. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  12210. When performing a POST where one of your parameters is a binary file, this
  12211. lets you specify the file.
  12212. Note that the filename is stored, but the file itself won't actually be read
  12213. until this URL is later used to create a network input stream.
  12214. */
  12215. const URL withFileToUpload (const String& parameterName,
  12216. const File& fileToUpload,
  12217. const String& mimeType) const;
  12218. /** Returns a set of all the parameters encoded into the url.
  12219. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  12220. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  12221. The values returned will have been cleaned up to remove any escape characters.
  12222. @see getNamedParameter, withParameter
  12223. */
  12224. const StringPairArray& getParameters() const;
  12225. /** Returns the set of files that should be uploaded as part of a POST operation.
  12226. This is the set of files that were added to the URL with the withFileToUpload()
  12227. method.
  12228. */
  12229. const StringPairArray& getFilesToUpload() const;
  12230. /** Returns the set of mime types associated with each of the upload files.
  12231. */
  12232. const StringPairArray& getMimeTypesOfUploadFiles() const;
  12233. /** Returns a copy of this URL, with a block of data to send as the POST data.
  12234. If you're setting the POST data, be careful not to have any parameters set
  12235. as well, otherwise it'll all get thrown in together, and might not have the
  12236. desired effect.
  12237. If the URL already contains some POST data, this will replace it, rather
  12238. than being appended to it.
  12239. This data will only be used if you specify a post operation when you call
  12240. createInputStream().
  12241. */
  12242. const URL withPOSTData (const String& postData) const;
  12243. /** Returns the data that was set using withPOSTData().
  12244. */
  12245. const String getPostData() const { return postData; }
  12246. /** Tries to launch the system's default browser to open the URL.
  12247. Returns true if this seems to have worked.
  12248. */
  12249. bool launchInDefaultBrowser() const;
  12250. /** Takes a guess as to whether a string might be a valid website address.
  12251. This isn't foolproof!
  12252. */
  12253. static bool isProbablyAWebsiteURL (const String& possibleURL);
  12254. /** Takes a guess as to whether a string might be a valid email address.
  12255. This isn't foolproof!
  12256. */
  12257. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  12258. /** This callback function can be used by the createInputStream() method.
  12259. It allows your app to receive progress updates during a lengthy POST operation. If you
  12260. want to continue the operation, this should return true, or false to abort.
  12261. */
  12262. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  12263. /** Attempts to open a stream that can read from this URL.
  12264. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  12265. the paramters, otherwise it'll encode them into the
  12266. URL and do a 'GET'.
  12267. @param progressCallback if this is non-zero, it lets you supply a callback function
  12268. to keep track of the operation's progress. This can be useful
  12269. for lengthy POST operations, so that you can provide user feedback.
  12270. @param progressCallbackContext if a callback is specified, this value will be passed to
  12271. the function
  12272. @param extraHeaders if not empty, this string is appended onto the headers that
  12273. are used for the request. It must therefore be a valid set of HTML
  12274. header directives, separated by newlines.
  12275. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  12276. a negative number, it will be infinite. Otherwise it specifies a
  12277. time in milliseconds.
  12278. */
  12279. InputStream* createInputStream (bool usePostCommand,
  12280. OpenStreamProgressCallback* progressCallback = 0,
  12281. void* progressCallbackContext = 0,
  12282. const String& extraHeaders = String::empty,
  12283. int connectionTimeOutMs = 0) const;
  12284. /** Tries to download the entire contents of this URL into a binary data block.
  12285. If it succeeds, this will return true and append the data it read onto the end
  12286. of the memory block.
  12287. @param destData the memory block to append the new data to
  12288. @param usePostCommand whether to use a POST command to get the data (uses
  12289. a GET command if this is false)
  12290. @see readEntireTextStream, readEntireXmlStream
  12291. */
  12292. bool readEntireBinaryStream (MemoryBlock& destData,
  12293. bool usePostCommand = false) const;
  12294. /** Tries to download the entire contents of this URL as a string.
  12295. If it fails, this will return an empty string, otherwise it will return the
  12296. contents of the downloaded file. If you need to distinguish between a read
  12297. operation that fails and one that returns an empty string, you'll need to use
  12298. a different method, such as readEntireBinaryStream().
  12299. @param usePostCommand whether to use a POST command to get the data (uses
  12300. a GET command if this is false)
  12301. @see readEntireBinaryStream, readEntireXmlStream
  12302. */
  12303. const String readEntireTextStream (bool usePostCommand = false) const;
  12304. /** Tries to download the entire contents of this URL and parse it as XML.
  12305. If it fails, or if the text that it reads can't be parsed as XML, this will
  12306. return 0.
  12307. When it returns a valid XmlElement object, the caller is responsibile for deleting
  12308. this object when no longer needed.
  12309. @param usePostCommand whether to use a POST command to get the data (uses
  12310. a GET command if this is false)
  12311. @see readEntireBinaryStream, readEntireTextStream
  12312. */
  12313. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  12314. /** Adds escape sequences to a string to encode any characters that aren't
  12315. legal in a URL.
  12316. E.g. any spaces will be replaced with "%20".
  12317. This is the opposite of removeEscapeChars().
  12318. If isParameter is true, it means that the string is going to be used
  12319. as a parameter, so it also encodes '$' and ',' (which would otherwise
  12320. be legal in a URL.
  12321. @see removeEscapeChars
  12322. */
  12323. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  12324. bool isParameter);
  12325. /** Replaces any escape character sequences in a string with their original
  12326. character codes.
  12327. E.g. any instances of "%20" will be replaced by a space.
  12328. This is the opposite of addEscapeChars().
  12329. @see addEscapeChars
  12330. */
  12331. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  12332. juce_UseDebuggingNewOperator
  12333. private:
  12334. String url, postData;
  12335. StringPairArray parameters, filesToUpload, mimeTypes;
  12336. };
  12337. #endif // __JUCE_URL_JUCEHEADER__
  12338. /*** End of inlined file: juce_URL.h ***/
  12339. #endif
  12340. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12341. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  12342. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12343. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12344. /** Wraps another input stream, and reads from it using an intermediate buffer
  12345. If you're using an input stream such as a file input stream, and making lots of
  12346. small read accesses to it, it's probably sensible to wrap it in one of these,
  12347. so that the source stream gets accessed in larger chunk sizes, meaning less
  12348. work for the underlying stream.
  12349. */
  12350. class JUCE_API BufferedInputStream : public InputStream
  12351. {
  12352. public:
  12353. /** Creates a BufferedInputStream from an input source.
  12354. @param sourceStream the source stream to read from
  12355. @param bufferSize the size of reservoir to use to buffer the source
  12356. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12357. deleted by this object when it is itself deleted.
  12358. */
  12359. BufferedInputStream (InputStream* sourceStream,
  12360. int bufferSize,
  12361. bool deleteSourceWhenDestroyed);
  12362. /** Destructor.
  12363. This may also delete the source stream, if that option was chosen when the
  12364. buffered stream was created.
  12365. */
  12366. ~BufferedInputStream();
  12367. int64 getTotalLength();
  12368. int64 getPosition();
  12369. bool setPosition (int64 newPosition);
  12370. int read (void* destBuffer, int maxBytesToRead);
  12371. const String readString();
  12372. bool isExhausted();
  12373. juce_UseDebuggingNewOperator
  12374. private:
  12375. InputStream* const source;
  12376. ScopedPointer <InputStream> sourceToDelete;
  12377. int bufferSize;
  12378. int64 position, lastReadPos, bufferStart, bufferOverlap;
  12379. HeapBlock <char> buffer;
  12380. void ensureBuffered();
  12381. BufferedInputStream (const BufferedInputStream&);
  12382. BufferedInputStream& operator= (const BufferedInputStream&);
  12383. };
  12384. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12385. /*** End of inlined file: juce_BufferedInputStream.h ***/
  12386. #endif
  12387. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12388. /*** Start of inlined file: juce_FileInputSource.h ***/
  12389. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12390. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12391. /**
  12392. A type of InputSource that represents a normal file.
  12393. @see InputSource
  12394. */
  12395. class JUCE_API FileInputSource : public InputSource
  12396. {
  12397. public:
  12398. FileInputSource (const File& file);
  12399. ~FileInputSource();
  12400. InputStream* createInputStream();
  12401. InputStream* createInputStreamFor (const String& relatedItemPath);
  12402. int64 hashCode() const;
  12403. juce_UseDebuggingNewOperator
  12404. private:
  12405. const File file;
  12406. FileInputSource (const FileInputSource&);
  12407. FileInputSource& operator= (const FileInputSource&);
  12408. };
  12409. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12410. /*** End of inlined file: juce_FileInputSource.h ***/
  12411. #endif
  12412. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12413. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12414. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12415. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12416. class GZIPCompressorHelper;
  12417. /**
  12418. A stream which uses zlib to compress the data written into it.
  12419. @see GZIPDecompressorInputStream
  12420. */
  12421. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  12422. {
  12423. public:
  12424. /** Creates a compression stream.
  12425. @param destStream the stream into which the compressed data should
  12426. be written
  12427. @param compressionLevel how much to compress the data, between 1 and 9, where
  12428. 1 is the fastest/lowest compression, and 9 is the
  12429. slowest/highest compression. Any value outside this range
  12430. indicates that a default compression level should be used.
  12431. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  12432. this stream is destroyed
  12433. @param noWrap this is used internally by the ZipFile class
  12434. and should be ignored by user applications
  12435. */
  12436. GZIPCompressorOutputStream (OutputStream* destStream,
  12437. int compressionLevel = 0,
  12438. bool deleteDestStreamWhenDestroyed = false,
  12439. bool noWrap = false);
  12440. /** Destructor. */
  12441. ~GZIPCompressorOutputStream();
  12442. void flush();
  12443. int64 getPosition();
  12444. bool setPosition (int64 newPosition);
  12445. bool write (const void* destBuffer, int howMany);
  12446. juce_UseDebuggingNewOperator
  12447. private:
  12448. OutputStream* const destStream;
  12449. ScopedPointer <OutputStream> streamToDelete;
  12450. HeapBlock <uint8> buffer;
  12451. ScopedPointer <GZIPCompressorHelper> helper;
  12452. bool doNextBlock();
  12453. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  12454. GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  12455. };
  12456. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12457. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12458. #endif
  12459. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12460. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12461. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12462. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12463. class GZIPDecompressHelper;
  12464. /**
  12465. This stream will decompress a source-stream using zlib.
  12466. Tip: if you're reading lots of small items from one of these streams, you
  12467. can increase the performance enormously by passing it through a
  12468. BufferedInputStream, so that it has to read larger blocks less often.
  12469. @see GZIPCompressorOutputStream
  12470. */
  12471. class JUCE_API GZIPDecompressorInputStream : public InputStream
  12472. {
  12473. public:
  12474. /** Creates a decompressor stream.
  12475. @param sourceStream the stream to read from
  12476. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  12477. when this object is destroyed
  12478. @param noWrap this is used internally by the ZipFile class
  12479. and should be ignored by user applications
  12480. @param uncompressedStreamLength if the creator knows the length that the
  12481. uncompressed stream will be, then it can supply this
  12482. value, which will be returned by getTotalLength()
  12483. */
  12484. GZIPDecompressorInputStream (InputStream* sourceStream,
  12485. bool deleteSourceWhenDestroyed,
  12486. bool noWrap = false,
  12487. int64 uncompressedStreamLength = -1);
  12488. /** Destructor. */
  12489. ~GZIPDecompressorInputStream();
  12490. int64 getPosition();
  12491. bool setPosition (int64 pos);
  12492. int64 getTotalLength();
  12493. bool isExhausted();
  12494. int read (void* destBuffer, int maxBytesToRead);
  12495. juce_UseDebuggingNewOperator
  12496. private:
  12497. InputStream* const sourceStream;
  12498. ScopedPointer <InputStream> streamToDelete;
  12499. const int64 uncompressedStreamLength;
  12500. const bool noWrap;
  12501. bool isEof;
  12502. int activeBufferSize;
  12503. int64 originalSourcePos, currentPos;
  12504. HeapBlock <uint8> buffer;
  12505. ScopedPointer <GZIPDecompressHelper> helper;
  12506. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  12507. GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  12508. };
  12509. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12510. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12511. #endif
  12512. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12513. #endif
  12514. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  12515. #endif
  12516. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12517. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  12518. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12519. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12520. /**
  12521. Allows a block of data and to be accessed as a stream.
  12522. This can either be used to refer to a shared block of memory, or can make its
  12523. own internal copy of the data when the MemoryInputStream is created.
  12524. */
  12525. class JUCE_API MemoryInputStream : public InputStream
  12526. {
  12527. public:
  12528. /** Creates a MemoryInputStream.
  12529. @param sourceData the block of data to use as the stream's source
  12530. @param sourceDataSize the number of bytes in the source data block
  12531. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  12532. the source data, so this data shouldn't be changed
  12533. for the lifetime of the stream; if this parameter is
  12534. true, the stream will make its own copy of the
  12535. data and use that.
  12536. */
  12537. MemoryInputStream (const void* sourceData,
  12538. size_t sourceDataSize,
  12539. bool keepInternalCopyOfData);
  12540. /** Creates a MemoryInputStream.
  12541. @param data a block of data to use as the stream's source
  12542. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  12543. the source data, so this data shouldn't be changed
  12544. for the lifetime of the stream; if this parameter is
  12545. true, the stream will make its own copy of the
  12546. data and use that.
  12547. */
  12548. MemoryInputStream (const MemoryBlock& data,
  12549. bool keepInternalCopyOfData);
  12550. /** Destructor. */
  12551. ~MemoryInputStream();
  12552. int64 getPosition();
  12553. bool setPosition (int64 pos);
  12554. int64 getTotalLength();
  12555. bool isExhausted();
  12556. int read (void* destBuffer, int maxBytesToRead);
  12557. juce_UseDebuggingNewOperator
  12558. private:
  12559. const char* data;
  12560. size_t dataSize, position;
  12561. MemoryBlock internalCopy;
  12562. MemoryInputStream (const MemoryInputStream&);
  12563. MemoryInputStream& operator= (const MemoryInputStream&);
  12564. };
  12565. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12566. /*** End of inlined file: juce_MemoryInputStream.h ***/
  12567. #endif
  12568. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12569. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  12570. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12571. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12572. /** Writes data to an internal memory buffer, which grows as required.
  12573. The data that was written into the stream can then be accessed later as
  12574. a contiguous block of memory.
  12575. */
  12576. class JUCE_API MemoryOutputStream : public OutputStream
  12577. {
  12578. public:
  12579. /** Creates a memory stream ready for writing into.
  12580. @param initialSize the intial amount of space to allocate for writing into
  12581. @param granularity the increments by which the internal storage will be increased
  12582. @param memoryBlockToWriteTo if this is non-zero, then this block will be used as the
  12583. place that the data gets stored. If it's zero, the stream
  12584. will allocate its own storage internally, which you can
  12585. access using getData() and getDataSize()
  12586. */
  12587. MemoryOutputStream (size_t initialSize = 256,
  12588. size_t granularity = 256,
  12589. MemoryBlock* memoryBlockToWriteTo = 0);
  12590. /** Destructor.
  12591. This will free any data that was written to it.
  12592. */
  12593. ~MemoryOutputStream();
  12594. /** Returns a pointer to the data that has been written to the stream.
  12595. @see getDataSize
  12596. */
  12597. const char* getData() const throw();
  12598. /** Returns the number of bytes of data that have been written to the stream.
  12599. @see getData
  12600. */
  12601. size_t getDataSize() const throw() { return size; }
  12602. /** Resets the stream, clearing any data that has been written to it so far. */
  12603. void reset() throw();
  12604. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  12605. const String toUTF8() const;
  12606. void flush();
  12607. bool write (const void* buffer, int howMany);
  12608. int64 getPosition() { return position; }
  12609. bool setPosition (int64 newPosition);
  12610. juce_UseDebuggingNewOperator
  12611. private:
  12612. MemoryBlock* data;
  12613. ScopedPointer <MemoryBlock> dataToDelete;
  12614. size_t position, size, blockSize;
  12615. MemoryOutputStream (const MemoryOutputStream&);
  12616. MemoryOutputStream& operator= (const MemoryOutputStream&);
  12617. };
  12618. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12619. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  12620. #endif
  12621. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  12622. #endif
  12623. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12624. /*** Start of inlined file: juce_SubregionStream.h ***/
  12625. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12626. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12627. /** Wraps another input stream, and reads from a specific part of it.
  12628. This lets you take a subsection of a stream and present it as an entire
  12629. stream in its own right.
  12630. */
  12631. class JUCE_API SubregionStream : public InputStream
  12632. {
  12633. public:
  12634. /** Creates a SubregionStream from an input source.
  12635. @param sourceStream the source stream to read from
  12636. @param startPositionInSourceStream this is the position in the source stream that
  12637. corresponds to position 0 in this stream
  12638. @param lengthOfSourceStream this specifies the maximum number of bytes
  12639. from the source stream that will be passed through
  12640. by this stream. When the position of this stream
  12641. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  12642. If the length passed in here is greater than the length
  12643. of the source stream (as returned by getTotalLength()),
  12644. then the smaller value will be used.
  12645. Passing a negative value for this parameter means it
  12646. will keep reading until the source's end-of-stream.
  12647. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12648. deleted by this object when it is itself deleted.
  12649. */
  12650. SubregionStream (InputStream* sourceStream,
  12651. int64 startPositionInSourceStream,
  12652. int64 lengthOfSourceStream,
  12653. bool deleteSourceWhenDestroyed);
  12654. /** Destructor.
  12655. This may also delete the source stream, if that option was chosen when the
  12656. buffered stream was created.
  12657. */
  12658. ~SubregionStream();
  12659. int64 getTotalLength();
  12660. int64 getPosition();
  12661. bool setPosition (int64 newPosition);
  12662. int read (void* destBuffer, int maxBytesToRead);
  12663. bool isExhausted();
  12664. juce_UseDebuggingNewOperator
  12665. private:
  12666. InputStream* const source;
  12667. ScopedPointer <InputStream> sourceToDelete;
  12668. const int64 startPositionInSourceStream, lengthOfSourceStream;
  12669. SubregionStream (const SubregionStream&);
  12670. SubregionStream& operator= (const SubregionStream&);
  12671. };
  12672. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12673. /*** End of inlined file: juce_SubregionStream.h ***/
  12674. #endif
  12675. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  12676. #endif
  12677. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12678. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  12679. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12680. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12681. /** Used in the same way as the T(text) macro, this will attempt to translate a
  12682. string into a localised version using the LocalisedStrings class.
  12683. @see LocalisedStrings
  12684. */
  12685. #define TRANS(stringLiteral) \
  12686. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  12687. /**
  12688. Used to convert strings to localised foreign-language versions.
  12689. This is basically a look-up table of strings and their translated equivalents.
  12690. It can be loaded from a text file, so that you can supply a set of localised
  12691. versions of strings that you use in your app.
  12692. To use it in your code, simply call the translate() method on each string that
  12693. might have foreign versions, and if none is found, the method will just return
  12694. the original string.
  12695. The translation file should start with some lines specifying a description of
  12696. the language it contains, and also a list of ISO country codes where it might
  12697. be appropriate to use the file. After that, each line of the file should contain
  12698. a pair of quoted strings with an '=' sign.
  12699. E.g. for a french translation, the file might be:
  12700. @code
  12701. language: French
  12702. countries: fr be mc ch lu
  12703. "hello" = "bonjour"
  12704. "goodbye" = "au revoir"
  12705. @endcode
  12706. If the strings need to contain a quote character, they can use '\"' instead, and
  12707. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  12708. (you can use this to add comments).
  12709. Note that this is a singleton class, so don't create or destroy the object directly.
  12710. There's also a TRANS(text) macro defined to make it easy to use the this.
  12711. E.g. @code
  12712. printSomething (TRANS("hello"));
  12713. @endcode
  12714. This macro is used in the Juce classes themselves, so your application has a chance to
  12715. intercept and translate any internal Juce text strings that might be shown. (You can easily
  12716. get a list of all the messages by searching for the TRANS() macro in the Juce source
  12717. code).
  12718. */
  12719. class JUCE_API LocalisedStrings
  12720. {
  12721. public:
  12722. /** Creates a set of translations from the text of a translation file.
  12723. When you create one of these, you can call setCurrentMappings() to make it
  12724. the set of mappings that the system's using.
  12725. */
  12726. LocalisedStrings (const String& fileContents);
  12727. /** Creates a set of translations from a file.
  12728. When you create one of these, you can call setCurrentMappings() to make it
  12729. the set of mappings that the system's using.
  12730. */
  12731. LocalisedStrings (const File& fileToLoad);
  12732. /** Destructor. */
  12733. ~LocalisedStrings();
  12734. /** Selects the current set of mappings to be used by the system.
  12735. The object you pass in will be automatically deleted when no longer needed, so
  12736. don't keep a pointer to it. You can also pass in zero to remove the current
  12737. mappings.
  12738. See also the TRANS() macro, which uses the current set to do its translation.
  12739. @see translateWithCurrentMappings
  12740. */
  12741. static void setCurrentMappings (LocalisedStrings* newTranslations);
  12742. /** Returns the currently selected set of mappings.
  12743. This is the object that was last passed to setCurrentMappings(). It may
  12744. be 0 if none has been created.
  12745. */
  12746. static LocalisedStrings* getCurrentMappings();
  12747. /** Tries to translate a string using the currently selected set of mappings.
  12748. If no mapping has been set, or if the mapping doesn't contain a translation
  12749. for the string, this will just return the original string.
  12750. See also the TRANS() macro, which uses this method to do its translation.
  12751. @see setCurrentMappings, getCurrentMappings
  12752. */
  12753. static const String translateWithCurrentMappings (const String& text);
  12754. /** Tries to translate a string using the currently selected set of mappings.
  12755. If no mapping has been set, or if the mapping doesn't contain a translation
  12756. for the string, this will just return the original string.
  12757. See also the TRANS() macro, which uses this method to do its translation.
  12758. @see setCurrentMappings, getCurrentMappings
  12759. */
  12760. static const String translateWithCurrentMappings (const char* text);
  12761. /** Attempts to look up a string and return its localised version.
  12762. If the string isn't found in the list, the original string will be returned.
  12763. */
  12764. const String translate (const String& text) const;
  12765. /** Returns the name of the language specified in the translation file.
  12766. This is specified in the file using a line starting with "language:", e.g.
  12767. @code
  12768. language: german
  12769. @endcode
  12770. */
  12771. const String getLanguageName() const { return languageName; }
  12772. /** Returns the list of suitable country codes listed in the translation file.
  12773. These is specified in the file using a line starting with "countries:", e.g.
  12774. @code
  12775. countries: fr be mc ch lu
  12776. @endcode
  12777. The country codes are supposed to be 2-character ISO complient codes.
  12778. */
  12779. const StringArray getCountryCodes() const { return countryCodes; }
  12780. /** Indicates whether to use a case-insensitive search when looking up a string.
  12781. This defaults to true.
  12782. */
  12783. void setIgnoresCase (const bool shouldIgnoreCase);
  12784. juce_UseDebuggingNewOperator
  12785. private:
  12786. String languageName;
  12787. StringArray countryCodes;
  12788. StringPairArray translations;
  12789. void loadFromText (const String& fileContents);
  12790. };
  12791. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12792. /*** End of inlined file: juce_LocalisedStrings.h ***/
  12793. #endif
  12794. #ifndef __JUCE_STRING_JUCEHEADER__
  12795. #endif
  12796. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  12797. #endif
  12798. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  12799. #endif
  12800. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  12801. /*** Start of inlined file: juce_StringPool.h ***/
  12802. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  12803. #define __JUCE_STRINGPOOL_JUCEHEADER__
  12804. /**
  12805. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  12806. comparison speed when dealing with many duplicate strings.
  12807. When you add a string to a pool using getPooledString, it'll return a character
  12808. array containing the same string. This array is owned by the pool, and the same array
  12809. is returned every time a matching string is asked for. This means that it's trivial to
  12810. compare two pooled strings for equality, as you can simply compare their pointers. It
  12811. also cuts down on storage if you're using many copies of the same string.
  12812. */
  12813. class JUCE_API StringPool
  12814. {
  12815. public:
  12816. /** Creates an empty pool. */
  12817. StringPool() throw();
  12818. /** Destructor */
  12819. ~StringPool();
  12820. /** Returns a pointer to a copy of the string that is passed in.
  12821. The pool will always return the same pointer when asked for a string that matches it.
  12822. The pool will own all the pointers that it returns, deleting them when the pool itself
  12823. is deleted.
  12824. */
  12825. const juce_wchar* getPooledString (const String& original);
  12826. /** Returns a pointer to a copy of the string that is passed in.
  12827. The pool will always return the same pointer when asked for a string that matches it.
  12828. The pool will own all the pointers that it returns, deleting them when the pool itself
  12829. is deleted.
  12830. */
  12831. const juce_wchar* getPooledString (const char* original);
  12832. /** Returns a pointer to a copy of the string that is passed in.
  12833. The pool will always return the same pointer when asked for a string that matches it.
  12834. The pool will own all the pointers that it returns, deleting them when the pool itself
  12835. is deleted.
  12836. */
  12837. const juce_wchar* getPooledString (const juce_wchar* original);
  12838. /** Returns the number of strings in the pool. */
  12839. int size() const throw();
  12840. /** Returns one of the strings in the pool, by index. */
  12841. const juce_wchar* operator[] (int index) const throw();
  12842. private:
  12843. Array <String> strings;
  12844. };
  12845. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  12846. /*** End of inlined file: juce_StringPool.h ***/
  12847. #endif
  12848. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12849. /*** Start of inlined file: juce_XmlDocument.h ***/
  12850. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12851. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  12852. /**
  12853. Parses a text-based XML document and creates an XmlElement object from it.
  12854. The parser will parse DTDs to load external entities but won't
  12855. check the document for validity against the DTD.
  12856. e.g.
  12857. @code
  12858. XmlDocument myDocument (File ("myfile.xml"));
  12859. XmlElement* mainElement = myDocument.getDocumentElement();
  12860. if (mainElement == 0)
  12861. {
  12862. String error = myDocument.getLastParseError();
  12863. }
  12864. else
  12865. {
  12866. ..use the element
  12867. }
  12868. @endcode
  12869. @see XmlElement
  12870. */
  12871. class JUCE_API XmlDocument
  12872. {
  12873. public:
  12874. /** Creates an XmlDocument from the xml text.
  12875. The text doesn't actually get parsed until the getDocumentElement() method is
  12876. called.
  12877. */
  12878. XmlDocument (const String& documentText);
  12879. /** Creates an XmlDocument from a file.
  12880. The text doesn't actually get parsed until the getDocumentElement() method is
  12881. called.
  12882. */
  12883. XmlDocument (const File& file);
  12884. /** Destructor. */
  12885. ~XmlDocument();
  12886. /** Creates an XmlElement object to represent the main document node.
  12887. This method will do the actual parsing of the text, and if there's a
  12888. parse error, it may returns 0 (and you can find out the error using
  12889. the getLastParseError() method).
  12890. @param onlyReadOuterDocumentElement if true, the parser will only read the
  12891. first section of the file, and will only
  12892. return the outer document element - this
  12893. allows quick checking of large files to
  12894. see if they contain the correct type of
  12895. tag, without having to parse the entire file
  12896. @returns a new XmlElement which the caller will need to delete, or null if
  12897. there was an error.
  12898. @see getLastParseError
  12899. */
  12900. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  12901. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  12902. @returns the error, or an empty string if there was no error.
  12903. */
  12904. const String& getLastParseError() const throw();
  12905. /** Sets an input source object to use for parsing documents that reference external entities.
  12906. If the document has been created from a file, this probably won't be needed, but
  12907. if you're parsing some text and there might be a DTD that references external
  12908. files, you may need to create a custom input source that can retrieve the
  12909. other files it needs.
  12910. The object that is passed-in will be deleted automatically when no longer needed.
  12911. @see InputSource
  12912. */
  12913. void setInputSource (InputSource* const newSource) throw();
  12914. /** Sets a flag to change the treatment of empty text elements.
  12915. If this is true (the default state), then any text elements that contain only
  12916. whitespace characters will be ingored during parsing. If you need to catch
  12917. whitespace-only text, then you should set this to false before calling the
  12918. getDocumentElement() method.
  12919. */
  12920. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  12921. juce_UseDebuggingNewOperator
  12922. private:
  12923. String originalText;
  12924. const juce_wchar* input;
  12925. bool outOfData, errorOccurred;
  12926. bool identifierLookupTable [128];
  12927. String lastError, dtdText;
  12928. StringArray tokenisedDTD;
  12929. bool needToLoadDTD, ignoreEmptyTextElements;
  12930. ScopedPointer <InputSource> inputSource;
  12931. void setLastError (const String& desc, const bool carryOn);
  12932. void skipHeader();
  12933. void skipNextWhiteSpace();
  12934. juce_wchar readNextChar() throw();
  12935. XmlElement* readNextElement (const bool alsoParseSubElements);
  12936. void readChildElements (XmlElement* parent);
  12937. int findNextTokenLength() throw();
  12938. void readQuotedString (String& result);
  12939. void readEntity (String& result);
  12940. static bool isXmlIdentifierCharSlow (juce_wchar c) throw();
  12941. bool isXmlIdentifierChar (juce_wchar c) const throw();
  12942. const String getFileContents (const String& filename) const;
  12943. const String expandEntity (const String& entity);
  12944. const String expandExternalEntity (const String& entity);
  12945. const String getParameterEntity (const String& entity);
  12946. XmlDocument (const XmlDocument&);
  12947. XmlDocument& operator= (const XmlDocument&);
  12948. };
  12949. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  12950. /*** End of inlined file: juce_XmlDocument.h ***/
  12951. #endif
  12952. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  12953. #endif
  12954. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  12955. #endif
  12956. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  12957. /*** Start of inlined file: juce_InterProcessLock.h ***/
  12958. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  12959. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  12960. /**
  12961. Acts as a critical section which processes can use to block each other.
  12962. @see CriticalSection
  12963. */
  12964. class JUCE_API InterProcessLock
  12965. {
  12966. public:
  12967. /** Creates a lock object.
  12968. @param name a name that processes will use to identify this lock object
  12969. */
  12970. explicit InterProcessLock (const String& name);
  12971. /** Destructor.
  12972. This will also release the lock if it's currently held by this process.
  12973. */
  12974. ~InterProcessLock();
  12975. /** Attempts to lock the critical section.
  12976. @param timeOutMillisecs how many milliseconds to wait if the lock
  12977. is already held by another process - a value of
  12978. 0 will return immediately, negative values will wait
  12979. forever
  12980. @returns true if the lock could be gained within the timeout period, or
  12981. false if the timeout expired.
  12982. */
  12983. bool enter (int timeOutMillisecs = -1);
  12984. /** Releases the lock if it's currently held by this process.
  12985. */
  12986. void exit();
  12987. /**
  12988. Automatically locks and unlocks an InterProcessLock object.
  12989. This works like a ScopedLock, but using an InterprocessLock rather than
  12990. a CriticalSection.
  12991. @see ScopedLock
  12992. */
  12993. class ScopedLockType
  12994. {
  12995. public:
  12996. /** Creates a scoped lock.
  12997. As soon as it is created, this will lock the InterProcessLock, and
  12998. when the ScopedLockType object is deleted, the InterProcessLock will
  12999. be unlocked.
  13000. Note that since an InterprocessLock can fail due to errors, you should check
  13001. isLocked() to make sure that the lock was successful before using it.
  13002. Make sure this object is created and deleted by the same thread,
  13003. otherwise there are no guarantees what will happen! Best just to use it
  13004. as a local stack object, rather than creating one with the new() operator.
  13005. */
  13006. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  13007. /** Destructor.
  13008. The InterProcessLock will be unlocked when the destructor is called.
  13009. Make sure this object is created and deleted by the same thread,
  13010. otherwise there are no guarantees what will happen!
  13011. */
  13012. inline ~ScopedLockType() { lock_.exit(); }
  13013. /** Returns true if the InterProcessLock was successfully locked. */
  13014. bool isLocked() const throw() { return lockWasSuccessful; }
  13015. private:
  13016. InterProcessLock& lock_;
  13017. bool lockWasSuccessful;
  13018. ScopedLockType (const ScopedLockType&);
  13019. ScopedLockType& operator= (const ScopedLockType&);
  13020. };
  13021. juce_UseDebuggingNewOperator
  13022. private:
  13023. class Pimpl;
  13024. friend class ScopedPointer <Pimpl>;
  13025. ScopedPointer <Pimpl> pimpl;
  13026. CriticalSection lock;
  13027. String name;
  13028. InterProcessLock (const InterProcessLock&);
  13029. InterProcessLock& operator= (const InterProcessLock&);
  13030. };
  13031. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13032. /*** End of inlined file: juce_InterProcessLock.h ***/
  13033. #endif
  13034. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13035. /*** Start of inlined file: juce_Process.h ***/
  13036. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13037. #define __JUCE_PROCESS_JUCEHEADER__
  13038. /** Represents the current executable's process.
  13039. This contains methods for controlling the current application at the
  13040. process-level.
  13041. @see Thread, JUCEApplication
  13042. */
  13043. class JUCE_API Process
  13044. {
  13045. public:
  13046. enum ProcessPriority
  13047. {
  13048. LowPriority = 0,
  13049. NormalPriority = 1,
  13050. HighPriority = 2,
  13051. RealtimePriority = 3
  13052. };
  13053. /** Changes the current process's priority.
  13054. @param priority the process priority, where
  13055. 0=low, 1=normal, 2=high, 3=realtime
  13056. */
  13057. static void setPriority (const ProcessPriority priority);
  13058. /** Kills the current process immediately.
  13059. This is an emergency process terminator that kills the application
  13060. immediately - it's intended only for use only when something goes
  13061. horribly wrong.
  13062. @see JUCEApplication::quit
  13063. */
  13064. static void terminate();
  13065. /** Returns true if this application process is the one that the user is
  13066. currently using.
  13067. */
  13068. static bool isForegroundProcess();
  13069. /** Raises the current process's privilege level.
  13070. Does nothing if this isn't supported by the current OS, or if process
  13071. privilege level is fixed.
  13072. */
  13073. static void raisePrivilege();
  13074. /** Lowers the current process's privilege level.
  13075. Does nothing if this isn't supported by the current OS, or if process
  13076. privilege level is fixed.
  13077. */
  13078. static void lowerPrivilege();
  13079. /** Returns true if this process is being hosted by a debugger.
  13080. */
  13081. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  13082. private:
  13083. Process();
  13084. Process (const Process&);
  13085. Process& operator= (const Process&);
  13086. };
  13087. #endif // __JUCE_PROCESS_JUCEHEADER__
  13088. /*** End of inlined file: juce_Process.h ***/
  13089. #endif
  13090. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13091. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  13092. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13093. #define __JUCE_READWRITELOCK_JUCEHEADER__
  13094. /*** Start of inlined file: juce_WaitableEvent.h ***/
  13095. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13096. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  13097. /**
  13098. Allows threads to wait for events triggered by other threads.
  13099. A thread can call wait() on a WaitableObject, and this will suspend the
  13100. calling thread until another thread wakes it up by calling the signal()
  13101. method.
  13102. */
  13103. class JUCE_API WaitableEvent
  13104. {
  13105. public:
  13106. /** Creates a WaitableEvent object.
  13107. @param manualReset If this is false, the event will be reset automatically when the wait()
  13108. method is called. If manualReset is true, then once the event is signalled,
  13109. the only way to reset it will be by calling the reset() method.
  13110. */
  13111. WaitableEvent (bool manualReset = false) throw();
  13112. /** Destructor.
  13113. If other threads are waiting on this object when it gets deleted, this
  13114. can cause nasty errors, so be careful!
  13115. */
  13116. ~WaitableEvent() throw();
  13117. /** Suspends the calling thread until the event has been signalled.
  13118. This will wait until the object's signal() method is called by another thread,
  13119. or until the timeout expires.
  13120. After the event has been signalled, this method will return true and if manualReset
  13121. was set to false in the WaitableEvent's constructor, then the event will be reset.
  13122. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  13123. value will cause it to wait forever.
  13124. @returns true if the object has been signalled, false if the timeout expires first.
  13125. @see signal, reset
  13126. */
  13127. bool wait (int timeOutMilliseconds = -1) const throw();
  13128. /** Wakes up any threads that are currently waiting on this object.
  13129. If signal() is called when nothing is waiting, the next thread to call wait()
  13130. will return immediately and reset the signal.
  13131. @see wait, reset
  13132. */
  13133. void signal() const throw();
  13134. /** Resets the event to an unsignalled state.
  13135. If it's not already signalled, this does nothing.
  13136. */
  13137. void reset() const throw();
  13138. juce_UseDebuggingNewOperator
  13139. private:
  13140. void* internal;
  13141. WaitableEvent (const WaitableEvent&);
  13142. WaitableEvent& operator= (const WaitableEvent&);
  13143. };
  13144. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  13145. /*** End of inlined file: juce_WaitableEvent.h ***/
  13146. /*** Start of inlined file: juce_Thread.h ***/
  13147. #ifndef __JUCE_THREAD_JUCEHEADER__
  13148. #define __JUCE_THREAD_JUCEHEADER__
  13149. /**
  13150. Encapsulates a thread.
  13151. Subclasses derive from Thread and implement the run() method, in which they
  13152. do their business. The thread can then be started with the startThread() method
  13153. and controlled with various other methods.
  13154. This class also contains some thread-related static methods, such
  13155. as sleep(), yield(), getCurrentThreadId() etc.
  13156. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  13157. MessageManagerLock
  13158. */
  13159. class JUCE_API Thread
  13160. {
  13161. public:
  13162. /**
  13163. Creates a thread.
  13164. When first created, the thread is not running. Use the startThread()
  13165. method to start it.
  13166. */
  13167. explicit Thread (const String& threadName);
  13168. /** Destructor.
  13169. Deleting a Thread object that is running will only give the thread a
  13170. brief opportunity to stop itself cleanly, so it's recommended that you
  13171. should always call stopThread() with a decent timeout before deleting,
  13172. to avoid the thread being forcibly killed (which is a Bad Thing).
  13173. */
  13174. virtual ~Thread();
  13175. /** Must be implemented to perform the thread's actual code.
  13176. Remember that the thread must regularly check the threadShouldExit()
  13177. method whilst running, and if this returns true it should return from
  13178. the run() method as soon as possible to avoid being forcibly killed.
  13179. @see threadShouldExit, startThread
  13180. */
  13181. virtual void run() = 0;
  13182. // Thread control functions..
  13183. /** Starts the thread running.
  13184. This will start the thread's run() method.
  13185. (if it's already started, startThread() won't do anything).
  13186. @see stopThread
  13187. */
  13188. void startThread();
  13189. /** Starts the thread with a given priority.
  13190. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  13191. If the thread is already running, its priority will be changed.
  13192. @see startThread, setPriority
  13193. */
  13194. void startThread (int priority);
  13195. /** Attempts to stop the thread running.
  13196. This method will cause the threadShouldExit() method to return true
  13197. and call notify() in case the thread is currently waiting.
  13198. Hopefully the thread will then respond to this by exiting cleanly, and
  13199. the stopThread method will wait for a given time-period for this to
  13200. happen.
  13201. If the thread is stuck and fails to respond after the time-out, it gets
  13202. forcibly killed, which is a very bad thing to happen, as it could still
  13203. be holding locks, etc. which are needed by other parts of your program.
  13204. @param timeOutMilliseconds The number of milliseconds to wait for the
  13205. thread to finish before killing it by force. A negative
  13206. value in here will wait forever.
  13207. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  13208. */
  13209. void stopThread (int timeOutMilliseconds);
  13210. /** Returns true if the thread is currently active */
  13211. bool isThreadRunning() const;
  13212. /** Sets a flag to tell the thread it should stop.
  13213. Calling this means that the threadShouldExit() method will then return true.
  13214. The thread should be regularly checking this to see whether it should exit.
  13215. If your thread makes use of wait(), you might want to call notify() after calling
  13216. this method, to interrupt any waits that might be in progress, and allow it
  13217. to reach a point where it can exit.
  13218. @see threadShouldExit
  13219. @see waitForThreadToExit
  13220. */
  13221. void signalThreadShouldExit();
  13222. /** Checks whether the thread has been told to stop running.
  13223. Threads need to check this regularly, and if it returns true, they should
  13224. return from their run() method at the first possible opportunity.
  13225. @see signalThreadShouldExit
  13226. */
  13227. inline bool threadShouldExit() const { return threadShouldExit_; }
  13228. /** Waits for the thread to stop.
  13229. This will waits until isThreadRunning() is false or until a timeout expires.
  13230. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  13231. is less than zero, it will wait forever.
  13232. @returns true if the thread exits, or false if the timeout expires first.
  13233. */
  13234. bool waitForThreadToExit (int timeOutMilliseconds) const;
  13235. /** Changes the thread's priority.
  13236. May return false if for some reason the priority can't be changed.
  13237. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  13238. of 5 is normal.
  13239. */
  13240. bool setPriority (int priority);
  13241. /** Changes the priority of the caller thread.
  13242. Similar to setPriority(), but this static method acts on the caller thread.
  13243. May return false if for some reason the priority can't be changed.
  13244. @see setPriority
  13245. */
  13246. static bool setCurrentThreadPriority (int priority);
  13247. /** Sets the affinity mask for the thread.
  13248. This will only have an effect next time the thread is started - i.e. if the
  13249. thread is already running when called, it'll have no effect.
  13250. @see setCurrentThreadAffinityMask
  13251. */
  13252. void setAffinityMask (uint32 affinityMask);
  13253. /** Changes the affinity mask for the caller thread.
  13254. This will change the affinity mask for the thread that calls this static method.
  13255. @see setAffinityMask
  13256. */
  13257. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  13258. // this can be called from any thread that needs to pause..
  13259. static void JUCE_CALLTYPE sleep (int milliseconds);
  13260. /** Yields the calling thread's current time-slot. */
  13261. static void JUCE_CALLTYPE yield();
  13262. /** Makes the thread wait for a notification.
  13263. This puts the thread to sleep until either the timeout period expires, or
  13264. another thread calls the notify() method to wake it up.
  13265. A negative time-out value means that the method will wait indefinitely.
  13266. @returns true if the event has been signalled, false if the timeout expires.
  13267. */
  13268. bool wait (int timeOutMilliseconds) const;
  13269. /** Wakes up the thread.
  13270. If the thread has called the wait() method, this will wake it up.
  13271. @see wait
  13272. */
  13273. void notify() const;
  13274. /** A value type used for thread IDs.
  13275. @see getCurrentThreadId(), getThreadId()
  13276. */
  13277. typedef void* ThreadID;
  13278. /** Returns an id that identifies the caller thread.
  13279. To find the ID of a particular thread object, use getThreadId().
  13280. @returns a unique identifier that identifies the calling thread.
  13281. @see getThreadId
  13282. */
  13283. static ThreadID getCurrentThreadId();
  13284. /** Finds the thread object that is currently running.
  13285. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  13286. object associated with them, so this will return 0.
  13287. */
  13288. static Thread* getCurrentThread();
  13289. /** Returns the ID of this thread.
  13290. That means the ID of this thread object - not of the thread that's calling the method.
  13291. This can change when the thread is started and stopped, and will be invalid if the
  13292. thread's not actually running.
  13293. @see getCurrentThreadId
  13294. */
  13295. ThreadID getThreadId() const throw() { return threadId_; }
  13296. /** Returns the name of the thread.
  13297. This is the name that gets set in the constructor.
  13298. */
  13299. const String getThreadName() const { return threadName_; }
  13300. /** Returns the number of currently-running threads.
  13301. @returns the number of Thread objects known to be currently running.
  13302. @see stopAllThreads
  13303. */
  13304. static int getNumRunningThreads();
  13305. /** Tries to stop all currently-running threads.
  13306. This will attempt to stop all the threads known to be running at the moment.
  13307. */
  13308. static void stopAllThreads (int timeoutInMillisecs);
  13309. juce_UseDebuggingNewOperator
  13310. private:
  13311. const String threadName_;
  13312. void* volatile threadHandle_;
  13313. CriticalSection startStopLock;
  13314. WaitableEvent startSuspensionEvent_, defaultEvent_;
  13315. int threadPriority_;
  13316. ThreadID threadId_;
  13317. uint32 affinityMask_;
  13318. bool volatile threadShouldExit_;
  13319. friend void JUCE_API juce_threadEntryPoint (void*);
  13320. static void threadEntryPoint (Thread* thread);
  13321. static Array<Thread*> runningThreads;
  13322. static CriticalSection runningThreadsLock;
  13323. Thread (const Thread&);
  13324. Thread& operator= (const Thread&);
  13325. };
  13326. #endif // __JUCE_THREAD_JUCEHEADER__
  13327. /*** End of inlined file: juce_Thread.h ***/
  13328. /**
  13329. A critical section that allows multiple simultaneous readers.
  13330. Features of this type of lock are:
  13331. - Multiple readers can hold the lock at the same time, but only one writer
  13332. can hold it at once.
  13333. - Writers trying to gain the lock will be blocked until all readers and writers
  13334. have released it
  13335. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  13336. blocked until the writer has obtained and released it
  13337. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  13338. there are no other readers
  13339. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  13340. - Recursive locking is supported.
  13341. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  13342. */
  13343. class JUCE_API ReadWriteLock
  13344. {
  13345. public:
  13346. /**
  13347. Creates a ReadWriteLock object.
  13348. */
  13349. ReadWriteLock() throw();
  13350. /** Destructor.
  13351. If the object is deleted whilst locked, any subsequent behaviour
  13352. is unpredictable.
  13353. */
  13354. ~ReadWriteLock() throw();
  13355. /** Locks this object for reading.
  13356. Multiple threads can simulaneously lock the object for reading, but if another
  13357. thread has it locked for writing, then this will block until it releases the
  13358. lock.
  13359. @see exitRead, ScopedReadLock
  13360. */
  13361. void enterRead() const throw();
  13362. /** Releases the read-lock.
  13363. If the caller thread hasn't got the lock, this can have unpredictable results.
  13364. If the enterRead() method has been called multiple times by the thread, each
  13365. call must be matched by a call to exitRead() before other threads will be allowed
  13366. to take over the lock.
  13367. @see enterRead, ScopedReadLock
  13368. */
  13369. void exitRead() const throw();
  13370. /** Locks this object for writing.
  13371. This will block until any other threads that have it locked for reading or
  13372. writing have released their lock.
  13373. @see exitWrite, ScopedWriteLock
  13374. */
  13375. void enterWrite() const throw();
  13376. /** Tries to lock this object for writing.
  13377. This is like enterWrite(), but doesn't block - it returns true if it manages
  13378. to obtain the lock.
  13379. @see enterWrite
  13380. */
  13381. bool tryEnterWrite() const throw();
  13382. /** Releases the write-lock.
  13383. If the caller thread hasn't got the lock, this can have unpredictable results.
  13384. If the enterWrite() method has been called multiple times by the thread, each
  13385. call must be matched by a call to exit() before other threads will be allowed
  13386. to take over the lock.
  13387. @see enterWrite, ScopedWriteLock
  13388. */
  13389. void exitWrite() const throw();
  13390. juce_UseDebuggingNewOperator
  13391. private:
  13392. CriticalSection accessLock;
  13393. WaitableEvent waitEvent;
  13394. mutable int numWaitingWriters, numWriters;
  13395. mutable Thread::ThreadID writerThreadId;
  13396. mutable Array <Thread::ThreadID> readerThreads;
  13397. ReadWriteLock (const ReadWriteLock&);
  13398. ReadWriteLock& operator= (const ReadWriteLock&);
  13399. };
  13400. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  13401. /*** End of inlined file: juce_ReadWriteLock.h ***/
  13402. #endif
  13403. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13404. #endif
  13405. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13406. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  13407. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13408. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13409. /**
  13410. Automatically locks and unlocks a ReadWriteLock object.
  13411. Use one of these as a local variable to control access to a ReadWriteLock.
  13412. e.g. @code
  13413. ReadWriteLock myLock;
  13414. for (;;)
  13415. {
  13416. const ScopedReadLock myScopedLock (myLock);
  13417. // myLock is now locked
  13418. ...do some stuff...
  13419. // myLock gets unlocked here.
  13420. }
  13421. @endcode
  13422. @see ReadWriteLock, ScopedWriteLock
  13423. */
  13424. class JUCE_API ScopedReadLock
  13425. {
  13426. public:
  13427. /** Creates a ScopedReadLock.
  13428. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  13429. when the ScopedReadLock object is deleted, the ReadWriteLock will
  13430. be unlocked.
  13431. Make sure this object is created and deleted by the same thread,
  13432. otherwise there are no guarantees what will happen! Best just to use it
  13433. as a local stack object, rather than creating one with the new() operator.
  13434. */
  13435. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  13436. /** Destructor.
  13437. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  13438. Make sure this object is created and deleted by the same thread,
  13439. otherwise there are no guarantees what will happen!
  13440. */
  13441. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  13442. private:
  13443. const ReadWriteLock& lock_;
  13444. ScopedReadLock (const ScopedReadLock&);
  13445. ScopedReadLock& operator= (const ScopedReadLock&);
  13446. };
  13447. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13448. /*** End of inlined file: juce_ScopedReadLock.h ***/
  13449. #endif
  13450. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13451. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  13452. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13453. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13454. /**
  13455. Automatically tries to lock and unlock a CriticalSection object.
  13456. Use one of these as a local variable to control access to a CriticalSection.
  13457. e.g. @code
  13458. CriticalSection myCriticalSection;
  13459. for (;;)
  13460. {
  13461. const ScopedTryLock myScopedTryLock (myCriticalSection);
  13462. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  13463. // should test this with the isLocked() method before doing your thread-unsafe
  13464. // action..
  13465. if (myScopedTryLock.isLocked())
  13466. {
  13467. ...do some stuff...
  13468. }
  13469. else
  13470. {
  13471. ..our attempt at locking failed because another thread had already locked it..
  13472. }
  13473. // myCriticalSection gets unlocked here (if it was locked)
  13474. }
  13475. @endcode
  13476. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  13477. */
  13478. class JUCE_API ScopedTryLock
  13479. {
  13480. public:
  13481. /** Creates a ScopedTryLock.
  13482. As soon as it is created, this will try to lock the CriticalSection, and
  13483. when the ScopedTryLock object is deleted, the CriticalSection will
  13484. be unlocked if the lock was successful.
  13485. Make sure this object is created and deleted by the same thread,
  13486. otherwise there are no guarantees what will happen! Best just to use it
  13487. as a local stack object, rather than creating one with the new() operator.
  13488. */
  13489. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  13490. /** Destructor.
  13491. The CriticalSection will be unlocked (if locked) when the destructor is called.
  13492. Make sure this object is created and deleted by the same thread,
  13493. otherwise there are no guarantees what will happen!
  13494. */
  13495. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  13496. /** Returns true if the CriticalSection was successfully locked. */
  13497. bool isLocked() const throw() { return lockWasSuccessful; }
  13498. private:
  13499. const CriticalSection& lock_;
  13500. const bool lockWasSuccessful;
  13501. ScopedTryLock (const ScopedTryLock&);
  13502. ScopedTryLock& operator= (const ScopedTryLock&);
  13503. };
  13504. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13505. /*** End of inlined file: juce_ScopedTryLock.h ***/
  13506. #endif
  13507. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13508. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  13509. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13510. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13511. /**
  13512. Automatically locks and unlocks a ReadWriteLock object.
  13513. Use one of these as a local variable to control access to a ReadWriteLock.
  13514. e.g. @code
  13515. ReadWriteLock myLock;
  13516. for (;;)
  13517. {
  13518. const ScopedWriteLock myScopedLock (myLock);
  13519. // myLock is now locked
  13520. ...do some stuff...
  13521. // myLock gets unlocked here.
  13522. }
  13523. @endcode
  13524. @see ReadWriteLock, ScopedReadLock
  13525. */
  13526. class JUCE_API ScopedWriteLock
  13527. {
  13528. public:
  13529. /** Creates a ScopedWriteLock.
  13530. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  13531. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  13532. be unlocked.
  13533. Make sure this object is created and deleted by the same thread,
  13534. otherwise there are no guarantees what will happen! Best just to use it
  13535. as a local stack object, rather than creating one with the new() operator.
  13536. */
  13537. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  13538. /** Destructor.
  13539. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  13540. Make sure this object is created and deleted by the same thread,
  13541. otherwise there are no guarantees what will happen!
  13542. */
  13543. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  13544. private:
  13545. const ReadWriteLock& lock_;
  13546. ScopedWriteLock (const ScopedWriteLock&);
  13547. ScopedWriteLock& operator= (const ScopedWriteLock&);
  13548. };
  13549. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13550. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  13551. #endif
  13552. #ifndef __JUCE_THREAD_JUCEHEADER__
  13553. #endif
  13554. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13555. /*** Start of inlined file: juce_ThreadPool.h ***/
  13556. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13557. #define __JUCE_THREADPOOL_JUCEHEADER__
  13558. class ThreadPool;
  13559. class ThreadPoolThread;
  13560. /**
  13561. A task that is executed by a ThreadPool object.
  13562. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  13563. its threads.
  13564. The runJob() method needs to be implemented to do the task, and if the code that
  13565. does the work takes a significant time to run, it must keep checking the shouldExit()
  13566. method to see if something is trying to interrupt the job. If shouldExit() returns
  13567. true, the runJob() method must return immediately.
  13568. @see ThreadPool, Thread
  13569. */
  13570. class JUCE_API ThreadPoolJob
  13571. {
  13572. public:
  13573. /** Creates a thread pool job object.
  13574. After creating your job, add it to a thread pool with ThreadPool::addJob().
  13575. */
  13576. explicit ThreadPoolJob (const String& name);
  13577. /** Destructor. */
  13578. virtual ~ThreadPoolJob();
  13579. /** Returns the name of this job.
  13580. @see setJobName
  13581. */
  13582. const String getJobName() const;
  13583. /** Changes the job's name.
  13584. @see getJobName
  13585. */
  13586. void setJobName (const String& newName);
  13587. /** These are the values that can be returned by the runJob() method.
  13588. */
  13589. enum JobStatus
  13590. {
  13591. jobHasFinished = 0, /**< indicates that the job has finished and can be
  13592. removed from the pool. */
  13593. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  13594. should be automatically deleted by the pool. */
  13595. jobNeedsRunningAgain /**< indicates that the job would like to be called
  13596. again when a thread is free. */
  13597. };
  13598. /** Peforms the actual work that this job needs to do.
  13599. Your subclass must implement this method, in which is does its work.
  13600. If the code in this method takes a significant time to run, it must repeatedly check
  13601. the shouldExit() method to see if something is trying to interrupt the job.
  13602. If shouldExit() ever returns true, the runJob() method must return immediately.
  13603. If this method returns jobHasFinished, then the job will be removed from the pool
  13604. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  13605. pool and will get a chance to run again as soon as a thread is free.
  13606. @see shouldExit()
  13607. */
  13608. virtual JobStatus runJob() = 0;
  13609. /** Returns true if this job is currently running its runJob() method. */
  13610. bool isRunning() const { return isActive; }
  13611. /** Returns true if something is trying to interrupt this job and make it stop.
  13612. Your runJob() method must call this whenever it gets a chance, and if it ever
  13613. returns true, the runJob() method must return immediately.
  13614. @see signalJobShouldExit()
  13615. */
  13616. bool shouldExit() const { return shouldStop; }
  13617. /** Calling this will cause the shouldExit() method to return true, and the job
  13618. should (if it's been implemented correctly) stop as soon as possible.
  13619. @see shouldExit()
  13620. */
  13621. void signalJobShouldExit();
  13622. juce_UseDebuggingNewOperator
  13623. private:
  13624. friend class ThreadPool;
  13625. friend class ThreadPoolThread;
  13626. String jobName;
  13627. ThreadPool* pool;
  13628. bool shouldStop, isActive, shouldBeDeleted;
  13629. ThreadPoolJob (const ThreadPoolJob&);
  13630. ThreadPoolJob& operator= (const ThreadPoolJob&);
  13631. };
  13632. /**
  13633. A set of threads that will run a list of jobs.
  13634. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  13635. will be called by the next pooled thread that becomes free.
  13636. @see ThreadPoolJob, Thread
  13637. */
  13638. class JUCE_API ThreadPool
  13639. {
  13640. public:
  13641. /** Creates a thread pool.
  13642. Once you've created a pool, you can give it some things to do with the addJob()
  13643. method.
  13644. @param numberOfThreads the maximum number of actual threads to run.
  13645. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  13646. until there are some jobs to run. If false, then
  13647. all the threads will be fired-up immediately so that
  13648. they're ready for action
  13649. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  13650. inactive for this length of time, they will automatically
  13651. be stopped until more jobs come along and they're needed
  13652. */
  13653. ThreadPool (int numberOfThreads,
  13654. bool startThreadsOnlyWhenNeeded = true,
  13655. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  13656. /** Destructor.
  13657. This will attempt to remove all the jobs before deleting, but if you want to
  13658. specify a timeout, you should call removeAllJobs() explicitly before deleting
  13659. the pool.
  13660. */
  13661. ~ThreadPool();
  13662. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  13663. for some kind of operation.
  13664. @see ThreadPool::removeAllJobs
  13665. */
  13666. class JUCE_API JobSelector
  13667. {
  13668. public:
  13669. virtual ~JobSelector() {}
  13670. /** Should return true if the specified thread matches your criteria for whatever
  13671. operation that this object is being used for.
  13672. Any implementation of this method must be extremely fast and thread-safe!
  13673. */
  13674. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  13675. };
  13676. /** Adds a job to the queue.
  13677. Once a job has been added, then the next time a thread is free, it will run
  13678. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  13679. runJob() method, the pool will either remove the job from the pool or add it to
  13680. the back of the queue to be run again.
  13681. */
  13682. void addJob (ThreadPoolJob* job);
  13683. /** Tries to remove a job from the pool.
  13684. If the job isn't yet running, this will simply remove it. If it is running, it
  13685. will wait for it to finish.
  13686. If the timeout period expires before the job finishes running, then the job will be
  13687. left in the pool and this will return false. It returns true if the job is sucessfully
  13688. stopped and removed.
  13689. @param job the job to remove
  13690. @param interruptIfRunning if true, then if the job is currently busy, its
  13691. ThreadPoolJob::signalJobShouldExit() method will be called to try
  13692. to interrupt it. If false, then if the job will be allowed to run
  13693. until it stops normally (or the timeout expires)
  13694. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  13695. before giving up and returning false
  13696. */
  13697. bool removeJob (ThreadPoolJob* job,
  13698. bool interruptIfRunning,
  13699. int timeOutMilliseconds);
  13700. /** Tries to remove all jobs from the pool.
  13701. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  13702. methods called to try to interrupt them
  13703. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  13704. before giving up and returning false
  13705. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  13706. they will simply be removed from the pool. Jobs that are already running when
  13707. this method is called can choose whether they should be deleted by
  13708. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  13709. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  13710. jobs should be removed. If it is zero, all jobs are removed
  13711. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  13712. expires while waiting for one or more jobs to stop
  13713. */
  13714. bool removeAllJobs (bool interruptRunningJobs,
  13715. int timeOutMilliseconds,
  13716. bool deleteInactiveJobs = false,
  13717. JobSelector* selectedJobsToRemove = 0);
  13718. /** Returns the number of jobs currently running or queued.
  13719. */
  13720. int getNumJobs() const;
  13721. /** Returns one of the jobs in the queue.
  13722. Note that this can be a very volatile list as jobs might be continuously getting shifted
  13723. around in the list, and this method may return 0 if the index is currently out-of-range.
  13724. */
  13725. ThreadPoolJob* getJob (int index) const;
  13726. /** Returns true if the given job is currently queued or running.
  13727. @see isJobRunning()
  13728. */
  13729. bool contains (const ThreadPoolJob* job) const;
  13730. /** Returns true if the given job is currently being run by a thread.
  13731. */
  13732. bool isJobRunning (const ThreadPoolJob* job) const;
  13733. /** Waits until a job has finished running and has been removed from the pool.
  13734. This will wait until the job is no longer in the pool - i.e. until its
  13735. runJob() method returns ThreadPoolJob::jobHasFinished.
  13736. If the timeout period expires before the job finishes, this will return false;
  13737. it returns true if the job has finished successfully.
  13738. */
  13739. bool waitForJobToFinish (const ThreadPoolJob* job,
  13740. int timeOutMilliseconds) const;
  13741. /** Returns a list of the names of all the jobs currently running or queued.
  13742. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  13743. */
  13744. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  13745. /** Changes the priority of all the threads.
  13746. This will call Thread::setPriority() for each thread in the pool.
  13747. May return false if for some reason the priority can't be changed.
  13748. */
  13749. bool setThreadPriorities (int newPriority);
  13750. juce_UseDebuggingNewOperator
  13751. private:
  13752. const int threadStopTimeout;
  13753. int priority;
  13754. class ThreadPoolThread;
  13755. OwnedArray <ThreadPoolThread> threads;
  13756. Array <ThreadPoolJob*> jobs;
  13757. CriticalSection lock;
  13758. uint32 lastJobEndTime;
  13759. WaitableEvent jobFinishedSignal;
  13760. friend class ThreadPoolThread;
  13761. bool runNextJob();
  13762. ThreadPool (const ThreadPool&);
  13763. ThreadPool& operator= (const ThreadPool&);
  13764. };
  13765. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  13766. /*** End of inlined file: juce_ThreadPool.h ***/
  13767. #endif
  13768. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13769. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  13770. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13771. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13772. /**
  13773. Used by the TimeSliceThread class.
  13774. To register your class with a TimeSliceThread, derive from this class and
  13775. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  13776. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  13777. deleting your client!
  13778. @see TimeSliceThread
  13779. */
  13780. class JUCE_API TimeSliceClient
  13781. {
  13782. public:
  13783. /** Destructor. */
  13784. virtual ~TimeSliceClient() {}
  13785. /** Called back by a TimeSliceThread.
  13786. When you register this class with it, a TimeSliceThread will repeatedly call
  13787. this method.
  13788. The implementation of this method should use its time-slice to do something that's
  13789. quick - never block for longer than absolutely necessary.
  13790. @returns Your method should return true if it needs more time, or false if it's
  13791. not too busy and doesn't need calling back urgently. If all the thread's
  13792. clients indicate that they're not busy, then it'll save CPU by sleeping for
  13793. up to half a second in between callbacks. You can force the TimeSliceThread
  13794. to wake up and poll again immediately by calling its notify() method.
  13795. */
  13796. virtual bool useTimeSlice() = 0;
  13797. };
  13798. /**
  13799. A thread that keeps a list of clients, and calls each one in turn, giving them
  13800. all a chance to run some sort of short task.
  13801. @see TimeSliceClient, Thread
  13802. */
  13803. class JUCE_API TimeSliceThread : public Thread
  13804. {
  13805. public:
  13806. /**
  13807. Creates a TimeSliceThread.
  13808. When first created, the thread is not running. Use the startThread()
  13809. method to start it.
  13810. */
  13811. explicit TimeSliceThread (const String& threadName);
  13812. /** Destructor.
  13813. Deleting a Thread object that is running will only give the thread a
  13814. brief opportunity to stop itself cleanly, so it's recommended that you
  13815. should always call stopThread() with a decent timeout before deleting,
  13816. to avoid the thread being forcibly killed (which is a Bad Thing).
  13817. */
  13818. ~TimeSliceThread();
  13819. /** Adds a client to the list.
  13820. The client's callbacks will start immediately (possibly before the method
  13821. has returned).
  13822. */
  13823. void addTimeSliceClient (TimeSliceClient* client);
  13824. /** Removes a client from the list.
  13825. This method will make sure that all callbacks to the client have completely
  13826. finished before the method returns.
  13827. */
  13828. void removeTimeSliceClient (TimeSliceClient* client);
  13829. /** Returns the number of registered clients. */
  13830. int getNumClients() const;
  13831. /** Returns one of the registered clients. */
  13832. TimeSliceClient* getClient (int index) const;
  13833. /** @internal */
  13834. void run();
  13835. juce_UseDebuggingNewOperator
  13836. private:
  13837. CriticalSection callbackLock, listLock;
  13838. Array <TimeSliceClient*> clients;
  13839. int index;
  13840. TimeSliceClient* clientBeingCalled;
  13841. bool clientsChanged;
  13842. TimeSliceThread (const TimeSliceThread&);
  13843. TimeSliceThread& operator= (const TimeSliceThread&);
  13844. };
  13845. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13846. /*** End of inlined file: juce_TimeSliceThread.h ***/
  13847. #endif
  13848. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13849. #endif
  13850. #endif
  13851. /*** End of inlined file: juce_core_includes.h ***/
  13852. // if you're compiling a command-line app, you might want to just include the core headers,
  13853. // so you can set this macro before including juce.h
  13854. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  13855. /*** Start of inlined file: juce_app_includes.h ***/
  13856. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  13857. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  13858. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  13859. /*** Start of inlined file: juce_Application.h ***/
  13860. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  13861. #define __JUCE_APPLICATION_JUCEHEADER__
  13862. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  13863. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  13864. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  13865. /*** Start of inlined file: juce_Component.h ***/
  13866. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  13867. #define __JUCE_COMPONENT_JUCEHEADER__
  13868. /*** Start of inlined file: juce_MouseCursor.h ***/
  13869. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  13870. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  13871. class Image;
  13872. class ComponentPeer;
  13873. class Component;
  13874. /**
  13875. Represents a mouse cursor image.
  13876. This object can either be used to represent one of the standard mouse
  13877. cursor shapes, or a custom one generated from an image.
  13878. */
  13879. class JUCE_API MouseCursor
  13880. {
  13881. public:
  13882. /** The set of available standard mouse cursors. */
  13883. enum StandardCursorType
  13884. {
  13885. NoCursor = 0, /**< An invisible cursor. */
  13886. NormalCursor, /**< The stardard arrow cursor. */
  13887. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  13888. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  13889. CrosshairCursor, /**< A pair of crosshairs. */
  13890. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  13891. that you're dragging a copy of something. */
  13892. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  13893. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  13894. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  13895. UpDownResizeCursor, /**< an arrow pointing up and down. */
  13896. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  13897. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  13898. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  13899. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  13900. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  13901. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  13902. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  13903. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  13904. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  13905. };
  13906. /** Creates the standard arrow cursor. */
  13907. MouseCursor();
  13908. /** Creates one of the standard mouse cursor */
  13909. MouseCursor (StandardCursorType type);
  13910. /** Creates a custom cursor from an image.
  13911. @param image the image to use for the cursor - if this is bigger than the
  13912. system can manage, it might get scaled down first, and might
  13913. also have to be turned to black-and-white if it can't do colour
  13914. cursors.
  13915. @param hotSpotX the x position of the cursor's hotspot within the image
  13916. @param hotSpotY the y position of the cursor's hotspot within the image
  13917. */
  13918. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  13919. /** Creates a copy of another cursor object. */
  13920. MouseCursor (const MouseCursor& other);
  13921. /** Copies this cursor from another object. */
  13922. MouseCursor& operator= (const MouseCursor& other);
  13923. /** Destructor. */
  13924. ~MouseCursor();
  13925. /** Checks whether two mouse cursors are the same.
  13926. For custom cursors, two cursors created from the same image won't be
  13927. recognised as the same, only MouseCursor objects that have been
  13928. copied from the same object.
  13929. */
  13930. bool operator== (const MouseCursor& other) const throw();
  13931. /** Checks whether two mouse cursors are the same.
  13932. For custom cursors, two cursors created from the same image won't be
  13933. recognised as the same, only MouseCursor objects that have been
  13934. copied from the same object.
  13935. */
  13936. bool operator!= (const MouseCursor& other) const throw();
  13937. /** Makes the system show its default 'busy' cursor.
  13938. This will turn the system cursor to an hourglass or spinning beachball
  13939. until the next time the mouse is moved, or hideWaitCursor() is called.
  13940. This is handy if the message loop is about to block for a couple of
  13941. seconds while busy and you want to give the user feedback about this.
  13942. @see MessageManager::setTimeBeforeShowingWaitCursor
  13943. */
  13944. static void showWaitCursor();
  13945. /** If showWaitCursor has been called, this will return the mouse to its
  13946. normal state.
  13947. This will look at what component is under the mouse, and update the
  13948. cursor to be the correct one for that component.
  13949. @see showWaitCursor
  13950. */
  13951. static void hideWaitCursor();
  13952. juce_UseDebuggingNewOperator
  13953. private:
  13954. class SharedCursorHandle;
  13955. friend class SharedCursorHandle;
  13956. SharedCursorHandle* cursorHandle;
  13957. friend class MouseInputSourceInternal;
  13958. void showInWindow (ComponentPeer* window) const;
  13959. void showInAllWindows() const;
  13960. void* getHandle() const throw();
  13961. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  13962. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  13963. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  13964. };
  13965. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  13966. /*** End of inlined file: juce_MouseCursor.h ***/
  13967. /*** Start of inlined file: juce_MouseListener.h ***/
  13968. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  13969. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  13970. class MouseEvent;
  13971. /**
  13972. A MouseListener can be registered with a component to receive callbacks
  13973. about mouse events that happen to that component.
  13974. @see Component::addMouseListener, Component::removeMouseListener
  13975. */
  13976. class JUCE_API MouseListener
  13977. {
  13978. public:
  13979. /** Destructor. */
  13980. virtual ~MouseListener() {}
  13981. /** Called when the mouse moves inside a component.
  13982. If the mouse button isn't pressed and the mouse moves over a component,
  13983. this will be called to let the component react to this.
  13984. A component will always get a mouseEnter callback before a mouseMove.
  13985. @param e details about the position and status of the mouse event, including
  13986. the source component in which it occurred
  13987. @see mouseEnter, mouseExit, mouseDrag, contains
  13988. */
  13989. virtual void mouseMove (const MouseEvent& e);
  13990. /** Called when the mouse first enters a component.
  13991. If the mouse button isn't pressed and the mouse moves into a component,
  13992. this will be called to let the component react to this.
  13993. When the mouse button is pressed and held down while being moved in
  13994. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  13995. mouseDrag messages are sent to the component that the mouse was originally
  13996. clicked on, until the button is released.
  13997. @param e details about the position and status of the mouse event, including
  13998. the source component in which it occurred
  13999. @see mouseExit, mouseDrag, mouseMove, contains
  14000. */
  14001. virtual void mouseEnter (const MouseEvent& e);
  14002. /** Called when the mouse moves out of a component.
  14003. This will be called when the mouse moves off the edge of this
  14004. component.
  14005. If the mouse button was pressed, and it was then dragged off the
  14006. edge of the component and released, then this callback will happen
  14007. when the button is released, after the mouseUp callback.
  14008. @param e details about the position and status of the mouse event, including
  14009. the source component in which it occurred
  14010. @see mouseEnter, mouseDrag, mouseMove, contains
  14011. */
  14012. virtual void mouseExit (const MouseEvent& e);
  14013. /** Called when a mouse button is pressed.
  14014. The MouseEvent object passed in contains lots of methods for finding out
  14015. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14016. were held down at the time.
  14017. Once a button is held down, the mouseDrag method will be called when the
  14018. mouse moves, until the button is released.
  14019. @param e details about the position and status of the mouse event, including
  14020. the source component in which it occurred
  14021. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  14022. */
  14023. virtual void mouseDown (const MouseEvent& e);
  14024. /** Called when the mouse is moved while a button is held down.
  14025. When a mouse button is pressed inside a component, that component
  14026. receives mouseDrag callbacks each time the mouse moves, even if the
  14027. mouse strays outside the component's bounds.
  14028. @param e details about the position and status of the mouse event, including
  14029. the source component in which it occurred
  14030. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  14031. */
  14032. virtual void mouseDrag (const MouseEvent& e);
  14033. /** Called when a mouse button is released.
  14034. A mouseUp callback is sent to the component in which a button was pressed
  14035. even if the mouse is actually over a different component when the
  14036. button is released.
  14037. The MouseEvent object passed in contains lots of methods for finding out
  14038. which buttons were down just before they were released.
  14039. @param e details about the position and status of the mouse event, including
  14040. the source component in which it occurred
  14041. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  14042. */
  14043. virtual void mouseUp (const MouseEvent& e);
  14044. /** Called when a mouse button has been double-clicked on a component.
  14045. The MouseEvent object passed in contains lots of methods for finding out
  14046. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14047. were held down at the time.
  14048. @param e details about the position and status of the mouse event, including
  14049. the source component in which it occurred
  14050. @see mouseDown, mouseUp
  14051. */
  14052. virtual void mouseDoubleClick (const MouseEvent& e);
  14053. /** Called when the mouse-wheel is moved.
  14054. This callback is sent to the component that the mouse is over when the
  14055. wheel is moved.
  14056. If not overridden, the component will forward this message to its parent, so
  14057. that parent components can collect mouse-wheel messages that happen to
  14058. child components which aren't interested in them.
  14059. @param e details about the position and status of the mouse event, including
  14060. the source component in which it occurred
  14061. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  14062. value means the wheel has been pushed to the right, negative means it
  14063. was pushed to the left
  14064. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  14065. value means the wheel has been pushed upwards, negative means it
  14066. was pushed downwards
  14067. */
  14068. virtual void mouseWheelMove (const MouseEvent& e,
  14069. float wheelIncrementX,
  14070. float wheelIncrementY);
  14071. };
  14072. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  14073. /*** End of inlined file: juce_MouseListener.h ***/
  14074. /*** Start of inlined file: juce_MouseEvent.h ***/
  14075. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  14076. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  14077. class Component;
  14078. class MouseInputSource;
  14079. /*** Start of inlined file: juce_ModifierKeys.h ***/
  14080. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  14081. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  14082. /**
  14083. Represents the state of the mouse buttons and modifier keys.
  14084. This is used both by mouse events and by KeyPress objects to describe
  14085. the state of keys such as shift, control, alt, etc.
  14086. @see KeyPress, MouseEvent::mods
  14087. */
  14088. class JUCE_API ModifierKeys
  14089. {
  14090. public:
  14091. /** Creates a ModifierKeys object from a raw set of flags.
  14092. @param flags to represent the keys that are down
  14093. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  14094. rightButtonModifier, commandModifier, popupMenuClickModifier
  14095. */
  14096. ModifierKeys (int flags = 0) throw();
  14097. /** Creates a copy of another object. */
  14098. ModifierKeys (const ModifierKeys& other) throw();
  14099. /** Copies this object from another one. */
  14100. ModifierKeys& operator= (const ModifierKeys& other) throw();
  14101. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  14102. This is a platform-agnostic way of checking for the operating system's
  14103. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  14104. Windows/Linux, it's actually checking for the CTRL key.
  14105. */
  14106. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  14107. /** Checks whether the user is trying to launch a pop-up menu.
  14108. This checks for platform-specific modifiers that might indicate that the user
  14109. is following the operating system's normal method of showing a pop-up menu.
  14110. So on Windows/Linux, this method is really testing for a right-click.
  14111. On the Mac, it tests for either the CTRL key being down, or a right-click.
  14112. */
  14113. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  14114. /** Checks whether the flag is set for the left mouse-button. */
  14115. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  14116. /** Checks whether the flag is set for the right mouse-button.
  14117. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  14118. this is platform-independent (and makes your code more explanatory too).
  14119. */
  14120. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  14121. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  14122. /** Tests for any of the mouse-button flags. */
  14123. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  14124. /** Tests for any of the modifier key flags. */
  14125. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  14126. /** Checks whether the shift key's flag is set. */
  14127. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  14128. /** Checks whether the CTRL key's flag is set.
  14129. Remember that it's better to use the platform-agnostic routines to test for command-key and
  14130. popup-menu modifiers.
  14131. @see isCommandDown, isPopupMenu
  14132. */
  14133. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  14134. /** Checks whether the shift key's flag is set. */
  14135. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  14136. /** Flags that represent the different keys. */
  14137. enum Flags
  14138. {
  14139. /** Shift key flag. */
  14140. shiftModifier = 1,
  14141. /** CTRL key flag. */
  14142. ctrlModifier = 2,
  14143. /** ALT key flag. */
  14144. altModifier = 4,
  14145. /** Left mouse button flag. */
  14146. leftButtonModifier = 16,
  14147. /** Right mouse button flag. */
  14148. rightButtonModifier = 32,
  14149. /** Middle mouse button flag. */
  14150. middleButtonModifier = 64,
  14151. #if JUCE_MAC
  14152. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14153. commandModifier = 8,
  14154. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14155. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14156. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  14157. #else
  14158. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14159. commandModifier = ctrlModifier,
  14160. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14161. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14162. popupMenuClickModifier = rightButtonModifier,
  14163. #endif
  14164. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  14165. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  14166. /** Represents a combination of all the mouse buttons at once. */
  14167. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  14168. };
  14169. /** Returns a copy of only the mouse-button flags */
  14170. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  14171. /** Returns a copy of only the non-mouse flags */
  14172. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  14173. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  14174. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  14175. /** Returns the raw flags for direct testing. */
  14176. inline int getRawFlags() const throw() { return flags; }
  14177. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  14178. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  14179. /** Tests a combination of flags and returns true if any of them are set. */
  14180. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14181. /** Returns the total number of mouse buttons that are down. */
  14182. int getNumMouseButtonsDown() const throw();
  14183. /** Creates a ModifierKeys object to represent the last-known state of the
  14184. keyboard and mouse buttons.
  14185. @see getCurrentModifiersRealtime
  14186. */
  14187. static const ModifierKeys getCurrentModifiers() throw();
  14188. /** Creates a ModifierKeys object to represent the current state of the
  14189. keyboard and mouse buttons.
  14190. This isn't often needed and isn't recommended, but will actively check all the
  14191. mouse and key states rather than just returning their last-known state like
  14192. getCurrentModifiers() does.
  14193. This is only needed in special circumstances for up-to-date modifier information
  14194. at times when the app's event loop isn't running normally.
  14195. */
  14196. static const ModifierKeys getCurrentModifiersRealtime() throw();
  14197. private:
  14198. int flags;
  14199. static ModifierKeys currentModifiers;
  14200. friend class ComponentPeer;
  14201. friend class MouseInputSource;
  14202. friend class MouseInputSourceInternal;
  14203. static void updateCurrentModifiers() throw();
  14204. };
  14205. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  14206. /*** End of inlined file: juce_ModifierKeys.h ***/
  14207. /*** Start of inlined file: juce_Point.h ***/
  14208. #ifndef __JUCE_POINT_JUCEHEADER__
  14209. #define __JUCE_POINT_JUCEHEADER__
  14210. /*** Start of inlined file: juce_AffineTransform.h ***/
  14211. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14212. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14213. /**
  14214. Represents a 2D affine-transformation matrix.
  14215. An affine transformation is a transformation such as a rotation, scale, shear,
  14216. resize or translation.
  14217. These are used for various 2D transformation tasks, e.g. with Path objects.
  14218. @see Path, Point, Line
  14219. */
  14220. class JUCE_API AffineTransform
  14221. {
  14222. public:
  14223. /** Creates an identity transform. */
  14224. AffineTransform() throw();
  14225. /** Creates a copy of another transform. */
  14226. AffineTransform (const AffineTransform& other) throw();
  14227. /** Creates a transform from a set of raw matrix values.
  14228. The resulting matrix is:
  14229. (mat00 mat01 mat02)
  14230. (mat10 mat11 mat12)
  14231. ( 0 0 1 )
  14232. */
  14233. AffineTransform (float mat00, float mat01, float mat02,
  14234. float mat10, float mat11, float mat12) throw();
  14235. /** Copies from another AffineTransform object */
  14236. AffineTransform& operator= (const AffineTransform& other) throw();
  14237. /** Compares two transforms. */
  14238. bool operator== (const AffineTransform& other) const throw();
  14239. /** Compares two transforms. */
  14240. bool operator!= (const AffineTransform& other) const throw();
  14241. /** A ready-to-use identity transform, which you can use to append other
  14242. transformations to.
  14243. e.g. @code
  14244. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  14245. .scaled (2.0f);
  14246. @endcode
  14247. */
  14248. static const AffineTransform identity;
  14249. /** Transforms a 2D co-ordinate using this matrix. */
  14250. void transformPoint (float& x,
  14251. float& y) const throw();
  14252. /** Transforms a 2D co-ordinate using this matrix. */
  14253. void transformPoint (double& x,
  14254. double& y) const throw();
  14255. /** Returns a new transform which is the same as this one followed by a translation. */
  14256. const AffineTransform translated (float deltaX,
  14257. float deltaY) const throw();
  14258. /** Returns a new transform which is a translation. */
  14259. static const AffineTransform translation (float deltaX,
  14260. float deltaY) throw();
  14261. /** Returns a transform which is the same as this one followed by a rotation.
  14262. The rotation is specified by a number of radians to rotate clockwise, centred around
  14263. the origin (0, 0).
  14264. */
  14265. const AffineTransform rotated (float angleInRadians) const throw();
  14266. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  14267. The rotation is specified by a number of radians to rotate clockwise, centred around
  14268. the co-ordinates passed in.
  14269. */
  14270. const AffineTransform rotated (float angleInRadians,
  14271. float pivotX,
  14272. float pivotY) const throw();
  14273. /** Returns a new transform which is a rotation about (0, 0). */
  14274. static const AffineTransform rotation (float angleInRadians) throw();
  14275. /** Returns a new transform which is a rotation about a given point. */
  14276. static const AffineTransform rotation (float angleInRadians,
  14277. float pivotX,
  14278. float pivotY) throw();
  14279. /** Returns a transform which is the same as this one followed by a re-scaling.
  14280. The scaling is centred around the origin (0, 0).
  14281. */
  14282. const AffineTransform scaled (float factorX,
  14283. float factorY) const throw();
  14284. /** Returns a new transform which is a re-scale about the origin. */
  14285. static const AffineTransform scale (float factorX,
  14286. float factorY) throw();
  14287. /** Returns a transform which is the same as this one followed by a shear.
  14288. The shear is centred around the origin (0, 0).
  14289. */
  14290. const AffineTransform sheared (float shearX,
  14291. float shearY) const throw();
  14292. /** Returns a matrix which is the inverse operation of this one.
  14293. Some matrices don't have an inverse - in this case, the method will just return
  14294. an identity transform.
  14295. */
  14296. const AffineTransform inverted() const throw();
  14297. /** Returns the transform that will map three known points onto three coordinates
  14298. that are supplied.
  14299. This returns the transform that will transform (0, 0) into (x00, y00),
  14300. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  14301. */
  14302. static const AffineTransform fromTargetPoints (float x00, float y00,
  14303. float x10, float y10,
  14304. float x01, float y01) throw();
  14305. /** Returns the result of concatenating another transformation after this one. */
  14306. const AffineTransform followedBy (const AffineTransform& other) const throw();
  14307. /** Returns true if this transform has no effect on points. */
  14308. bool isIdentity() const throw();
  14309. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  14310. bool isSingularity() const throw();
  14311. /** Returns true if the transform only translates, and doesn't scale or rotate the
  14312. points. */
  14313. bool isOnlyTranslation() const throw();
  14314. /** If this transform is only a translation, this returns the X offset.
  14315. @see isOnlyTranslation
  14316. */
  14317. float getTranslationX() const throw() { return mat02; }
  14318. /** If this transform is only a translation, this returns the X offset.
  14319. @see isOnlyTranslation
  14320. */
  14321. float getTranslationY() const throw() { return mat12; }
  14322. /* The transform matrix is:
  14323. (mat00 mat01 mat02)
  14324. (mat10 mat11 mat12)
  14325. ( 0 0 1 )
  14326. */
  14327. float mat00, mat01, mat02;
  14328. float mat10, mat11, mat12;
  14329. juce_UseDebuggingNewOperator
  14330. private:
  14331. const AffineTransform followedBy (float mat00, float mat01, float mat02,
  14332. float mat10, float mat11, float mat12) const throw();
  14333. };
  14334. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14335. /*** End of inlined file: juce_AffineTransform.h ***/
  14336. /**
  14337. A pair of (x, y) co-ordinates.
  14338. The ValueType template should be a primitive type such as int, float, double,
  14339. rather than a class.
  14340. @see Line, Path, AffineTransform
  14341. */
  14342. template <typename ValueType>
  14343. class Point
  14344. {
  14345. public:
  14346. /** Creates a point with co-ordinates (0, 0). */
  14347. Point() throw() : x (0), y (0) {}
  14348. /** Creates a copy of another point. */
  14349. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  14350. /** Creates a point from an (x, y) position. */
  14351. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  14352. /** Destructor. */
  14353. ~Point() throw() {}
  14354. /** Copies this point from another one. */
  14355. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  14356. /** Returns true if the point is (0, 0). */
  14357. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  14358. /** Returns the point's x co-ordinate. */
  14359. inline ValueType getX() const throw() { return x; }
  14360. /** Returns the point's y co-ordinate. */
  14361. inline ValueType getY() const throw() { return y; }
  14362. /** Sets the point's x co-ordinate. */
  14363. inline void setX (const ValueType newX) throw() { x = newX; }
  14364. /** Sets the point's y co-ordinate. */
  14365. inline void setY (const ValueType newY) throw() { y = newY; }
  14366. /** Returns a point which has the same Y position as this one, but a new X. */
  14367. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  14368. /** Returns a point which has the same X position as this one, but a new Y. */
  14369. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  14370. /** Changes the point's x and y co-ordinates. */
  14371. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  14372. /** Adds a pair of co-ordinates to this value. */
  14373. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  14374. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  14375. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  14376. /** Adds two points together. */
  14377. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  14378. /** Adds another point's co-ordinates to this one. */
  14379. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  14380. /** Subtracts one points from another. */
  14381. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  14382. /** Subtracts another point's co-ordinates to this one. */
  14383. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  14384. /** Returns a point whose coordinates are multiplied by a given value. */
  14385. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  14386. /** Multiplies the point's co-ordinates by a value. */
  14387. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  14388. /** Returns a point whose coordinates are divided by a given value. */
  14389. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  14390. /** Divides the point's co-ordinates by a value. */
  14391. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  14392. /** Returns the inverse of this point. */
  14393. const Point operator-() const throw() { return Point (-x, -y); }
  14394. /** Returns the straight-line distance between this point and another one. */
  14395. ValueType getDistanceFromOrigin() const throw() { return (ValueType) juce_hypot (x, y); }
  14396. /** Returns the straight-line distance between this point and another one. */
  14397. ValueType getDistanceFrom (const Point& other) const throw() { return (ValueType) juce_hypot (x - other.x, y - other.y); }
  14398. /** Returns the angle from this point to another one.
  14399. The return value is the number of radians clockwise from the 3 o'clock direction,
  14400. where this point is the centre and the other point is on the radius.
  14401. */
  14402. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  14403. /** Uses a transform to change the point's co-ordinates.
  14404. This will only compile if ValueType = float!
  14405. @see AffineTransform::transformPoint
  14406. */
  14407. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  14408. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  14409. const Point transformedBy (const AffineTransform& transform) const throw() { ValueType x2 (x), y2 (y); transform.transformPoint (x2, y2); return Point (x2, y2); }
  14410. /** Casts this point to a Point<float> object. */
  14411. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  14412. /** Returns the point as a string in the form "x, y". */
  14413. const String toString() const { return String (x) + ", " + String (y); }
  14414. juce_UseDebuggingNewOperator
  14415. private:
  14416. ValueType x, y;
  14417. };
  14418. #endif // __JUCE_POINT_JUCEHEADER__
  14419. /*** End of inlined file: juce_Point.h ***/
  14420. /**
  14421. Contains position and status information about a mouse event.
  14422. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  14423. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  14424. */
  14425. class JUCE_API MouseEvent
  14426. {
  14427. public:
  14428. /** Creates a MouseEvent.
  14429. Normally an application will never need to use this.
  14430. @param source the source that's invoking the event
  14431. @param position the position of the mouse, relative to the component that is passed-in
  14432. @param modifiers the key modifiers at the time of the event
  14433. @param originator the component that the mouse event applies to
  14434. @param eventTime the time the event happened
  14435. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  14436. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14437. the same as the current mouse-x position.
  14438. @param mouseDownTime the time at which the corresponding mouse-down event happened
  14439. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14440. the same as the current mouse-event time.
  14441. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  14442. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  14443. */
  14444. MouseEvent (MouseInputSource& source,
  14445. const Point<int>& position,
  14446. const ModifierKeys& modifiers,
  14447. Component* originator,
  14448. const Time& eventTime,
  14449. const Point<int> mouseDownPos,
  14450. const Time& mouseDownTime,
  14451. int numberOfClicks,
  14452. bool mouseWasDragged) throw();
  14453. /** Destructor. */
  14454. ~MouseEvent() throw();
  14455. /** The x-position of the mouse when the event occurred.
  14456. This value is relative to the top-left of the component to which the
  14457. event applies (as indicated by the MouseEvent::eventComponent field).
  14458. */
  14459. const int x;
  14460. /** The y-position of the mouse when the event occurred.
  14461. This value is relative to the top-left of the component to which the
  14462. event applies (as indicated by the MouseEvent::eventComponent field).
  14463. */
  14464. const int y;
  14465. /** The key modifiers associated with the event.
  14466. This will let you find out which mouse buttons were down, as well as which
  14467. modifier keys were held down.
  14468. When used for mouse-up events, this will indicate the state of the mouse buttons
  14469. just before they were released, so that you can tell which button they let go of.
  14470. */
  14471. const ModifierKeys mods;
  14472. /** The component that this event applies to.
  14473. This is usually the component that the mouse was over at the time, but for mouse-drag
  14474. events the mouse could actually be over a different component and the events are
  14475. still sent to the component that the button was originally pressed on.
  14476. The x and y member variables are relative to this component's position.
  14477. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14478. component, this pointer will be updated, but originalComponent remains unchanged.
  14479. @see originalComponent
  14480. */
  14481. Component* const eventComponent;
  14482. /** The component that the event first occurred on.
  14483. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14484. component, this value remains unchanged to indicate the first component that received it.
  14485. @see eventComponent
  14486. */
  14487. Component* const originalComponent;
  14488. /** The time that this mouse-event occurred.
  14489. */
  14490. const Time eventTime;
  14491. /** The source device that generated this event.
  14492. */
  14493. MouseInputSource& source;
  14494. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  14495. The co-ordinate is relative to the component specified in MouseEvent::component.
  14496. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14497. */
  14498. int getMouseDownX() const throw();
  14499. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  14500. The co-ordinate is relative to the component specified in MouseEvent::component.
  14501. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14502. */
  14503. int getMouseDownY() const throw();
  14504. /** Returns the co-ordinates of the last place that a mouse was pressed.
  14505. The co-ordinates are relative to the component specified in MouseEvent::component.
  14506. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14507. */
  14508. const Point<int> getMouseDownPosition() const throw();
  14509. /** Returns the straight-line distance between where the mouse is now and where it
  14510. was the last time the button was pressed.
  14511. This is quite handy for things like deciding whether the user has moved far enough
  14512. for it to be considered a drag operation.
  14513. @see getDistanceFromDragStartX
  14514. */
  14515. int getDistanceFromDragStart() const throw();
  14516. /** Returns the difference between the mouse's current x postion and where it was
  14517. when the button was last pressed.
  14518. @see getDistanceFromDragStart
  14519. */
  14520. int getDistanceFromDragStartX() const throw();
  14521. /** Returns the difference between the mouse's current y postion and where it was
  14522. when the button was last pressed.
  14523. @see getDistanceFromDragStart
  14524. */
  14525. int getDistanceFromDragStartY() const throw();
  14526. /** Returns the difference between the mouse's current postion and where it was
  14527. when the button was last pressed.
  14528. @see getDistanceFromDragStart
  14529. */
  14530. const Point<int> getOffsetFromDragStart() const throw();
  14531. /** Returns true if the mouse has just been clicked.
  14532. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  14533. the user has dragged the mouse more than a few pixels from the place where the
  14534. mouse-down occurred.
  14535. Once they have dragged it far enough for this method to return false, it will continue
  14536. to return false until the mouse-up, even if they move the mouse back to the same
  14537. position where they originally pressed it. This means that it's very handy for
  14538. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  14539. callback to ignore any small movements they might make while clicking.
  14540. @returns true if the mouse wasn't dragged by more than a few pixels between
  14541. the last time the button was pressed and released.
  14542. */
  14543. bool mouseWasClicked() const throw();
  14544. /** For a click event, the number of times the mouse was clicked in succession.
  14545. So for example a double-click event will return 2, a triple-click 3, etc.
  14546. */
  14547. int getNumberOfClicks() const throw() { return numberOfClicks; }
  14548. /** Returns the time that the mouse button has been held down for.
  14549. If called from a mouseDrag or mouseUp callback, this will return the
  14550. number of milliseconds since the corresponding mouseDown event occurred.
  14551. If called in other contexts, e.g. a mouseMove, then the returned value
  14552. may be 0 or an undefined value.
  14553. */
  14554. int getLengthOfMousePress() const throw();
  14555. /** The position of the mouse when the event occurred.
  14556. This position is relative to the top-left of the component to which the
  14557. event applies (as indicated by the MouseEvent::eventComponent field).
  14558. */
  14559. const Point<int> getPosition() const throw();
  14560. /** Returns the mouse x position of this event, in global screen co-ordinates.
  14561. The co-ordinates are relative to the top-left of the main monitor.
  14562. @see getScreenPosition
  14563. */
  14564. int getScreenX() const;
  14565. /** Returns the mouse y position of this event, in global screen co-ordinates.
  14566. The co-ordinates are relative to the top-left of the main monitor.
  14567. @see getScreenPosition
  14568. */
  14569. int getScreenY() const;
  14570. /** Returns the mouse position of this event, in global screen co-ordinates.
  14571. The co-ordinates are relative to the top-left of the main monitor.
  14572. @see getMouseDownScreenPosition
  14573. */
  14574. const Point<int> getScreenPosition() const;
  14575. /** Returns the x co-ordinate at which the mouse button was last pressed.
  14576. The co-ordinates are relative to the top-left of the main monitor.
  14577. @see getMouseDownScreenPosition
  14578. */
  14579. int getMouseDownScreenX() const;
  14580. /** Returns the y co-ordinate at which the mouse button was last pressed.
  14581. The co-ordinates are relative to the top-left of the main monitor.
  14582. @see getMouseDownScreenPosition
  14583. */
  14584. int getMouseDownScreenY() const;
  14585. /** Returns the co-ordinates at which the mouse button was last pressed.
  14586. The co-ordinates are relative to the top-left of the main monitor.
  14587. @see getScreenPosition
  14588. */
  14589. const Point<int> getMouseDownScreenPosition() const;
  14590. /** Creates a version of this event that is relative to a different component.
  14591. The x and y positions of the event that is returned will have been
  14592. adjusted to be relative to the new component.
  14593. */
  14594. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  14595. /** Creates a copy of this event with a different position.
  14596. All other members of the event object are the same, but the x and y are
  14597. replaced with these new values.
  14598. */
  14599. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  14600. /** Changes the application-wide setting for the double-click time limit.
  14601. This is the maximum length of time between mouse-clicks for it to be
  14602. considered a double-click. It's used by the Component class.
  14603. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  14604. */
  14605. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  14606. /** Returns the application-wide setting for the double-click time limit.
  14607. This is the maximum length of time between mouse-clicks for it to be
  14608. considered a double-click. It's used by the Component class.
  14609. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  14610. */
  14611. static int getDoubleClickTimeout() throw();
  14612. juce_UseDebuggingNewOperator
  14613. private:
  14614. const Point<int> mouseDownPos;
  14615. const Time mouseDownTime;
  14616. const int numberOfClicks;
  14617. const bool wasMovedSinceMouseDown;
  14618. MouseEvent& operator= (const MouseEvent&);
  14619. };
  14620. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  14621. /*** End of inlined file: juce_MouseEvent.h ***/
  14622. /*** Start of inlined file: juce_ComponentListener.h ***/
  14623. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14624. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14625. class Component;
  14626. /**
  14627. Gets informed about changes to a component's hierarchy or position.
  14628. To monitor a component for changes, register a subclass of ComponentListener
  14629. with the component using Component::addComponentListener().
  14630. Be sure to deregister listeners before you delete them!
  14631. @see Component::addComponentListener, Component::removeComponentListener
  14632. */
  14633. class JUCE_API ComponentListener
  14634. {
  14635. public:
  14636. /** Destructor. */
  14637. virtual ~ComponentListener() {}
  14638. /** Called when the component's position or size changes.
  14639. @param component the component that was moved or resized
  14640. @param wasMoved true if the component's top-left corner has just moved
  14641. @param wasResized true if the component's width or height has just changed
  14642. @see Component::setBounds, Component::resized, Component::moved
  14643. */
  14644. virtual void componentMovedOrResized (Component& component,
  14645. bool wasMoved,
  14646. bool wasResized);
  14647. /** Called when the component is brought to the top of the z-order.
  14648. @param component the component that was moved
  14649. @see Component::toFront, Component::broughtToFront
  14650. */
  14651. virtual void componentBroughtToFront (Component& component);
  14652. /** Called when the component is made visible or invisible.
  14653. @param component the component that changed
  14654. @see Component::setVisible
  14655. */
  14656. virtual void componentVisibilityChanged (Component& component);
  14657. /** Called when the component has children added or removed.
  14658. @param component the component whose children were changed
  14659. @see Component::childrenChanged, Component::addChildComponent,
  14660. Component::removeChildComponent
  14661. */
  14662. virtual void componentChildrenChanged (Component& component);
  14663. /** Called to indicate that the component's parents have changed.
  14664. When a component is added or removed from its parent, all of its children
  14665. will produce this notification (recursively - so all children of its
  14666. children will also be called as well).
  14667. @param component the component that this listener is registered with
  14668. @see Component::parentHierarchyChanged
  14669. */
  14670. virtual void componentParentHierarchyChanged (Component& component);
  14671. /** Called when the component's name is changed.
  14672. @see Component::setName, Component::getName
  14673. */
  14674. virtual void componentNameChanged (Component& component);
  14675. /** Called when the component is in the process of being deleted.
  14676. This callback is made from inside the destructor, so be very, very cautious
  14677. about what you do inside the callback.
  14678. It will be called before the component has been removed from its parent, and
  14679. before any child components have been removed.
  14680. */
  14681. virtual void componentBeingDeleted (Component& component);
  14682. };
  14683. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14684. /*** End of inlined file: juce_ComponentListener.h ***/
  14685. /*** Start of inlined file: juce_KeyListener.h ***/
  14686. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  14687. #define __JUCE_KEYLISTENER_JUCEHEADER__
  14688. /*** Start of inlined file: juce_KeyPress.h ***/
  14689. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  14690. #define __JUCE_KEYPRESS_JUCEHEADER__
  14691. /**
  14692. Represents a key press, including any modifier keys that are needed.
  14693. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  14694. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  14695. */
  14696. class JUCE_API KeyPress
  14697. {
  14698. public:
  14699. /** Creates an (invalid) KeyPress.
  14700. @see isValid
  14701. */
  14702. KeyPress() throw();
  14703. /** Creates a KeyPress for a key and some modifiers.
  14704. e.g.
  14705. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  14706. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  14707. @param keyCode a code that represents the key - this value must be
  14708. one of special constants listed in this class, or an
  14709. 8-bit character code such as a letter (case is ignored),
  14710. digit or a simple key like "," or ".". Note that this
  14711. isn't the same as the textCharacter parameter, so for example
  14712. a keyCode of 'a' and a shift-key modifier should have a
  14713. textCharacter value of 'A'.
  14714. @param modifiers the modifiers to associate with the keystroke
  14715. @param textCharacter the character that would be printed if someone typed
  14716. this keypress into a text editor. This value may be
  14717. null if the keypress is a non-printing character
  14718. @see getKeyCode, isKeyCode, getModifiers
  14719. */
  14720. KeyPress (int keyCode,
  14721. const ModifierKeys& modifiers,
  14722. juce_wchar textCharacter) throw();
  14723. /** Creates a keypress with a keyCode but no modifiers or text character.
  14724. */
  14725. KeyPress (int keyCode) throw();
  14726. /** Creates a copy of another KeyPress. */
  14727. KeyPress (const KeyPress& other) throw();
  14728. /** Copies this KeyPress from another one. */
  14729. KeyPress& operator= (const KeyPress& other) throw();
  14730. /** Compares two KeyPress objects. */
  14731. bool operator== (const KeyPress& other) const throw();
  14732. /** Compares two KeyPress objects. */
  14733. bool operator!= (const KeyPress& other) const throw();
  14734. /** Returns true if this is a valid KeyPress.
  14735. A null keypress can be created by the default constructor, in case it's
  14736. needed.
  14737. */
  14738. bool isValid() const throw() { return keyCode != 0; }
  14739. /** Returns the key code itself.
  14740. This will either be one of the special constants defined in this class,
  14741. or an 8-bit character code.
  14742. */
  14743. int getKeyCode() const throw() { return keyCode; }
  14744. /** Returns the key modifiers.
  14745. @see ModifierKeys
  14746. */
  14747. const ModifierKeys getModifiers() const throw() { return mods; }
  14748. /** Returns the character that is associated with this keypress.
  14749. This is the character that you'd expect to see printed if you press this
  14750. keypress in a text editor or similar component.
  14751. */
  14752. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  14753. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  14754. the modifiers.
  14755. The values for key codes can either be one of the special constants defined in
  14756. this class, or an 8-bit character code.
  14757. @see getKeyCode
  14758. */
  14759. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  14760. /** Converts a textual key description to a KeyPress.
  14761. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  14762. This isn't designed to cope with any kind of input, but should be given the
  14763. strings that are created by the getTextDescription() method.
  14764. If the string can't be parsed, the object returned will be invalid.
  14765. @see getTextDescription
  14766. */
  14767. static const KeyPress createFromDescription (const String& textVersion);
  14768. /** Creates a textual description of the key combination.
  14769. e.g. "CTRL + C" or "DELETE".
  14770. To store a keypress in a file, use this method, along with createFromDescription()
  14771. to retrieve it later.
  14772. */
  14773. const String getTextDescription() const;
  14774. /** Checks whether the user is currently holding down the keys that make up this
  14775. KeyPress.
  14776. Note that this will return false if any extra modifier keys are
  14777. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  14778. then it will be false.
  14779. */
  14780. bool isCurrentlyDown() const;
  14781. /** Checks whether a particular key is held down, irrespective of modifiers.
  14782. The values for key codes can either be one of the special constants defined in
  14783. this class, or an 8-bit character code.
  14784. */
  14785. static bool isKeyCurrentlyDown (int keyCode);
  14786. // Key codes
  14787. //
  14788. // Note that the actual values of these are platform-specific and may change
  14789. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  14790. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  14791. //
  14792. static const int spaceKey; /**< key-code for the space bar */
  14793. static const int escapeKey; /**< key-code for the escape key */
  14794. static const int returnKey; /**< key-code for the return key*/
  14795. static const int tabKey; /**< key-code for the tab key*/
  14796. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  14797. static const int backspaceKey; /**< key-code for the backspace key */
  14798. static const int insertKey; /**< key-code for the insert key */
  14799. static const int upKey; /**< key-code for the cursor-up key */
  14800. static const int downKey; /**< key-code for the cursor-down key */
  14801. static const int leftKey; /**< key-code for the cursor-left key */
  14802. static const int rightKey; /**< key-code for the cursor-right key */
  14803. static const int pageUpKey; /**< key-code for the page-up key */
  14804. static const int pageDownKey; /**< key-code for the page-down key */
  14805. static const int homeKey; /**< key-code for the home key */
  14806. static const int endKey; /**< key-code for the end key */
  14807. static const int F1Key; /**< key-code for the F1 key */
  14808. static const int F2Key; /**< key-code for the F2 key */
  14809. static const int F3Key; /**< key-code for the F3 key */
  14810. static const int F4Key; /**< key-code for the F4 key */
  14811. static const int F5Key; /**< key-code for the F5 key */
  14812. static const int F6Key; /**< key-code for the F6 key */
  14813. static const int F7Key; /**< key-code for the F7 key */
  14814. static const int F8Key; /**< key-code for the F8 key */
  14815. static const int F9Key; /**< key-code for the F9 key */
  14816. static const int F10Key; /**< key-code for the F10 key */
  14817. static const int F11Key; /**< key-code for the F11 key */
  14818. static const int F12Key; /**< key-code for the F12 key */
  14819. static const int F13Key; /**< key-code for the F13 key */
  14820. static const int F14Key; /**< key-code for the F14 key */
  14821. static const int F15Key; /**< key-code for the F15 key */
  14822. static const int F16Key; /**< key-code for the F16 key */
  14823. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  14824. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  14825. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  14826. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  14827. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  14828. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  14829. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  14830. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  14831. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  14832. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  14833. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  14834. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  14835. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  14836. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  14837. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  14838. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  14839. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  14840. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  14841. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  14842. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  14843. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  14844. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  14845. juce_UseDebuggingNewOperator
  14846. private:
  14847. int keyCode;
  14848. ModifierKeys mods;
  14849. juce_wchar textCharacter;
  14850. };
  14851. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  14852. /*** End of inlined file: juce_KeyPress.h ***/
  14853. class Component;
  14854. /**
  14855. Receives callbacks when keys are pressed.
  14856. You can add a key listener to a component to be informed when that component
  14857. gets key events. See the Component::addListener method for more details.
  14858. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  14859. */
  14860. class JUCE_API KeyListener
  14861. {
  14862. public:
  14863. /** Destructor. */
  14864. virtual ~KeyListener() {}
  14865. /** Called to indicate that a key has been pressed.
  14866. If your implementation returns true, then the key event is considered to have
  14867. been consumed, and will not be passed on to any other components. If it returns
  14868. false, then the key will be passed to other components that might want to use it.
  14869. @param key the keystroke, including modifier keys
  14870. @param originatingComponent the component that received the key event
  14871. @see keyStateChanged, Component::keyPressed
  14872. */
  14873. virtual bool keyPressed (const KeyPress& key,
  14874. Component* originatingComponent) = 0;
  14875. /** Called when any key is pressed or released.
  14876. When this is called, classes that might be interested in
  14877. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  14878. check whether their key has changed.
  14879. If your implementation returns true, then the key event is considered to have
  14880. been consumed, and will not be passed on to any other components. If it returns
  14881. false, then the key will be passed to other components that might want to use it.
  14882. @param originatingComponent the component that received the key event
  14883. @param isKeyDown true if a key is being pressed, false if one is being released
  14884. @see KeyPress, Component::keyStateChanged
  14885. */
  14886. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  14887. };
  14888. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  14889. /*** End of inlined file: juce_KeyListener.h ***/
  14890. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  14891. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  14892. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  14893. class Component;
  14894. /**
  14895. Controls the order in which focus moves between components.
  14896. The default algorithm used by this class to work out the order of traversal
  14897. is as follows:
  14898. - if two components both have an explicit focus order specified, then the
  14899. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  14900. method).
  14901. - any component with an explicit focus order greater than 0 comes before ones
  14902. that don't have an order specified.
  14903. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  14904. order.
  14905. If you need traversal in a more customised way, you can create a subclass
  14906. of KeyboardFocusTraverser that uses your own algorithm, and use
  14907. Component::createFocusTraverser() to create it.
  14908. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  14909. */
  14910. class JUCE_API KeyboardFocusTraverser
  14911. {
  14912. public:
  14913. KeyboardFocusTraverser();
  14914. /** Destructor. */
  14915. virtual ~KeyboardFocusTraverser();
  14916. /** Returns the component that should be given focus after the specified one
  14917. when moving "forwards".
  14918. The default implementation will return the next component which is to the
  14919. right of or below this one.
  14920. This may return 0 if there's no suitable candidate.
  14921. */
  14922. virtual Component* getNextComponent (Component* current);
  14923. /** Returns the component that should be given focus after the specified one
  14924. when moving "backwards".
  14925. The default implementation will return the next component which is to the
  14926. left of or above this one.
  14927. This may return 0 if there's no suitable candidate.
  14928. */
  14929. virtual Component* getPreviousComponent (Component* current);
  14930. /** Returns the component that should receive focus be default within the given
  14931. parent component.
  14932. The default implementation will just return the foremost child component that
  14933. wants focus.
  14934. This may return 0 if there's no suitable candidate.
  14935. */
  14936. virtual Component* getDefaultComponent (Component* parentComponent);
  14937. };
  14938. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  14939. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  14940. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  14941. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  14942. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  14943. /*** Start of inlined file: juce_Graphics.h ***/
  14944. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  14945. #define __JUCE_GRAPHICS_JUCEHEADER__
  14946. /*** Start of inlined file: juce_Font.h ***/
  14947. #ifndef __JUCE_FONT_JUCEHEADER__
  14948. #define __JUCE_FONT_JUCEHEADER__
  14949. /*** Start of inlined file: juce_Typeface.h ***/
  14950. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  14951. #define __JUCE_TYPEFACE_JUCEHEADER__
  14952. /*** Start of inlined file: juce_Path.h ***/
  14953. #ifndef __JUCE_PATH_JUCEHEADER__
  14954. #define __JUCE_PATH_JUCEHEADER__
  14955. /*** Start of inlined file: juce_Line.h ***/
  14956. #ifndef __JUCE_LINE_JUCEHEADER__
  14957. #define __JUCE_LINE_JUCEHEADER__
  14958. /**
  14959. Represents a line.
  14960. This class contains a bunch of useful methods for various geometric
  14961. tasks.
  14962. The ValueType template parameter should be a primitive type - float or double
  14963. are what it's designed for. Integer types will work in a basic way, but some methods
  14964. that perform mathematical operations may not compile, or they may not produce
  14965. sensible results.
  14966. @see Point, Rectangle, Path, Graphics::drawLine
  14967. */
  14968. template <typename ValueType>
  14969. class Line
  14970. {
  14971. public:
  14972. /** Creates a line, using (0, 0) as its start and end points. */
  14973. Line() throw() {}
  14974. /** Creates a copy of another line. */
  14975. Line (const Line& other) throw()
  14976. : start (other.start),
  14977. end (other.end)
  14978. {
  14979. }
  14980. /** Creates a line based on the co-ordinates of its start and end points. */
  14981. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  14982. : start (startX, startY),
  14983. end (endX, endY)
  14984. {
  14985. }
  14986. /** Creates a line from its start and end points. */
  14987. Line (const Point<ValueType>& startPoint,
  14988. const Point<ValueType>& endPoint) throw()
  14989. : start (startPoint),
  14990. end (endPoint)
  14991. {
  14992. }
  14993. /** Copies a line from another one. */
  14994. Line& operator= (const Line& other) throw()
  14995. {
  14996. start = other.start;
  14997. end = other.end;
  14998. return *this;
  14999. }
  15000. /** Destructor. */
  15001. ~Line() throw() {}
  15002. /** Returns the x co-ordinate of the line's start point. */
  15003. inline ValueType getStartX() const throw() { return start.getX(); }
  15004. /** Returns the y co-ordinate of the line's start point. */
  15005. inline ValueType getStartY() const throw() { return start.getY(); }
  15006. /** Returns the x co-ordinate of the line's end point. */
  15007. inline ValueType getEndX() const throw() { return end.getX(); }
  15008. /** Returns the y co-ordinate of the line's end point. */
  15009. inline ValueType getEndY() const throw() { return end.getY(); }
  15010. /** Returns the line's start point. */
  15011. inline const Point<ValueType>& getStart() const throw() { return start; }
  15012. /** Returns the line's end point. */
  15013. inline const Point<ValueType>& getEnd() const throw() { return end; }
  15014. /** Changes this line's start point */
  15015. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  15016. /** Changes this line's end point */
  15017. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  15018. /** Changes this line's start point */
  15019. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  15020. /** Changes this line's end point */
  15021. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  15022. /** Applies an affine transform to the line's start and end points. */
  15023. void applyTransform (const AffineTransform& transform) throw()
  15024. {
  15025. start.applyTransform (transform);
  15026. end.applyTransform (transform);
  15027. }
  15028. /** Returns the length of the line. */
  15029. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  15030. /** Returns true if the line's start and end x co-ordinates are the same. */
  15031. bool isVertical() const throw() { return start.getX() == end.getX(); }
  15032. /** Returns true if the line's start and end y co-ordinates are the same. */
  15033. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  15034. /** Returns the line's angle.
  15035. This value is the number of radians clockwise from the 3 o'clock direction,
  15036. where the line's start point is considered to be at the centre.
  15037. */
  15038. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  15039. /** Compares two lines. */
  15040. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  15041. /** Compares two lines. */
  15042. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  15043. /** Finds the intersection between two lines.
  15044. @param line the other line
  15045. @param intersection the position of the point where the lines meet (or
  15046. where they would meet if they were infinitely long)
  15047. the intersection (if the lines intersect). If the lines
  15048. are parallel, this will just be set to the position
  15049. of one of the line's endpoints.
  15050. @returns true if the line segments intersect; false if they dont. Even if they
  15051. don't intersect, the intersection co-ordinates returned will still
  15052. be valid
  15053. */
  15054. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  15055. {
  15056. return findIntersection (start, end, line.start, line.end, intersection);
  15057. }
  15058. /** Returns the location of the point which is a given distance along this line.
  15059. @param distanceFromStart the distance to move along the line from its
  15060. start point. This value can be negative or longer
  15061. than the line itself
  15062. @see getPointAlongLineProportionally
  15063. */
  15064. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  15065. {
  15066. return start + (end - start) * (distanceFromStart / getLength());
  15067. }
  15068. /** Returns a point which is a certain distance along and to the side of this line.
  15069. This effectively moves a given distance along the line, then another distance
  15070. perpendicularly to this, and returns the resulting position.
  15071. @param distanceFromStart the distance to move along the line from its
  15072. start point. This value can be negative or longer
  15073. than the line itself
  15074. @param perpendicularDistance how far to move sideways from the line. If you're
  15075. looking along the line from its start towards its
  15076. end, then a positive value here will move to the
  15077. right, negative value move to the left.
  15078. */
  15079. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  15080. ValueType perpendicularDistance) const throw()
  15081. {
  15082. const Point<ValueType> delta (end - start);
  15083. const double length = juce_hypot (delta.getX(), delta.getY());
  15084. if (length == 0)
  15085. return start;
  15086. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  15087. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  15088. }
  15089. /** Returns the location of the point which is a given distance along this line
  15090. proportional to the line's length.
  15091. @param proportionOfLength the distance to move along the line from its
  15092. start point, in multiples of the line's length.
  15093. So a value of 0.0 will return the line's start point
  15094. and a value of 1.0 will return its end point. (This value
  15095. can be negative or greater than 1.0).
  15096. @see getPointAlongLine
  15097. */
  15098. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  15099. {
  15100. return start + (end - start) * proportionOfLength;
  15101. }
  15102. /** Returns the smallest distance between this line segment and a given point.
  15103. So if the point is close to the line, this will return the perpendicular
  15104. distance from the line; if the point is a long way beyond one of the line's
  15105. end-point's, it'll return the straight-line distance to the nearest end-point.
  15106. @returns the point's distance from the line
  15107. @see getPositionAlongLineOfNearestPoint
  15108. */
  15109. ValueType getDistanceFromLine (const Point<ValueType>& point) const throw()
  15110. {
  15111. const Point<ValueType> delta (end - start);
  15112. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15113. if (length > 0)
  15114. {
  15115. const double prop = ((point.getX() - start.getX()) * delta.getX()
  15116. + (point.getY() - start.getY()) * delta.getY()) / length;
  15117. if (prop >= 0 && prop <= 1.0)
  15118. return point.getDistanceFrom (start + delta * (ValueType) prop);
  15119. }
  15120. return jmin (point.getDistanceFrom (start),
  15121. point.getDistanceFrom (end));
  15122. }
  15123. /** Finds the point on this line which is nearest to a given point, and
  15124. returns its position as a proportional position along the line.
  15125. @returns a value 0 to 1.0 which is the distance along this line from the
  15126. line's start to the point which is nearest to the point passed-in. To
  15127. turn this number into a position, use getPointAlongLineProportionally().
  15128. @see getDistanceFromLine, getPointAlongLineProportionally
  15129. */
  15130. ValueType findNearestPointTo (const Point<ValueType>& point) const throw()
  15131. {
  15132. const Point<ValueType> delta (end - start);
  15133. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15134. return length <= 0 ? 0
  15135. : jlimit ((ValueType) 0, (ValueType) 1,
  15136. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  15137. + (point.getY() - start.getY()) * delta.getY()) / length));
  15138. }
  15139. /** Returns true if the given point lies above this line.
  15140. The return value is true if the point's y coordinate is less than the y
  15141. coordinate of this line at the given x (assuming the line extends infinitely
  15142. in both directions).
  15143. */
  15144. bool isPointAbove (const Point<ValueType>& point) const throw()
  15145. {
  15146. return start.getX() != end.getX()
  15147. && point.getY() < ((end.getY() - start.getY())
  15148. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  15149. }
  15150. /** Returns a shortened copy of this line.
  15151. This will chop off part of the start of this line by a certain amount, (leaving the
  15152. end-point the same), and return the new line.
  15153. */
  15154. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  15155. {
  15156. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  15157. }
  15158. /** Returns a shortened copy of this line.
  15159. This will chop off part of the end of this line by a certain amount, (leaving the
  15160. start-point the same), and return the new line.
  15161. */
  15162. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  15163. {
  15164. const ValueType length = getLength();
  15165. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  15166. }
  15167. juce_UseDebuggingNewOperator
  15168. private:
  15169. Point<ValueType> start, end;
  15170. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  15171. const Point<ValueType>& p3, const Point<ValueType>& p4,
  15172. Point<ValueType>& intersection) throw()
  15173. {
  15174. if (p2 == p3)
  15175. {
  15176. intersection = p2;
  15177. return true;
  15178. }
  15179. const Point<ValueType> d1 (p2 - p1);
  15180. const Point<ValueType> d2 (p4 - p3);
  15181. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  15182. if (divisor == 0)
  15183. {
  15184. if (! (d1.isOrigin() || d2.isOrigin()))
  15185. {
  15186. if (d1.getY() == 0 && d2.getY() != 0)
  15187. {
  15188. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  15189. intersection = p1.withX (p3.getX() + along * d2.getX());
  15190. return along >= 0 && along <= (ValueType) 1;
  15191. }
  15192. else if (d2.getY() == 0 && d1.getY() != 0)
  15193. {
  15194. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  15195. intersection = p3.withX (p1.getX() + along * d1.getX());
  15196. return along >= 0 && along <= (ValueType) 1;
  15197. }
  15198. else if (d1.getX() == 0 && d2.getX() != 0)
  15199. {
  15200. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  15201. intersection = p1.withY (p3.getY() + along * d2.getY());
  15202. return along >= 0 && along <= (ValueType) 1;
  15203. }
  15204. else if (d2.getX() == 0 && d1.getX() != 0)
  15205. {
  15206. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  15207. intersection = p3.withY (p1.getY() + along * d1.getY());
  15208. return along >= 0 && along <= (ValueType) 1;
  15209. }
  15210. }
  15211. intersection = (p2 + p3) / (ValueType) 2;
  15212. return false;
  15213. }
  15214. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  15215. intersection = p1 + d1 * along1;
  15216. if (along1 < 0 || along1 > (ValueType) 1)
  15217. return false;
  15218. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  15219. return along2 >= 0 && along2 <= (ValueType) 1;
  15220. }
  15221. };
  15222. #endif // __JUCE_LINE_JUCEHEADER__
  15223. /*** End of inlined file: juce_Line.h ***/
  15224. /*** Start of inlined file: juce_Rectangle.h ***/
  15225. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  15226. #define __JUCE_RECTANGLE_JUCEHEADER__
  15227. class RectangleList;
  15228. /**
  15229. Manages a rectangle and allows geometric operations to be performed on it.
  15230. @see RectangleList, Path, Line, Point
  15231. */
  15232. template <typename ValueType>
  15233. class Rectangle
  15234. {
  15235. public:
  15236. /** Creates a rectangle of zero size.
  15237. The default co-ordinates will be (0, 0, 0, 0).
  15238. */
  15239. Rectangle() throw()
  15240. : x (0), y (0), w (0), h (0)
  15241. {
  15242. }
  15243. /** Creates a copy of another rectangle. */
  15244. Rectangle (const Rectangle& other) throw()
  15245. : x (other.x), y (other.y),
  15246. w (other.w), h (other.h)
  15247. {
  15248. }
  15249. /** Creates a rectangle with a given position and size. */
  15250. Rectangle (const ValueType initialX, const ValueType initialY,
  15251. const ValueType width, const ValueType height) throw()
  15252. : x (initialX), y (initialY),
  15253. w (width), h (height)
  15254. {
  15255. }
  15256. /** Creates a rectangle with a given size, and a position of (0, 0). */
  15257. Rectangle (const ValueType width, const ValueType height) throw()
  15258. : x (0), y (0), w (width), h (height)
  15259. {
  15260. }
  15261. /** Creates a Rectangle from the positions of two opposite corners. */
  15262. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  15263. : x (jmin (corner1.getX(), corner2.getX())),
  15264. y (jmin (corner1.getY(), corner2.getY())),
  15265. w (corner1.getX() - corner2.getX()),
  15266. h (corner1.getY() - corner2.getY())
  15267. {
  15268. if (w < 0) w = -w;
  15269. if (h < 0) h = -h;
  15270. }
  15271. Rectangle& operator= (const Rectangle& other) throw()
  15272. {
  15273. x = other.x; y = other.y;
  15274. w = other.w; h = other.h;
  15275. return *this;
  15276. }
  15277. /** Destructor. */
  15278. ~Rectangle() throw() {}
  15279. /** Returns true if the rectangle's width and height are both zero or less */
  15280. bool isEmpty() const throw() { return w <= 0 || h <= 0; }
  15281. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  15282. inline ValueType getX() const throw() { return x; }
  15283. /** Returns the y co-ordinate of the rectangle's top edge. */
  15284. inline ValueType getY() const throw() { return y; }
  15285. /** Returns the width of the rectangle. */
  15286. inline ValueType getWidth() const throw() { return w; }
  15287. /** Returns the height of the rectangle. */
  15288. inline ValueType getHeight() const throw() { return h; }
  15289. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  15290. inline ValueType getRight() const throw() { return x + w; }
  15291. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  15292. inline ValueType getBottom() const throw() { return y + h; }
  15293. /** Returns the x co-ordinate of the rectangle's centre. */
  15294. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  15295. /** Returns the y co-ordinate of the rectangle's centre. */
  15296. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  15297. /** Returns the centre point of the rectangle. */
  15298. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  15299. /** Returns the aspect ratio of the rectangle's width / height.
  15300. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  15301. it returns height / width. */
  15302. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  15303. /** Returns the rectangle's top-left position as a Point. */
  15304. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  15305. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15306. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  15307. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15308. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  15309. /** Returns a rectangle with the same size as this one, but a new position. */
  15310. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  15311. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  15312. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  15313. /** Returns a rectangle with the same position as this one, but a new size. */
  15314. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  15315. /** Changes all the rectangle's co-ordinates. */
  15316. void setBounds (const ValueType newX, const ValueType newY,
  15317. const ValueType newWidth, const ValueType newHeight) throw()
  15318. {
  15319. x = newX; y = newY; w = newWidth; h = newHeight;
  15320. }
  15321. /** Changes the rectangle's width */
  15322. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  15323. /** Changes the rectangle's height */
  15324. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  15325. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  15326. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  15327. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  15328. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  15329. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  15330. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  15331. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  15332. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  15333. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  15334. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  15335. */
  15336. void setLeft (const ValueType newLeft) throw()
  15337. {
  15338. w = jmax (ValueType(), x + w - newLeft);
  15339. x = newLeft;
  15340. }
  15341. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  15342. If the y is moved to be below the current bottom edge, the height will be set to zero.
  15343. */
  15344. void setTop (const ValueType newTop) throw()
  15345. {
  15346. h = jmax (ValueType(), y + h - newTop);
  15347. y = newTop;
  15348. }
  15349. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  15350. If the new right is below the current X value, the X will be pushed down to match it.
  15351. @see getRight
  15352. */
  15353. void setRight (const ValueType newRight) throw()
  15354. {
  15355. x = jmin (x, newRight);
  15356. w = newRight - x;
  15357. }
  15358. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  15359. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  15360. @see getBottom
  15361. */
  15362. void setBottom (const ValueType newBottom) throw()
  15363. {
  15364. y = jmin (y, newBottom);
  15365. h = newBottom - y;
  15366. }
  15367. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  15368. void translate (const ValueType deltaX,
  15369. const ValueType deltaY) throw()
  15370. {
  15371. x += deltaX;
  15372. y += deltaY;
  15373. }
  15374. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15375. const Rectangle translated (const ValueType deltaX,
  15376. const ValueType deltaY) const throw()
  15377. {
  15378. return Rectangle (x + deltaX, y + deltaY, w, h);
  15379. }
  15380. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15381. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  15382. {
  15383. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  15384. }
  15385. /** Moves this rectangle by a given amount. */
  15386. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  15387. {
  15388. x += deltaPosition.getX(); y += deltaPosition.getY();
  15389. return *this;
  15390. }
  15391. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15392. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  15393. {
  15394. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  15395. }
  15396. /** Moves this rectangle by a given amount. */
  15397. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  15398. {
  15399. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  15400. return *this;
  15401. }
  15402. /** Expands the rectangle by a given amount.
  15403. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15404. @see expanded, reduce, reduced
  15405. */
  15406. void expand (const ValueType deltaX,
  15407. const ValueType deltaY) throw()
  15408. {
  15409. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15410. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15411. setBounds (x - deltaX, y - deltaY, nw, nh);
  15412. }
  15413. /** Returns a rectangle that is larger than this one by a given amount.
  15414. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15415. @see expand, reduce, reduced
  15416. */
  15417. const Rectangle expanded (const ValueType deltaX,
  15418. const ValueType deltaY) const throw()
  15419. {
  15420. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15421. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15422. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  15423. }
  15424. /** Shrinks the rectangle by a given amount.
  15425. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15426. @see reduced, expand, expanded
  15427. */
  15428. void reduce (const ValueType deltaX,
  15429. const ValueType deltaY) throw()
  15430. {
  15431. expand (-deltaX, -deltaY);
  15432. }
  15433. /** Returns a rectangle that is smaller than this one by a given amount.
  15434. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15435. @see reduce, expand, expanded
  15436. */
  15437. const Rectangle reduced (const ValueType deltaX,
  15438. const ValueType deltaY) const throw()
  15439. {
  15440. return expanded (-deltaX, -deltaY);
  15441. }
  15442. /** Returns true if the two rectangles are identical. */
  15443. bool operator== (const Rectangle& other) const throw()
  15444. {
  15445. return x == other.x && y == other.y
  15446. && w == other.w && h == other.h;
  15447. }
  15448. /** Returns true if the two rectangles are not identical. */
  15449. bool operator!= (const Rectangle& other) const throw()
  15450. {
  15451. return x != other.x || y != other.y
  15452. || w != other.w || h != other.h;
  15453. }
  15454. /** Returns true if this co-ordinate is inside the rectangle. */
  15455. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  15456. {
  15457. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  15458. }
  15459. /** Returns true if this co-ordinate is inside the rectangle. */
  15460. bool contains (const Point<ValueType>& point) const throw()
  15461. {
  15462. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  15463. }
  15464. /** Returns true if this other rectangle is completely inside this one. */
  15465. bool contains (const Rectangle& other) const throw()
  15466. {
  15467. return x <= other.x && y <= other.y
  15468. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  15469. }
  15470. /** Returns the nearest point to the specified point that lies within this rectangle. */
  15471. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  15472. {
  15473. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  15474. jlimit (y, y + h, point.getY()));
  15475. }
  15476. /** Returns true if any part of another rectangle overlaps this one. */
  15477. bool intersects (const Rectangle& other) const throw()
  15478. {
  15479. return x + w > other.x
  15480. && y + h > other.y
  15481. && x < other.x + other.w
  15482. && y < other.y + other.h
  15483. && w > ValueType() && h > ValueType();
  15484. }
  15485. /** Returns the region that is the overlap between this and another rectangle.
  15486. If the two rectangles don't overlap, the rectangle returned will be empty.
  15487. */
  15488. const Rectangle getIntersection (const Rectangle& other) const throw()
  15489. {
  15490. const ValueType nx = jmax (x, other.x);
  15491. const ValueType ny = jmax (y, other.y);
  15492. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  15493. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  15494. if (nw >= ValueType() && nh >= ValueType())
  15495. return Rectangle (nx, ny, nw, nh);
  15496. return Rectangle();
  15497. }
  15498. /** Clips a rectangle so that it lies only within this one.
  15499. This is a non-static version of intersectRectangles().
  15500. Returns false if the two regions didn't overlap.
  15501. */
  15502. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  15503. {
  15504. const int maxX = jmax (otherX, x);
  15505. otherW = jmin (otherX + otherW, x + w) - maxX;
  15506. if (otherW > 0)
  15507. {
  15508. const int maxY = jmax (otherY, y);
  15509. otherH = jmin (otherY + otherH, y + h) - maxY;
  15510. if (otherH > 0)
  15511. {
  15512. otherX = maxX; otherY = maxY;
  15513. return true;
  15514. }
  15515. }
  15516. return false;
  15517. }
  15518. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  15519. If either this or the other rectangle are empty, they will not be counted as
  15520. part of the resulting region.
  15521. */
  15522. const Rectangle getUnion (const Rectangle& other) const throw()
  15523. {
  15524. if (other.isEmpty()) return *this;
  15525. if (isEmpty()) return other;
  15526. const ValueType newX = jmin (x, other.x);
  15527. const ValueType newY = jmin (y, other.y);
  15528. return Rectangle (newX, newY,
  15529. jmax (x + w, other.x + other.w) - newX,
  15530. jmax (y + h, other.y + other.h) - newY);
  15531. }
  15532. /** If this rectangle merged with another one results in a simple rectangle, this
  15533. will set this rectangle to the result, and return true.
  15534. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15535. or if they form a complex region.
  15536. */
  15537. bool enlargeIfAdjacent (const Rectangle& other) throw()
  15538. {
  15539. if (x == other.x && getRight() == other.getRight()
  15540. && (other.getBottom() >= y && other.y <= getBottom()))
  15541. {
  15542. const ValueType newY = jmin (y, other.y);
  15543. h = jmax (getBottom(), other.getBottom()) - newY;
  15544. y = newY;
  15545. return true;
  15546. }
  15547. else if (y == other.y && getBottom() == other.getBottom()
  15548. && (other.getRight() >= x && other.x <= getRight()))
  15549. {
  15550. const ValueType newX = jmin (x, other.x);
  15551. w = jmax (getRight(), other.getRight()) - newX;
  15552. x = newX;
  15553. return true;
  15554. }
  15555. return false;
  15556. }
  15557. /** If after removing another rectangle from this one the result is a simple rectangle,
  15558. this will set this object's bounds to be the result, and return true.
  15559. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15560. or if removing the other one would form a complex region.
  15561. */
  15562. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  15563. {
  15564. int inside = 0;
  15565. const int otherR = other.getRight();
  15566. if (x >= other.x && x < otherR) inside = 1;
  15567. const int otherB = other.getBottom();
  15568. if (y >= other.y && y < otherB) inside |= 2;
  15569. const int r = x + w;
  15570. if (r >= other.x && r < otherR) inside |= 4;
  15571. const int b = y + h;
  15572. if (b >= other.y && b < otherB) inside |= 8;
  15573. switch (inside)
  15574. {
  15575. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  15576. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  15577. case 2 + 4 + 8: w = other.x - x; return true;
  15578. case 1 + 4 + 8: h = other.y - y; return true;
  15579. }
  15580. return false;
  15581. }
  15582. /** Returns the smallest rectangle that can contain the shape created by applying
  15583. a transform to this rectangle.
  15584. This should only be used on floating point rectangles.
  15585. */
  15586. const Rectangle<ValueType> transformed (const AffineTransform& transform) const throw()
  15587. {
  15588. float x1 = x, y1 = y;
  15589. float x2 = x + w, y2 = y;
  15590. float x3 = x, y3 = y + h;
  15591. float x4 = x2, y4 = y3;
  15592. transform.transformPoint (x1, y1);
  15593. transform.transformPoint (x2, y2);
  15594. transform.transformPoint (x3, y3);
  15595. transform.transformPoint (x4, y4);
  15596. const float rx = jmin (x1, x2, x3, x4);
  15597. const float ry = jmin (y1, y2, y3, y4);
  15598. return Rectangle (rx, ry,
  15599. jmax (x1, x2, x3, x4) - rx,
  15600. jmax (y1, y2, y3, y4) - ry);
  15601. }
  15602. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  15603. This is only relevent for floating-point rectangles, of course.
  15604. @see toFloat()
  15605. */
  15606. const Rectangle<int> getSmallestIntegerContainer() const throw()
  15607. {
  15608. const int x1 = (int) std::floor (static_cast<float> (x));
  15609. const int y1 = (int) std::floor (static_cast<float> (y));
  15610. const int x2 = (int) std::floor (static_cast<float> (x + w + 0.9999f));
  15611. const int y2 = (int) std::floor (static_cast<float> (y + h + 0.9999f));
  15612. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  15613. }
  15614. /** Casts this rectangle to a Rectangle<float>.
  15615. Obviously this is mainly useful for rectangles that use integer types.
  15616. @see getSmallestIntegerContainer
  15617. */
  15618. const Rectangle<float> toFloat() const throw()
  15619. {
  15620. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  15621. static_cast<float> (w), static_cast<float> (h));
  15622. }
  15623. /** Static utility to intersect two sets of rectangular co-ordinates.
  15624. Returns false if the two regions didn't overlap.
  15625. @see intersectRectangle
  15626. */
  15627. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  15628. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  15629. {
  15630. const ValueType x = jmax (x1, x2);
  15631. w1 = jmin (x1 + w1, x2 + w2) - x;
  15632. if (w1 > 0)
  15633. {
  15634. const ValueType y = jmax (y1, y2);
  15635. h1 = jmin (y1 + h1, y2 + h2) - y;
  15636. if (h1 > 0)
  15637. {
  15638. x1 = x; y1 = y;
  15639. return true;
  15640. }
  15641. }
  15642. return false;
  15643. }
  15644. /** Creates a string describing this rectangle.
  15645. The string will be of the form "x y width height", e.g. "100 100 400 200".
  15646. Coupled with the fromString() method, this is very handy for things like
  15647. storing rectangles (particularly component positions) in XML attributes.
  15648. @see fromString
  15649. */
  15650. const String toString() const
  15651. {
  15652. String s;
  15653. s.preallocateStorage (16);
  15654. s << x << ' ' << y << ' ' << w << ' ' << h;
  15655. return s;
  15656. }
  15657. /** Parses a string containing a rectangle's details.
  15658. The string should contain 4 integer tokens, in the form "x y width height". They
  15659. can be comma or whitespace separated.
  15660. This method is intended to go with the toString() method, to form an easy way
  15661. of saving/loading rectangles as strings.
  15662. @see toString
  15663. */
  15664. static const Rectangle fromString (const String& stringVersion)
  15665. {
  15666. StringArray toks;
  15667. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  15668. return Rectangle (toks[0].trim().getIntValue(),
  15669. toks[1].trim().getIntValue(),
  15670. toks[2].trim().getIntValue(),
  15671. toks[3].trim().getIntValue());
  15672. }
  15673. juce_UseDebuggingNewOperator
  15674. private:
  15675. friend class RectangleList;
  15676. ValueType x, y, w, h;
  15677. };
  15678. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  15679. /*** End of inlined file: juce_Rectangle.h ***/
  15680. /*** Start of inlined file: juce_Justification.h ***/
  15681. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  15682. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  15683. /**
  15684. Represents a type of justification to be used when positioning graphical items.
  15685. e.g. it indicates whether something should be placed top-left, top-right,
  15686. centred, etc.
  15687. It is used in various places wherever this kind of information is needed.
  15688. */
  15689. class JUCE_API Justification
  15690. {
  15691. public:
  15692. /** Creates a Justification object using a combination of flags. */
  15693. inline Justification (int flags_) throw() : flags (flags_) {}
  15694. /** Creates a copy of another Justification object. */
  15695. Justification (const Justification& other) throw();
  15696. /** Copies another Justification object. */
  15697. Justification& operator= (const Justification& other) throw();
  15698. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  15699. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  15700. /** Returns the raw flags that are set for this Justification object. */
  15701. inline int getFlags() const throw() { return flags; }
  15702. /** Tests a set of flags for this object.
  15703. @returns true if any of the flags passed in are set on this object.
  15704. */
  15705. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  15706. /** Returns just the flags from this object that deal with vertical layout. */
  15707. int getOnlyVerticalFlags() const throw();
  15708. /** Returns just the flags from this object that deal with horizontal layout. */
  15709. int getOnlyHorizontalFlags() const throw();
  15710. /** Adjusts the position of a rectangle to fit it into a space.
  15711. The (x, y) position of the rectangle will be updated to position it inside the
  15712. given space according to the justification flags.
  15713. */
  15714. void applyToRectangle (int& x, int& y, int w, int h,
  15715. int spaceX, int spaceY, int spaceW, int spaceH) const throw();
  15716. /** Flag values that can be combined and used in the constructor. */
  15717. enum
  15718. {
  15719. /** Indicates that the item should be aligned against the left edge of the available space. */
  15720. left = 1,
  15721. /** Indicates that the item should be aligned against the right edge of the available space. */
  15722. right = 2,
  15723. /** Indicates that the item should be placed in the centre between the left and right
  15724. sides of the available space. */
  15725. horizontallyCentred = 4,
  15726. /** Indicates that the item should be aligned against the top edge of the available space. */
  15727. top = 8,
  15728. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  15729. bottom = 16,
  15730. /** Indicates that the item should be placed in the centre between the top and bottom
  15731. sides of the available space. */
  15732. verticallyCentred = 32,
  15733. /** Indicates that lines of text should be spread out to fill the maximum width
  15734. available, so that both margins are aligned vertically.
  15735. */
  15736. horizontallyJustified = 64,
  15737. /** Indicates that the item should be centred vertically and horizontally.
  15738. This is equivalent to (horizontallyCentred | verticallyCentred)
  15739. */
  15740. centred = 36,
  15741. /** Indicates that the item should be centred vertically but placed on the left hand side.
  15742. This is equivalent to (left | verticallyCentred)
  15743. */
  15744. centredLeft = 33,
  15745. /** Indicates that the item should be centred vertically but placed on the right hand side.
  15746. This is equivalent to (right | verticallyCentred)
  15747. */
  15748. centredRight = 34,
  15749. /** Indicates that the item should be centred horizontally and placed at the top.
  15750. This is equivalent to (horizontallyCentred | top)
  15751. */
  15752. centredTop = 12,
  15753. /** Indicates that the item should be centred horizontally and placed at the bottom.
  15754. This is equivalent to (horizontallyCentred | bottom)
  15755. */
  15756. centredBottom = 20,
  15757. /** Indicates that the item should be placed in the top-left corner.
  15758. This is equivalent to (left | top)
  15759. */
  15760. topLeft = 9,
  15761. /** Indicates that the item should be placed in the top-right corner.
  15762. This is equivalent to (right | top)
  15763. */
  15764. topRight = 10,
  15765. /** Indicates that the item should be placed in the bottom-left corner.
  15766. This is equivalent to (left | bottom)
  15767. */
  15768. bottomLeft = 17,
  15769. /** Indicates that the item should be placed in the bottom-left corner.
  15770. This is equivalent to (right | bottom)
  15771. */
  15772. bottomRight = 18
  15773. };
  15774. private:
  15775. int flags;
  15776. };
  15777. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  15778. /*** End of inlined file: juce_Justification.h ***/
  15779. class Image;
  15780. /**
  15781. A path is a sequence of lines and curves that may either form a closed shape
  15782. or be open-ended.
  15783. To use a path, you can create an empty one, then add lines and curves to it
  15784. to create shapes, then it can be rendered by a Graphics context or used
  15785. for geometric operations.
  15786. e.g. @code
  15787. Path myPath;
  15788. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  15789. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  15790. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  15791. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  15792. // add an ellipse as well, which will form a second sub-path within the path..
  15793. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  15794. // double the width of the whole thing..
  15795. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  15796. // and draw it to a graphics context with a 5-pixel thick outline.
  15797. g.strokePath (myPath, PathStrokeType (5.0f));
  15798. @endcode
  15799. A path object can actually contain multiple sub-paths, which may themselves
  15800. be open or closed.
  15801. @see PathFlatteningIterator, PathStrokeType, Graphics
  15802. */
  15803. class JUCE_API Path
  15804. {
  15805. public:
  15806. /** Creates an empty path. */
  15807. Path();
  15808. /** Creates a copy of another path. */
  15809. Path (const Path& other);
  15810. /** Destructor. */
  15811. ~Path();
  15812. /** Copies this path from another one. */
  15813. Path& operator= (const Path& other);
  15814. bool operator== (const Path& other) const throw();
  15815. bool operator!= (const Path& other) const throw();
  15816. /** Returns true if the path doesn't contain any lines or curves. */
  15817. bool isEmpty() const throw();
  15818. /** Returns the smallest rectangle that contains all points within the path.
  15819. */
  15820. const Rectangle<float> getBounds() const throw();
  15821. /** Returns the smallest rectangle that contains all points within the path
  15822. after it's been transformed with the given tranasform matrix.
  15823. */
  15824. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  15825. /** Checks whether a point lies within the path.
  15826. This is only relevent for closed paths (see closeSubPath()), and
  15827. may produce false results if used on a path which has open sub-paths.
  15828. The path's winding rule is taken into account by this method.
  15829. The tolerence parameter is passed to the PathFlatteningIterator that
  15830. is used to trace the path - for more info about it, see the notes for
  15831. the PathFlatteningIterator constructor.
  15832. @see closeSubPath, setUsingNonZeroWinding
  15833. */
  15834. bool contains (float x, float y,
  15835. float tolerence = 10.0f) const;
  15836. /** Checks whether a point lies within the path.
  15837. This is only relevent for closed paths (see closeSubPath()), and
  15838. may produce false results if used on a path which has open sub-paths.
  15839. The path's winding rule is taken into account by this method.
  15840. The tolerence parameter is passed to the PathFlatteningIterator that
  15841. is used to trace the path - for more info about it, see the notes for
  15842. the PathFlatteningIterator constructor.
  15843. @see closeSubPath, setUsingNonZeroWinding
  15844. */
  15845. bool contains (const Point<float>& point,
  15846. float tolerence = 10.0f) const;
  15847. /** Checks whether a line crosses the path.
  15848. This will return positive if the line crosses any of the paths constituent
  15849. lines or curves. It doesn't take into account whether the line is inside
  15850. or outside the path, or whether the path is open or closed.
  15851. The tolerence parameter is passed to the PathFlatteningIterator that
  15852. is used to trace the path - for more info about it, see the notes for
  15853. the PathFlatteningIterator constructor.
  15854. */
  15855. bool intersectsLine (const Line<float>& line,
  15856. float tolerence = 10.0f);
  15857. /** Cuts off parts of a line to keep the parts that are either inside or
  15858. outside this path.
  15859. Note that this isn't smart enough to cope with situations where the
  15860. line would need to be cut into multiple pieces to correctly clip against
  15861. a re-entrant shape.
  15862. @param line the line to clip
  15863. @param keepSectionOutsidePath if true, it's the section outside the path
  15864. that will be kept; if false its the section inside
  15865. the path
  15866. */
  15867. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  15868. /** Removes all lines and curves, resetting the path completely. */
  15869. void clear() throw();
  15870. /** Begins a new subpath with a given starting position.
  15871. This will move the path's current position to the co-ordinates passed in and
  15872. make it ready to draw lines or curves starting from this position.
  15873. After adding whatever lines and curves are needed, you can either
  15874. close the current sub-path using closeSubPath() or call startNewSubPath()
  15875. to move to a new sub-path, leaving the old one open-ended.
  15876. @see lineTo, quadraticTo, cubicTo, closeSubPath
  15877. */
  15878. void startNewSubPath (float startX, float startY);
  15879. /** Closes a the current sub-path with a line back to its start-point.
  15880. When creating a closed shape such as a triangle, don't use 3 lineTo()
  15881. calls - instead use two lineTo() calls, followed by a closeSubPath()
  15882. to join the final point back to the start.
  15883. This ensures that closes shapes are recognised as such, and this is
  15884. important for tasks like drawing strokes, which needs to know whether to
  15885. draw end-caps or not.
  15886. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  15887. */
  15888. void closeSubPath();
  15889. /** Adds a line from the shape's last position to a new end-point.
  15890. This will connect the end-point of the last line or curve that was added
  15891. to a new point, using a straight line.
  15892. See the class description for an example of how to add lines and curves to a path.
  15893. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  15894. */
  15895. void lineTo (float endX, float endY);
  15896. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  15897. This will connect the end-point of the last line or curve that was added
  15898. to a new point, using a quadratic spline with one control-point.
  15899. See the class description for an example of how to add lines and curves to a path.
  15900. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  15901. */
  15902. void quadraticTo (float controlPointX,
  15903. float controlPointY,
  15904. float endPointX,
  15905. float endPointY);
  15906. /** Adds a cubic bezier curve from the shape's last position to a new position.
  15907. This will connect the end-point of the last line or curve that was added
  15908. to a new point, using a cubic spline with two control-points.
  15909. See the class description for an example of how to add lines and curves to a path.
  15910. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  15911. */
  15912. void cubicTo (float controlPoint1X,
  15913. float controlPoint1Y,
  15914. float controlPoint2X,
  15915. float controlPoint2Y,
  15916. float endPointX,
  15917. float endPointY);
  15918. /** Returns the last point that was added to the path by one of the drawing methods.
  15919. */
  15920. const Point<float> getCurrentPosition() const;
  15921. /** Adds a rectangle to the path.
  15922. The rectangle is added as a new sub-path. (Any currently open paths will be
  15923. left open).
  15924. @see addRoundedRectangle, addTriangle
  15925. */
  15926. void addRectangle (float x, float y, float width, float height);
  15927. /** Adds a rectangle to the path.
  15928. The rectangle is added as a new sub-path. (Any currently open paths will be
  15929. left open).
  15930. @see addRoundedRectangle, addTriangle
  15931. */
  15932. void addRectangle (const Rectangle<int>& rectangle);
  15933. /** Adds a rectangle with rounded corners to the path.
  15934. The rectangle is added as a new sub-path. (Any currently open paths will be
  15935. left open).
  15936. @see addRectangle, addTriangle
  15937. */
  15938. void addRoundedRectangle (float x, float y, float width, float height,
  15939. float cornerSize);
  15940. /** Adds a rectangle with rounded corners to the path.
  15941. The rectangle is added as a new sub-path. (Any currently open paths will be
  15942. left open).
  15943. @see addRectangle, addTriangle
  15944. */
  15945. void addRoundedRectangle (float x, float y, float width, float height,
  15946. float cornerSizeX,
  15947. float cornerSizeY);
  15948. /** Adds a triangle to the path.
  15949. The triangle is added as a new closed sub-path. (Any currently open paths will be
  15950. left open).
  15951. Note that whether the vertices are specified in clockwise or anticlockwise
  15952. order will affect how the triangle is filled when it overlaps other
  15953. shapes (the winding order setting will affect this of course).
  15954. */
  15955. void addTriangle (float x1, float y1,
  15956. float x2, float y2,
  15957. float x3, float y3);
  15958. /** Adds a quadrilateral to the path.
  15959. The quad is added as a new closed sub-path. (Any currently open paths will be
  15960. left open).
  15961. Note that whether the vertices are specified in clockwise or anticlockwise
  15962. order will affect how the quad is filled when it overlaps other
  15963. shapes (the winding order setting will affect this of course).
  15964. */
  15965. void addQuadrilateral (float x1, float y1,
  15966. float x2, float y2,
  15967. float x3, float y3,
  15968. float x4, float y4);
  15969. /** Adds an ellipse to the path.
  15970. The shape is added as a new sub-path. (Any currently open paths will be
  15971. left open).
  15972. @see addArc
  15973. */
  15974. void addEllipse (float x, float y, float width, float height);
  15975. /** Adds an elliptical arc to the current path.
  15976. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  15977. or anti-clockwise according to whether the end angle is greater than the start. This means
  15978. that sometimes you may need to use values greater than 2*Pi for the end angle.
  15979. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  15980. @param y the top edge of the rectangle in which the elliptical outline fits
  15981. @param width the width of the rectangle in which the elliptical outline fits
  15982. @param height the height of the rectangle in which the elliptical outline fits
  15983. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  15984. top-centre of the ellipse)
  15985. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  15986. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  15987. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  15988. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  15989. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  15990. it will be added to the current sub-path, continuing from the current postition
  15991. @see addCentredArc, arcTo, addPieSegment, addEllipse
  15992. */
  15993. void addArc (float x, float y, float width, float height,
  15994. float fromRadians,
  15995. float toRadians,
  15996. bool startAsNewSubPath = false);
  15997. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  15998. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  15999. or anti-clockwise according to whether the end angle is greater than the start. This means
  16000. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16001. @param centreX the centre x of the ellipse
  16002. @param centreY the centre y of the ellipse
  16003. @param radiusX the horizontal radius of the ellipse
  16004. @param radiusY the vertical radius of the ellipse
  16005. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  16006. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16007. top-centre of the ellipse)
  16008. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16009. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16010. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16011. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16012. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16013. it will be added to the current sub-path, continuing from the current postition
  16014. @see addArc, arcTo
  16015. */
  16016. void addCentredArc (float centreX, float centreY,
  16017. float radiusX, float radiusY,
  16018. float rotationOfEllipse,
  16019. float fromRadians,
  16020. float toRadians,
  16021. bool startAsNewSubPath = false);
  16022. /** Adds a "pie-chart" shape to the path.
  16023. The shape is added as a new sub-path. (Any currently open paths will be
  16024. left open).
  16025. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16026. or anti-clockwise according to whether the end angle is greater than the start. This means
  16027. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16028. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16029. @param y the top edge of the rectangle in which the elliptical outline fits
  16030. @param width the width of the rectangle in which the elliptical outline fits
  16031. @param height the height of the rectangle in which the elliptical outline fits
  16032. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16033. top-centre of the ellipse)
  16034. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16035. top-centre of the ellipse)
  16036. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  16037. ellipse at its centre, where this value indicates the inner ellipse's size with
  16038. respect to the outer one.
  16039. @see addArc
  16040. */
  16041. void addPieSegment (float x, float y,
  16042. float width, float height,
  16043. float fromRadians,
  16044. float toRadians,
  16045. float innerCircleProportionalSize);
  16046. /** Adds a line with a specified thickness.
  16047. The line is added as a new closed sub-path. (Any currently open paths will be
  16048. left open).
  16049. @see addArrow
  16050. */
  16051. void addLineSegment (float startX, float startY,
  16052. float endX, float endY,
  16053. float lineThickness);
  16054. /** Adds a line with an arrowhead on the end.
  16055. The arrow is added as a new closed sub-path. (Any currently open paths will be
  16056. left open).
  16057. */
  16058. void addArrow (float startX, float startY,
  16059. float endX, float endY,
  16060. float lineThickness,
  16061. float arrowheadWidth,
  16062. float arrowheadLength);
  16063. /** Adds a star shape to the path.
  16064. */
  16065. void addStar (float centreX,
  16066. float centreY,
  16067. int numberOfPoints,
  16068. float innerRadius,
  16069. float outerRadius,
  16070. float startAngle = 0.0f);
  16071. /** Adds a speech-bubble shape to the path.
  16072. @param bodyX the left of the main body area of the bubble
  16073. @param bodyY the top of the main body area of the bubble
  16074. @param bodyW the width of the main body area of the bubble
  16075. @param bodyH the height of the main body area of the bubble
  16076. @param cornerSize the amount by which to round off the corners of the main body rectangle
  16077. @param arrowTipX the x position that the tip of the arrow should connect to
  16078. @param arrowTipY the y position that the tip of the arrow should connect to
  16079. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  16080. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  16081. arrow's base should be - this is a proportional distance between 0 and 1.0
  16082. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  16083. */
  16084. void addBubble (float bodyX, float bodyY,
  16085. float bodyW, float bodyH,
  16086. float cornerSize,
  16087. float arrowTipX,
  16088. float arrowTipY,
  16089. int whichSide,
  16090. float arrowPositionAlongEdgeProportional,
  16091. float arrowWidth);
  16092. /** Adds another path to this one.
  16093. The new path is added as a new sub-path. (Any currently open paths in this
  16094. path will be left open).
  16095. @param pathToAppend the path to add
  16096. */
  16097. void addPath (const Path& pathToAppend);
  16098. /** Adds another path to this one, transforming it on the way in.
  16099. The new path is added as a new sub-path, its points being transformed by the given
  16100. matrix before being added.
  16101. @param pathToAppend the path to add
  16102. @param transformToApply an optional transform to apply to the incoming vertices
  16103. */
  16104. void addPath (const Path& pathToAppend,
  16105. const AffineTransform& transformToApply);
  16106. /** Swaps the contents of this path with another one.
  16107. The internal data of the two paths is swapped over, so this is much faster than
  16108. copying it to a temp variable and back.
  16109. */
  16110. void swapWithPath (Path& other) throw();
  16111. /** Applies a 2D transform to all the vertices in the path.
  16112. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  16113. */
  16114. void applyTransform (const AffineTransform& transform) throw();
  16115. /** Rescales this path to make it fit neatly into a given space.
  16116. This is effectively a quick way of calling
  16117. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  16118. @param x the x position of the rectangle to fit the path inside
  16119. @param y the y position of the rectangle to fit the path inside
  16120. @param width the width of the rectangle to fit the path inside
  16121. @param height the height of the rectangle to fit the path inside
  16122. @param preserveProportions if true, it will fit the path into the space without altering its
  16123. horizontal/vertical scale ratio; if false, it will distort the
  16124. path to fill the specified ratio both horizontally and vertically
  16125. @see applyTransform, getTransformToScaleToFit
  16126. */
  16127. void scaleToFit (float x, float y, float width, float height,
  16128. bool preserveProportions) throw();
  16129. /** Returns a transform that can be used to rescale the path to fit into a given space.
  16130. @param x the x position of the rectangle to fit the path inside
  16131. @param y the y position of the rectangle to fit the path inside
  16132. @param width the width of the rectangle to fit the path inside
  16133. @param height the height of the rectangle to fit the path inside
  16134. @param preserveProportions if true, it will fit the path into the space without altering its
  16135. horizontal/vertical scale ratio; if false, it will distort the
  16136. path to fill the specified ratio both horizontally and vertically
  16137. @param justificationType if the proportions are preseved, the resultant path may be smaller
  16138. than the available rectangle, so this describes how it should be
  16139. positioned within the space.
  16140. @returns an appropriate transformation
  16141. @see applyTransform, scaleToFit
  16142. */
  16143. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  16144. bool preserveProportions,
  16145. const Justification& justificationType = Justification::centred) const;
  16146. /** Creates a version of this path where all sharp corners have been replaced by curves.
  16147. Wherever two lines meet at an angle, this will replace the corner with a curve
  16148. of the given radius.
  16149. */
  16150. const Path createPathWithRoundedCorners (float cornerRadius) const;
  16151. /** Changes the winding-rule to be used when filling the path.
  16152. If set to true (which is the default), then the path uses a non-zero-winding rule
  16153. to determine which points are inside the path. If set to false, it uses an
  16154. alternate-winding rule.
  16155. The winding-rule comes into play when areas of the shape overlap other
  16156. areas, and determines whether the overlapping regions are considered to be
  16157. inside or outside.
  16158. Changing this value just sets a flag - it doesn't affect the contents of the
  16159. path.
  16160. @see isUsingNonZeroWinding
  16161. */
  16162. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  16163. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  16164. The default for a new path is true.
  16165. @see setUsingNonZeroWinding
  16166. */
  16167. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  16168. /** Iterates the lines and curves that a path contains.
  16169. @see Path, PathFlatteningIterator
  16170. */
  16171. class JUCE_API Iterator
  16172. {
  16173. public:
  16174. Iterator (const Path& path);
  16175. ~Iterator();
  16176. /** Moves onto the next element in the path.
  16177. If this returns false, there are no more elements. If it returns true,
  16178. the elementType variable will be set to the type of the current element,
  16179. and some of the x and y variables will be filled in with values.
  16180. */
  16181. bool next();
  16182. enum PathElementType
  16183. {
  16184. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  16185. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  16186. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  16187. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  16188. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  16189. };
  16190. PathElementType elementType;
  16191. float x1, y1, x2, y2, x3, y3;
  16192. private:
  16193. const Path& path;
  16194. size_t index;
  16195. Iterator (const Iterator&);
  16196. Iterator& operator= (const Iterator&);
  16197. };
  16198. /** Loads a stored path from a data stream.
  16199. The data in the stream must have been written using writePathToStream().
  16200. Note that this will append the stored path to whatever is currently in
  16201. this path, so you might need to call clear() beforehand.
  16202. @see loadPathFromData, writePathToStream
  16203. */
  16204. void loadPathFromStream (InputStream& source);
  16205. /** Loads a stored path from a block of data.
  16206. This is similar to loadPathFromStream(), but just reads from a block
  16207. of data. Useful if you're including stored shapes in your code as a
  16208. block of static data.
  16209. @see loadPathFromStream, writePathToStream
  16210. */
  16211. void loadPathFromData (const void* data, int numberOfBytes);
  16212. /** Stores the path by writing it out to a stream.
  16213. After writing out a path, you can reload it using loadPathFromStream().
  16214. @see loadPathFromStream, loadPathFromData
  16215. */
  16216. void writePathToStream (OutputStream& destination) const;
  16217. /** Creates a string containing a textual representation of this path.
  16218. @see restoreFromString
  16219. */
  16220. const String toString() const;
  16221. /** Restores this path from a string that was created with the toString() method.
  16222. @see toString()
  16223. */
  16224. void restoreFromString (const String& stringVersion);
  16225. juce_UseDebuggingNewOperator
  16226. private:
  16227. friend class PathFlatteningIterator;
  16228. friend class Path::Iterator;
  16229. ArrayAllocationBase <float, DummyCriticalSection> data;
  16230. size_t numElements;
  16231. float pathXMin, pathXMax, pathYMin, pathYMax;
  16232. bool useNonZeroWinding;
  16233. static const float lineMarker;
  16234. static const float moveMarker;
  16235. static const float quadMarker;
  16236. static const float cubicMarker;
  16237. static const float closeSubPathMarker;
  16238. };
  16239. #endif // __JUCE_PATH_JUCEHEADER__
  16240. /*** End of inlined file: juce_Path.h ***/
  16241. class Font;
  16242. /** A typeface represents a size-independent font.
  16243. This base class is abstract, but calling createSystemTypefaceFor() will return
  16244. a platform-specific subclass that can be used.
  16245. The CustomTypeface subclass allow you to build your own typeface, and to
  16246. load and save it in the Juce typeface format.
  16247. Normally you should never need to deal directly with Typeface objects - the Font
  16248. class does everything you typically need for rendering text.
  16249. @see CustomTypeface, Font
  16250. */
  16251. class JUCE_API Typeface : public ReferenceCountedObject
  16252. {
  16253. public:
  16254. /** A handy typedef for a pointer to a typeface. */
  16255. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  16256. /** Returns the name of the typeface.
  16257. @see Font::getTypefaceName
  16258. */
  16259. const String getName() const throw() { return name; }
  16260. /** Creates a new system typeface. */
  16261. static const Ptr createSystemTypefaceFor (const Font& font);
  16262. /** Destructor. */
  16263. virtual ~Typeface();
  16264. /** Returns the ascent of the font, as a proportion of its height.
  16265. The height is considered to always be normalised as 1.0, so this will be a
  16266. value less that 1.0, indicating the proportion of the font that lies above
  16267. its baseline.
  16268. */
  16269. virtual float getAscent() const = 0;
  16270. /** Returns the descent of the font, as a proportion of its height.
  16271. The height is considered to always be normalised as 1.0, so this will be a
  16272. value less that 1.0, indicating the proportion of the font that lies below
  16273. its baseline.
  16274. */
  16275. virtual float getDescent() const = 0;
  16276. /** Measures the width of a line of text.
  16277. The distance returned is based on the font having an normalised height of 1.0.
  16278. You should never need to call this directly! Use Font::getStringWidth() instead!
  16279. */
  16280. virtual float getStringWidth (const String& text) = 0;
  16281. /** Converts a line of text into its glyph numbers and their positions.
  16282. The distances returned are based on the font having an normalised height of 1.0.
  16283. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  16284. */
  16285. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  16286. /** Returns the outline for a glyph.
  16287. The path returned will be normalised to a font height of 1.0.
  16288. */
  16289. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  16290. juce_UseDebuggingNewOperator
  16291. protected:
  16292. String name;
  16293. explicit Typeface (const String& name) throw();
  16294. private:
  16295. Typeface (const Typeface&);
  16296. Typeface& operator= (const Typeface&);
  16297. };
  16298. /** A typeface that can be populated with custom glyphs.
  16299. You can create a CustomTypeface if you need one that contains your own glyphs,
  16300. or if you need to load a typeface from a Juce-formatted binary stream.
  16301. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  16302. to copy glyphs into this face.
  16303. @see Typeface, Font
  16304. */
  16305. class JUCE_API CustomTypeface : public Typeface
  16306. {
  16307. public:
  16308. /** Creates a new, empty typeface. */
  16309. CustomTypeface();
  16310. /** Loads a typeface from a previously saved stream.
  16311. The stream must have been created by writeToStream().
  16312. @see writeToStream
  16313. */
  16314. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  16315. /** Destructor. */
  16316. ~CustomTypeface();
  16317. /** Resets this typeface, deleting all its glyphs and settings. */
  16318. void clear();
  16319. /** Sets the vital statistics for the typeface.
  16320. @param name the typeface's name
  16321. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  16322. the value that will be returned by Typeface::getAscent(). The
  16323. descent is assumed to be (1.0 - ascent)
  16324. @param isBold should be true if the typeface is bold
  16325. @param isItalic should be true if the typeface is italic
  16326. @param defaultCharacter the character to be used as a replacement if there's
  16327. no glyph available for the character that's being drawn
  16328. */
  16329. void setCharacteristics (const String& name, float ascent,
  16330. bool isBold, bool isItalic,
  16331. juce_wchar defaultCharacter) throw();
  16332. /** Adds a glyph to the typeface.
  16333. The path that is passed in is normalised so that the font height is 1.0, and its
  16334. origin is the anchor point of the character on its baseline.
  16335. The width is the nominal width of the character, and any extra kerning values that
  16336. are specified will be added to this width.
  16337. */
  16338. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  16339. /** Specifies an extra kerning amount to be used between a pair of characters.
  16340. The amount will be added to the nominal width of the first character when laying out a string.
  16341. */
  16342. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  16343. /** Adds a range of glyphs from another typeface.
  16344. This will attempt to pull in the paths and kerning information from another typeface and
  16345. add it to this one.
  16346. */
  16347. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  16348. /** Saves this typeface as a Juce-formatted font file.
  16349. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  16350. constructor.
  16351. */
  16352. bool writeToStream (OutputStream& outputStream);
  16353. // The following methods implement the basic Typeface behaviour.
  16354. float getAscent() const;
  16355. float getDescent() const;
  16356. float getStringWidth (const String& text);
  16357. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  16358. bool getOutlineForGlyph (int glyphNumber, Path& path);
  16359. int getGlyphForCharacter (juce_wchar character);
  16360. juce_UseDebuggingNewOperator
  16361. protected:
  16362. juce_wchar defaultCharacter;
  16363. float ascent;
  16364. bool isBold, isItalic;
  16365. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  16366. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  16367. particular character and there's no corresponding glyph, they'll call this
  16368. method so that a subclass can try to add that glyph, returning true if it
  16369. manages to do so.
  16370. */
  16371. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  16372. private:
  16373. class GlyphInfo;
  16374. friend class OwnedArray<GlyphInfo>;
  16375. OwnedArray <GlyphInfo> glyphs;
  16376. short lookupTable [128];
  16377. CustomTypeface (const CustomTypeface&);
  16378. CustomTypeface& operator= (const CustomTypeface&);
  16379. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  16380. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  16381. };
  16382. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  16383. /*** End of inlined file: juce_Typeface.h ***/
  16384. class LowLevelGraphicsContext;
  16385. /**
  16386. Represents a particular font, including its size, style, etc.
  16387. Apart from the typeface to be used, a Font object also dictates whether
  16388. the font is bold, italic, underlined, how big it is, and its kerning and
  16389. horizontal scale factor.
  16390. @see Typeface
  16391. */
  16392. class JUCE_API Font
  16393. {
  16394. public:
  16395. /** A combination of these values is used by the constructor to specify the
  16396. style of font to use.
  16397. */
  16398. enum FontStyleFlags
  16399. {
  16400. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  16401. bold = 1, /**< boldens the font. @see setStyleFlags */
  16402. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  16403. underlined = 4 /**< underlines the font. @see setStyleFlags */
  16404. };
  16405. /** Creates a sans-serif font in a given size.
  16406. @param fontHeight the height in pixels (can be fractional)
  16407. @param styleFlags the style to use - this can be a combination of the
  16408. Font::bold, Font::italic and Font::underlined, or
  16409. just Font::plain for the normal style.
  16410. @see FontStyleFlags, getDefaultSansSerifFontName
  16411. */
  16412. Font (float fontHeight,
  16413. int styleFlags = plain) throw();
  16414. /** Creates a font with a given typeface and parameters.
  16415. @param typefaceName the name of the typeface to use
  16416. @param fontHeight the height in pixels (can be fractional)
  16417. @param styleFlags the style to use - this can be a combination of the
  16418. Font::bold, Font::italic and Font::underlined, or
  16419. just Font::plain for the normal style.
  16420. @see FontStyleFlags, getDefaultSansSerifFontName
  16421. */
  16422. Font (const String& typefaceName,
  16423. float fontHeight,
  16424. int styleFlags) throw();
  16425. /** Creates a copy of another Font object. */
  16426. Font (const Font& other) throw();
  16427. /** Creates a font for a typeface. */
  16428. Font (const Typeface::Ptr& typeface) throw();
  16429. /** Creates a basic sans-serif font at a default height.
  16430. You should use one of the other constructors for creating a font that you're planning
  16431. on drawing with - this constructor is here to help initialise objects before changing
  16432. the font's settings later.
  16433. */
  16434. Font() throw();
  16435. /** Copies this font from another one. */
  16436. Font& operator= (const Font& other) throw();
  16437. bool operator== (const Font& other) const throw();
  16438. bool operator!= (const Font& other) const throw();
  16439. /** Destructor. */
  16440. ~Font() throw();
  16441. /** Changes the name of the typeface family.
  16442. e.g. "Arial", "Courier", etc.
  16443. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16444. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16445. but are generic names that are used to represent the various default fonts.
  16446. If you need to know the exact typeface name being used, you can call
  16447. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16448. If a suitable font isn't found on the machine, it'll just use a default instead.
  16449. */
  16450. void setTypefaceName (const String& faceName) throw();
  16451. /** Returns the name of the typeface family that this font uses.
  16452. e.g. "Arial", "Courier", etc.
  16453. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16454. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16455. but are generic names that are used to represent the various default fonts.
  16456. If you need to know the exact typeface name being used, you can call
  16457. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16458. */
  16459. const String& getTypefaceName() const throw() { return font->typefaceName; }
  16460. /** Returns a typeface name that represents the default sans-serif font.
  16461. This is also the typeface that will be used when a font is created without
  16462. specifying any typeface details.
  16463. Note that this method just returns a generic placeholder string that means "the default
  16464. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  16465. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16466. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  16467. */
  16468. static const String getDefaultSansSerifFontName() throw();
  16469. /** Returns a typeface name that represents the default sans-serif font.
  16470. Note that this method just returns a generic placeholder string that means "the default
  16471. serif font" - it's not the actual name of this font. To get the actual name, use
  16472. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16473. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  16474. */
  16475. static const String getDefaultSerifFontName() throw();
  16476. /** Returns a typeface name that represents the default sans-serif font.
  16477. Note that this method just returns a generic placeholder string that means "the default
  16478. monospaced font" - it's not the actual name of this font. To get the actual name, use
  16479. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16480. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  16481. */
  16482. static const String getDefaultMonospacedFontName() throw();
  16483. /** Returns the typeface names of the default fonts on the current platform. */
  16484. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed);
  16485. /** Returns the total height of this font.
  16486. This is the maximum height, from the top of the ascent to the bottom of the
  16487. descenders.
  16488. @see setHeight, setHeightWithoutChangingWidth, getAscent
  16489. */
  16490. float getHeight() const throw() { return font->height; }
  16491. /** Changes the font's height.
  16492. @see getHeight, setHeightWithoutChangingWidth
  16493. */
  16494. void setHeight (float newHeight) throw();
  16495. /** Changes the font's height without changing its width.
  16496. This alters the horizontal scale to compensate for the change in height.
  16497. */
  16498. void setHeightWithoutChangingWidth (float newHeight) throw();
  16499. /** Returns the height of the font above its baseline.
  16500. This is the maximum height from the baseline to the top.
  16501. @see getHeight, getDescent
  16502. */
  16503. float getAscent() const throw();
  16504. /** Returns the amount that the font descends below its baseline.
  16505. This is calculated as (getHeight() - getAscent()).
  16506. @see getAscent, getHeight
  16507. */
  16508. float getDescent() const throw();
  16509. /** Returns the font's style flags.
  16510. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  16511. enum, to describe whether the font is bold, italic, etc.
  16512. @see FontStyleFlags
  16513. */
  16514. int getStyleFlags() const throw() { return font->styleFlags; }
  16515. /** Changes the font's style.
  16516. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  16517. enum, to set the font's properties
  16518. @see FontStyleFlags
  16519. */
  16520. void setStyleFlags (int newFlags) throw();
  16521. /** Makes the font bold or non-bold. */
  16522. void setBold (bool shouldBeBold) throw();
  16523. /** Returns true if the font is bold. */
  16524. bool isBold() const throw();
  16525. /** Makes the font italic or non-italic. */
  16526. void setItalic (bool shouldBeItalic) throw();
  16527. /** Returns true if the font is italic. */
  16528. bool isItalic() const throw();
  16529. /** Makes the font underlined or non-underlined. */
  16530. void setUnderline (bool shouldBeUnderlined) throw();
  16531. /** Returns true if the font is underlined. */
  16532. bool isUnderlined() const throw();
  16533. /** Changes the font's horizontal scale factor.
  16534. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  16535. narrower, greater than 1.0 will be stretched out.
  16536. */
  16537. void setHorizontalScale (float scaleFactor) throw();
  16538. /** Returns the font's horizontal scale.
  16539. A value of 1.0 is the normal scale, less than this will be narrower, greater
  16540. than 1.0 will be stretched out.
  16541. @see setHorizontalScale
  16542. */
  16543. float getHorizontalScale() const throw() { return font->horizontalScale; }
  16544. /** Changes the font's kerning.
  16545. @param extraKerning a multiple of the font's height that will be added
  16546. to space between the characters. So a value of zero is
  16547. normal spacing, positive values spread the letters out,
  16548. negative values make them closer together.
  16549. */
  16550. void setExtraKerningFactor (float extraKerning) throw();
  16551. /** Returns the font's kerning.
  16552. This is the extra space added between adjacent characters, as a proportion
  16553. of the font's height.
  16554. A value of zero is normal spacing, positive values will spread the letters
  16555. out more, and negative values make them closer together.
  16556. */
  16557. float getExtraKerningFactor() const throw() { return font->kerning; }
  16558. /** Changes all the font's characteristics with one call. */
  16559. void setSizeAndStyle (float newHeight,
  16560. int newStyleFlags,
  16561. float newHorizontalScale,
  16562. float newKerningAmount) throw();
  16563. /** Returns the total width of a string as it would be drawn using this font.
  16564. For a more accurate floating-point result, use getStringWidthFloat().
  16565. */
  16566. int getStringWidth (const String& text) const throw();
  16567. /** Returns the total width of a string as it would be drawn using this font.
  16568. @see getStringWidth
  16569. */
  16570. float getStringWidthFloat (const String& text) const throw();
  16571. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  16572. An extra x offset is added at the end of the run, to indicate where the right hand
  16573. edge of the last character is.
  16574. */
  16575. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  16576. /** Returns the typeface used by this font.
  16577. Note that the object returned may go out of scope if this font is deleted
  16578. or has its style changed.
  16579. */
  16580. Typeface* getTypeface() const throw();
  16581. /** Creates an array of Font objects to represent all the fonts on the system.
  16582. If you just need the names of the typefaces, you can also use
  16583. findAllTypefaceNames() instead.
  16584. @param results the array to which new Font objects will be added.
  16585. */
  16586. static void findFonts (Array<Font>& results) throw();
  16587. /** Returns a list of all the available typeface names.
  16588. The names returned can be passed into setTypefaceName().
  16589. You can use this instead of findFonts() if you only need their names, and not
  16590. font objects.
  16591. */
  16592. static const StringArray findAllTypefaceNames();
  16593. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  16594. in the requested typeface.
  16595. */
  16596. static const String getFallbackFontName() throw();
  16597. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  16598. available in whatever font you're trying to use.
  16599. */
  16600. static void setFallbackFontName (const String& name) throw();
  16601. /** Creates a string to describe this font.
  16602. The string will contain information to describe the font's typeface, size, and
  16603. style. To recreate the font from this string, use fromString().
  16604. */
  16605. const String toString() const;
  16606. /** Recreates a font from its stringified encoding.
  16607. This method takes a string that was created by toString(), and recreates the
  16608. original font.
  16609. */
  16610. static const Font fromString (const String& fontDescription);
  16611. juce_UseDebuggingNewOperator
  16612. private:
  16613. friend class FontGlyphAlphaMap;
  16614. friend class TypefaceCache;
  16615. class SharedFontInternal : public ReferenceCountedObject
  16616. {
  16617. public:
  16618. SharedFontInternal (const String& typefaceName, float height, float horizontalScale,
  16619. float kerning, float ascent, int styleFlags,
  16620. Typeface* typeface) throw();
  16621. SharedFontInternal (const SharedFontInternal& other) throw();
  16622. String typefaceName;
  16623. float height, horizontalScale, kerning, ascent;
  16624. int styleFlags;
  16625. Typeface::Ptr typeface;
  16626. };
  16627. ReferenceCountedObjectPtr <SharedFontInternal> font;
  16628. void dupeInternalIfShared() throw();
  16629. };
  16630. #endif // __JUCE_FONT_JUCEHEADER__
  16631. /*** End of inlined file: juce_Font.h ***/
  16632. /*** Start of inlined file: juce_PathStrokeType.h ***/
  16633. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16634. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16635. /**
  16636. Describes a type of stroke used to render a solid outline along a path.
  16637. A PathStrokeType object can be used directly to create the shape of an outline
  16638. around a path, and is used by Graphics::strokePath to specify the type of
  16639. stroke to draw.
  16640. @see Path, Graphics::strokePath
  16641. */
  16642. class JUCE_API PathStrokeType
  16643. {
  16644. public:
  16645. /** The type of shape to use for the corners between two adjacent line segments. */
  16646. enum JointStyle
  16647. {
  16648. mitered, /**< Indicates that corners should be drawn with sharp joints.
  16649. Note that for angles that curve back on themselves, drawing a
  16650. mitre could require extending the point too far away from the
  16651. path, so a mitre limit is imposed and any corners that exceed it
  16652. are drawn as bevelled instead. */
  16653. curved, /**< Indicates that corners should be drawn as rounded-off. */
  16654. beveled /**< Indicates that corners should be drawn with a line flattening their
  16655. outside edge. */
  16656. };
  16657. /** The type shape to use for the ends of lines. */
  16658. enum EndCapStyle
  16659. {
  16660. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  16661. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  16662. the thickness of the stroke. */
  16663. rounded /**< Ends of lines are rounded-off with a circular shape. */
  16664. };
  16665. /** Creates a stroke type.
  16666. @param strokeThickness the width of the line to use
  16667. @param jointStyle the type of joints to use for corners
  16668. @param endStyle the type of end-caps to use for the ends of open paths.
  16669. */
  16670. PathStrokeType (float strokeThickness,
  16671. JointStyle jointStyle = mitered,
  16672. EndCapStyle endStyle = butt) throw();
  16673. /** Createes a copy of another stroke type. */
  16674. PathStrokeType (const PathStrokeType& other) throw();
  16675. /** Copies another stroke onto this one. */
  16676. PathStrokeType& operator= (const PathStrokeType& other) throw();
  16677. /** Destructor. */
  16678. ~PathStrokeType() throw();
  16679. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  16680. @param destPath the resultant stroked outline shape will be copied into this path.
  16681. Note that it's ok for the source and destination Paths to be
  16682. the same object, so you can easily turn a path into a stroked version
  16683. of itself.
  16684. @param sourcePath the path to use as the source
  16685. @param transform an optional transform to apply to the points from the source path
  16686. as they are being used
  16687. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  16688. a higher resolution, which improved the quality if you'll later want
  16689. to enlarge the stroked path
  16690. @see createDashedStroke
  16691. */
  16692. void createStrokedPath (Path& destPath,
  16693. const Path& sourcePath,
  16694. const AffineTransform& transform = AffineTransform::identity,
  16695. float extraAccuracy = 1.0f) const;
  16696. /** Applies this stroke type to a path, creating a dashed line.
  16697. This is similar to createStrokedPath, but uses the array passed in to
  16698. break the stroke up into a series of dashes.
  16699. @param destPath the resultant stroked outline shape will be copied into this path.
  16700. Note that it's ok for the source and destination Paths to be
  16701. the same object, so you can easily turn a path into a stroked version
  16702. of itself.
  16703. @param sourcePath the path to use as the source
  16704. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  16705. a line of length 2, then skip a length of 3, then add a line of length 4,
  16706. skip 5, and keep repeating this pattern.
  16707. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  16708. an even number, otherwise the pattern will get out of step as it
  16709. repeats.
  16710. @param transform an optional transform to apply to the points from the source path
  16711. as they are being used
  16712. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  16713. a higher resolution, which improved the quality if you'll later want
  16714. to enlarge the stroked path
  16715. */
  16716. void createDashedStroke (Path& destPath,
  16717. const Path& sourcePath,
  16718. const float* dashLengths,
  16719. int numDashLengths,
  16720. const AffineTransform& transform = AffineTransform::identity,
  16721. float extraAccuracy = 1.0f) const;
  16722. /** Returns the stroke thickness. */
  16723. float getStrokeThickness() const throw() { return thickness; }
  16724. /** Returns the joint style. */
  16725. JointStyle getJointStyle() const throw() { return jointStyle; }
  16726. /** Returns the end-cap style. */
  16727. EndCapStyle getEndStyle() const throw() { return endStyle; }
  16728. juce_UseDebuggingNewOperator
  16729. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  16730. bool operator== (const PathStrokeType& other) const throw();
  16731. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  16732. bool operator!= (const PathStrokeType& other) const throw();
  16733. private:
  16734. float thickness;
  16735. JointStyle jointStyle;
  16736. EndCapStyle endStyle;
  16737. };
  16738. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  16739. /*** End of inlined file: juce_PathStrokeType.h ***/
  16740. /*** Start of inlined file: juce_Colours.h ***/
  16741. #ifndef __JUCE_COLOURS_JUCEHEADER__
  16742. #define __JUCE_COLOURS_JUCEHEADER__
  16743. /*** Start of inlined file: juce_Colour.h ***/
  16744. #ifndef __JUCE_COLOUR_JUCEHEADER__
  16745. #define __JUCE_COLOUR_JUCEHEADER__
  16746. /*** Start of inlined file: juce_PixelFormats.h ***/
  16747. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  16748. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  16749. #if JUCE_MSVC
  16750. #pragma pack (push, 1)
  16751. #define PACKED
  16752. #elif JUCE_GCC
  16753. #define PACKED __attribute__((packed))
  16754. #else
  16755. #define PACKED
  16756. #endif
  16757. class PixelRGB;
  16758. class PixelAlpha;
  16759. /**
  16760. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  16761. operations with it.
  16762. This is used internally by the imaging classes.
  16763. @see PixelRGB
  16764. */
  16765. class JUCE_API PixelARGB
  16766. {
  16767. public:
  16768. /** Creates a pixel without defining its colour. */
  16769. PixelARGB() throw() {}
  16770. ~PixelARGB() throw() {}
  16771. /** Creates a pixel from a 32-bit argb value.
  16772. */
  16773. PixelARGB (const uint32 argb_) throw()
  16774. : argb (argb_)
  16775. {
  16776. }
  16777. forcedinline uint32 getARGB() const throw() { return argb; }
  16778. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  16779. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  16780. forcedinline uint8 getAlpha() const throw() { return components.a; }
  16781. forcedinline uint8 getRed() const throw() { return components.r; }
  16782. forcedinline uint8 getGreen() const throw() { return components.g; }
  16783. forcedinline uint8 getBlue() const throw() { return components.b; }
  16784. /** Blends another pixel onto this one.
  16785. This takes into account the opacity of the pixel being overlaid, and blends
  16786. it accordingly.
  16787. */
  16788. forcedinline void blend (const PixelARGB& src) throw()
  16789. {
  16790. uint32 sargb = src.getARGB();
  16791. const uint32 alpha = 0x100 - (sargb >> 24);
  16792. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  16793. sargb += 0xff00ff00 & (getAG() * alpha);
  16794. argb = sargb;
  16795. }
  16796. /** Blends another pixel onto this one.
  16797. This takes into account the opacity of the pixel being overlaid, and blends
  16798. it accordingly.
  16799. */
  16800. forcedinline void blend (const PixelAlpha& src) throw();
  16801. /** Blends another pixel onto this one.
  16802. This takes into account the opacity of the pixel being overlaid, and blends
  16803. it accordingly.
  16804. */
  16805. forcedinline void blend (const PixelRGB& src) throw();
  16806. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  16807. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  16808. being used, so this can blend semi-transparently from a PixelRGB argument.
  16809. */
  16810. template <class Pixel>
  16811. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  16812. {
  16813. ++extraAlpha;
  16814. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  16815. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  16816. const uint32 alpha = 0x100 - (sargb >> 24);
  16817. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  16818. sargb += 0xff00ff00 & (getAG() * alpha);
  16819. argb = sargb;
  16820. }
  16821. /** Blends another pixel with this one, creating a colour that is somewhere
  16822. between the two, as specified by the amount.
  16823. */
  16824. template <class Pixel>
  16825. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  16826. {
  16827. uint32 drb = getRB();
  16828. drb += (((src.getRB() - drb) * amount) >> 8);
  16829. drb &= 0x00ff00ff;
  16830. uint32 dag = getAG();
  16831. dag += (((src.getAG() - dag) * amount) >> 8);
  16832. dag &= 0x00ff00ff;
  16833. dag <<= 8;
  16834. dag |= drb;
  16835. argb = dag;
  16836. }
  16837. /** Copies another pixel colour over this one.
  16838. This doesn't blend it - this colour is simply replaced by the other one.
  16839. */
  16840. template <class Pixel>
  16841. forcedinline void set (const Pixel& src) throw()
  16842. {
  16843. argb = src.getARGB();
  16844. }
  16845. /** Replaces the colour's alpha value with another one. */
  16846. forcedinline void setAlpha (const uint8 newAlpha) throw()
  16847. {
  16848. components.a = newAlpha;
  16849. }
  16850. /** Multiplies the colour's alpha value with another one. */
  16851. forcedinline void multiplyAlpha (int multiplier) throw()
  16852. {
  16853. ++multiplier;
  16854. argb = ((multiplier * getAG()) & 0xff00ff00)
  16855. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  16856. }
  16857. forcedinline void multiplyAlpha (const float multiplier) throw()
  16858. {
  16859. multiplyAlpha ((int) (multiplier * 256.0f));
  16860. }
  16861. /** Sets the pixel's colour from individual components. */
  16862. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  16863. {
  16864. components.b = b;
  16865. components.g = g;
  16866. components.r = r;
  16867. components.a = a;
  16868. }
  16869. /** Premultiplies the pixel's RGB values by its alpha. */
  16870. forcedinline void premultiply() throw()
  16871. {
  16872. const uint32 alpha = components.a;
  16873. if (alpha < 0xff)
  16874. {
  16875. if (alpha == 0)
  16876. {
  16877. components.b = 0;
  16878. components.g = 0;
  16879. components.r = 0;
  16880. }
  16881. else
  16882. {
  16883. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  16884. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  16885. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  16886. }
  16887. }
  16888. }
  16889. /** Unpremultiplies the pixel's RGB values. */
  16890. forcedinline void unpremultiply() throw()
  16891. {
  16892. const uint32 alpha = components.a;
  16893. if (alpha < 0xff)
  16894. {
  16895. if (alpha == 0)
  16896. {
  16897. components.b = 0;
  16898. components.g = 0;
  16899. components.r = 0;
  16900. }
  16901. else
  16902. {
  16903. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  16904. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  16905. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  16906. }
  16907. }
  16908. }
  16909. forcedinline void desaturate() throw()
  16910. {
  16911. if (components.a < 0xff && components.a > 0)
  16912. {
  16913. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  16914. components.r = components.g = components.b
  16915. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  16916. }
  16917. else
  16918. {
  16919. components.r = components.g = components.b
  16920. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  16921. }
  16922. }
  16923. /** The indexes of the different components in the byte layout of this type of colour. */
  16924. #if JUCE_BIG_ENDIAN
  16925. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  16926. #else
  16927. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  16928. #endif
  16929. private:
  16930. union
  16931. {
  16932. uint32 argb;
  16933. struct
  16934. {
  16935. #if JUCE_BIG_ENDIAN
  16936. uint8 a : 8, r : 8, g : 8, b : 8;
  16937. #else
  16938. uint8 b, g, r, a;
  16939. #endif
  16940. } PACKED components;
  16941. };
  16942. } PACKED;
  16943. /**
  16944. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  16945. This is used internally by the imaging classes.
  16946. @see PixelARGB
  16947. */
  16948. class JUCE_API PixelRGB
  16949. {
  16950. public:
  16951. /** Creates a pixel without defining its colour. */
  16952. PixelRGB() throw() {}
  16953. ~PixelRGB() throw() {}
  16954. /** Creates a pixel from a 32-bit argb value.
  16955. (The argb format is that used by PixelARGB)
  16956. */
  16957. PixelRGB (const uint32 argb) throw()
  16958. {
  16959. r = (uint8) (argb >> 16);
  16960. g = (uint8) (argb >> 8);
  16961. b = (uint8) (argb);
  16962. }
  16963. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  16964. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  16965. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  16966. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  16967. forcedinline uint8 getRed() const throw() { return r; }
  16968. forcedinline uint8 getGreen() const throw() { return g; }
  16969. forcedinline uint8 getBlue() const throw() { return b; }
  16970. /** Blends another pixel onto this one.
  16971. This takes into account the opacity of the pixel being overlaid, and blends
  16972. it accordingly.
  16973. */
  16974. forcedinline void blend (const PixelARGB& src) throw()
  16975. {
  16976. uint32 sargb = src.getARGB();
  16977. const uint32 alpha = 0x100 - (sargb >> 24);
  16978. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  16979. sargb += 0x0000ff00 & (g * alpha);
  16980. r = (uint8) (sargb >> 16);
  16981. g = (uint8) (sargb >> 8);
  16982. b = (uint8) sargb;
  16983. }
  16984. forcedinline void blend (const PixelRGB& src) throw()
  16985. {
  16986. set (src);
  16987. }
  16988. forcedinline void blend (const PixelAlpha& src) throw();
  16989. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  16990. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  16991. being used, so this can blend semi-transparently from a PixelRGB argument.
  16992. */
  16993. template <class Pixel>
  16994. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  16995. {
  16996. ++extraAlpha;
  16997. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  16998. const uint32 sag = extraAlpha * src.getAG();
  16999. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  17000. const uint32 alpha = 0x100 - (sargb >> 24);
  17001. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17002. sargb += 0x0000ff00 & (g * alpha);
  17003. b = (uint8) sargb;
  17004. g = (uint8) (sargb >> 8);
  17005. r = (uint8) (sargb >> 16);
  17006. }
  17007. /** Blends another pixel with this one, creating a colour that is somewhere
  17008. between the two, as specified by the amount.
  17009. */
  17010. template <class Pixel>
  17011. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17012. {
  17013. uint32 drb = getRB();
  17014. drb += (((src.getRB() - drb) * amount) >> 8);
  17015. uint32 dag = getAG();
  17016. dag += (((src.getAG() - dag) * amount) >> 8);
  17017. b = (uint8) drb;
  17018. g = (uint8) dag;
  17019. r = (uint8) (drb >> 16);
  17020. }
  17021. /** Copies another pixel colour over this one.
  17022. This doesn't blend it - this colour is simply replaced by the other one.
  17023. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  17024. is thrown away.
  17025. */
  17026. template <class Pixel>
  17027. forcedinline void set (const Pixel& src) throw()
  17028. {
  17029. b = src.getBlue();
  17030. g = src.getGreen();
  17031. r = src.getRed();
  17032. }
  17033. /** This method is included for compatibility with the PixelARGB class. */
  17034. forcedinline void setAlpha (const uint8) throw() {}
  17035. /** Multiplies the colour's alpha value with another one. */
  17036. forcedinline void multiplyAlpha (int) throw() {}
  17037. /** Sets the pixel's colour from individual components. */
  17038. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  17039. {
  17040. r = r_;
  17041. g = g_;
  17042. b = b_;
  17043. }
  17044. /** Premultiplies the pixel's RGB values by its alpha. */
  17045. forcedinline void premultiply() throw() {}
  17046. /** Unpremultiplies the pixel's RGB values. */
  17047. forcedinline void unpremultiply() throw() {}
  17048. forcedinline void desaturate() throw()
  17049. {
  17050. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  17051. }
  17052. /** The indexes of the different components in the byte layout of this type of colour. */
  17053. #if JUCE_MAC
  17054. enum { indexR = 0, indexG = 1, indexB = 2 };
  17055. #else
  17056. enum { indexR = 2, indexG = 1, indexB = 0 };
  17057. #endif
  17058. private:
  17059. #if JUCE_MAC
  17060. uint8 r, g, b;
  17061. #else
  17062. uint8 b, g, r;
  17063. #endif
  17064. } PACKED;
  17065. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  17066. {
  17067. set (src);
  17068. }
  17069. /**
  17070. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  17071. This is used internally by the imaging classes.
  17072. @see PixelARGB, PixelRGB
  17073. */
  17074. class JUCE_API PixelAlpha
  17075. {
  17076. public:
  17077. /** Creates a pixel without defining its colour. */
  17078. PixelAlpha() throw() {}
  17079. ~PixelAlpha() throw() {}
  17080. /** Creates a pixel from a 32-bit argb value.
  17081. (The argb format is that used by PixelARGB)
  17082. */
  17083. PixelAlpha (const uint32 argb) throw()
  17084. {
  17085. a = (uint8) (argb >> 24);
  17086. }
  17087. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  17088. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  17089. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  17090. forcedinline uint8 getAlpha() const throw() { return a; }
  17091. forcedinline uint8 getRed() const throw() { return 0; }
  17092. forcedinline uint8 getGreen() const throw() { return 0; }
  17093. forcedinline uint8 getBlue() const throw() { return 0; }
  17094. /** Blends another pixel onto this one.
  17095. This takes into account the opacity of the pixel being overlaid, and blends
  17096. it accordingly.
  17097. */
  17098. template <class Pixel>
  17099. forcedinline void blend (const Pixel& src) throw()
  17100. {
  17101. const int srcA = src.getAlpha();
  17102. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  17103. }
  17104. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17105. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17106. being used, so this can blend semi-transparently from a PixelRGB argument.
  17107. */
  17108. template <class Pixel>
  17109. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17110. {
  17111. ++extraAlpha;
  17112. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  17113. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  17114. }
  17115. /** Blends another pixel with this one, creating a colour that is somewhere
  17116. between the two, as specified by the amount.
  17117. */
  17118. template <class Pixel>
  17119. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17120. {
  17121. a += ((src,getAlpha() - a) * amount) >> 8;
  17122. }
  17123. /** Copies another pixel colour over this one.
  17124. This doesn't blend it - this colour is simply replaced by the other one.
  17125. */
  17126. template <class Pixel>
  17127. forcedinline void set (const Pixel& src) throw()
  17128. {
  17129. a = src.getAlpha();
  17130. }
  17131. /** Replaces the colour's alpha value with another one. */
  17132. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17133. {
  17134. a = newAlpha;
  17135. }
  17136. /** Multiplies the colour's alpha value with another one. */
  17137. forcedinline void multiplyAlpha (int multiplier) throw()
  17138. {
  17139. ++multiplier;
  17140. a = (uint8) ((a * multiplier) >> 8);
  17141. }
  17142. forcedinline void multiplyAlpha (const float multiplier) throw()
  17143. {
  17144. a = (uint8) (a * multiplier);
  17145. }
  17146. /** Sets the pixel's colour from individual components. */
  17147. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  17148. {
  17149. a = a_;
  17150. }
  17151. /** Premultiplies the pixel's RGB values by its alpha. */
  17152. forcedinline void premultiply() throw()
  17153. {
  17154. }
  17155. /** Unpremultiplies the pixel's RGB values. */
  17156. forcedinline void unpremultiply() throw()
  17157. {
  17158. }
  17159. forcedinline void desaturate() throw()
  17160. {
  17161. }
  17162. /** The indexes of the different components in the byte layout of this type of colour. */
  17163. enum { indexA = 0 };
  17164. private:
  17165. uint8 a : 8;
  17166. } PACKED;
  17167. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  17168. {
  17169. blend (PixelARGB (src.getARGB()));
  17170. }
  17171. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  17172. {
  17173. uint32 sargb = src.getARGB();
  17174. const uint32 alpha = 0x100 - (sargb >> 24);
  17175. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17176. sargb += 0xff00ff00 & (getAG() * alpha);
  17177. argb = sargb;
  17178. }
  17179. #if JUCE_MSVC
  17180. #pragma pack (pop)
  17181. #endif
  17182. #undef PACKED
  17183. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  17184. /*** End of inlined file: juce_PixelFormats.h ***/
  17185. /**
  17186. Represents a colour, also including a transparency value.
  17187. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  17188. */
  17189. class JUCE_API Colour
  17190. {
  17191. public:
  17192. /** Creates a transparent black colour. */
  17193. Colour() throw();
  17194. /** Creates a copy of another Colour object. */
  17195. Colour (const Colour& other) throw();
  17196. /** Creates a colour from a 32-bit ARGB value.
  17197. The format of this number is:
  17198. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  17199. All components in the range 0x00 to 0xff.
  17200. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17201. @see getPixelARGB
  17202. */
  17203. explicit Colour (uint32 argb) throw();
  17204. /** Creates an opaque colour using 8-bit red, green and blue values */
  17205. Colour (uint8 red,
  17206. uint8 green,
  17207. uint8 blue) throw();
  17208. /** Creates an opaque colour using 8-bit red, green and blue values */
  17209. static const Colour fromRGB (uint8 red,
  17210. uint8 green,
  17211. uint8 blue) throw();
  17212. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17213. Colour (uint8 red,
  17214. uint8 green,
  17215. uint8 blue,
  17216. uint8 alpha) throw();
  17217. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17218. static const Colour fromRGBA (uint8 red,
  17219. uint8 green,
  17220. uint8 blue,
  17221. uint8 alpha) throw();
  17222. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  17223. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  17224. Values outside the valid range will be clipped.
  17225. */
  17226. Colour (uint8 red,
  17227. uint8 green,
  17228. uint8 blue,
  17229. float alpha) throw();
  17230. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  17231. static const Colour fromRGBAFloat (uint8 red,
  17232. uint8 green,
  17233. uint8 blue,
  17234. float alpha) throw();
  17235. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17236. The floating point values must be between 0.0 and 1.0.
  17237. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17238. Values outside the valid range will be clipped.
  17239. */
  17240. Colour (float hue,
  17241. float saturation,
  17242. float brightness,
  17243. uint8 alpha) throw();
  17244. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  17245. All values must be between 0.0 and 1.0.
  17246. Numbers outside the valid range will be clipped.
  17247. */
  17248. Colour (float hue,
  17249. float saturation,
  17250. float brightness,
  17251. float alpha) throw();
  17252. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17253. The floating point values must be between 0.0 and 1.0.
  17254. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17255. Values outside the valid range will be clipped.
  17256. */
  17257. static const Colour fromHSV (float hue,
  17258. float saturation,
  17259. float brightness,
  17260. float alpha) throw();
  17261. /** Destructor. */
  17262. ~Colour() throw();
  17263. /** Copies another Colour object. */
  17264. Colour& operator= (const Colour& other) throw();
  17265. /** Compares two colours. */
  17266. bool operator== (const Colour& other) const throw();
  17267. /** Compares two colours. */
  17268. bool operator!= (const Colour& other) const throw();
  17269. /** Returns the red component of this colour.
  17270. @returns a value between 0x00 and 0xff.
  17271. */
  17272. uint8 getRed() const throw() { return argb.getRed(); }
  17273. /** Returns the green component of this colour.
  17274. @returns a value between 0x00 and 0xff.
  17275. */
  17276. uint8 getGreen() const throw() { return argb.getGreen(); }
  17277. /** Returns the blue component of this colour.
  17278. @returns a value between 0x00 and 0xff.
  17279. */
  17280. uint8 getBlue() const throw() { return argb.getBlue(); }
  17281. /** Returns the red component of this colour as a floating point value.
  17282. @returns a value between 0.0 and 1.0
  17283. */
  17284. float getFloatRed() const throw();
  17285. /** Returns the green component of this colour as a floating point value.
  17286. @returns a value between 0.0 and 1.0
  17287. */
  17288. float getFloatGreen() const throw();
  17289. /** Returns the blue component of this colour as a floating point value.
  17290. @returns a value between 0.0 and 1.0
  17291. */
  17292. float getFloatBlue() const throw();
  17293. /** Returns a premultiplied ARGB pixel object that represents this colour.
  17294. */
  17295. const PixelARGB getPixelARGB() const throw();
  17296. /** Returns a 32-bit integer that represents this colour.
  17297. The format of this number is:
  17298. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  17299. */
  17300. uint32 getARGB() const throw();
  17301. /** Returns the colour's alpha (opacity).
  17302. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  17303. */
  17304. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  17305. /** Returns the colour's alpha (opacity) as a floating point value.
  17306. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  17307. */
  17308. float getFloatAlpha() const throw();
  17309. /** Returns true if this colour is completely opaque.
  17310. Equivalent to (getAlpha() == 0xff).
  17311. */
  17312. bool isOpaque() const throw();
  17313. /** Returns true if this colour is completely transparent.
  17314. Equivalent to (getAlpha() == 0x00).
  17315. */
  17316. bool isTransparent() const throw();
  17317. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17318. const Colour withAlpha (uint8 newAlpha) const throw();
  17319. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17320. const Colour withAlpha (float newAlpha) const throw();
  17321. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  17322. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  17323. */
  17324. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  17325. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  17326. If the foreground colour is semi-transparent, it is blended onto this colour
  17327. accordingly.
  17328. */
  17329. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  17330. /** Returns a colour that lies somewhere between this one and another.
  17331. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  17332. is 1.0, the result is 100% of the other colour.
  17333. */
  17334. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  17335. /** Returns the colour's hue component.
  17336. The value returned is in the range 0.0 to 1.0
  17337. */
  17338. float getHue() const throw();
  17339. /** Returns the colour's saturation component.
  17340. The value returned is in the range 0.0 to 1.0
  17341. */
  17342. float getSaturation() const throw();
  17343. /** Returns the colour's brightness component.
  17344. The value returned is in the range 0.0 to 1.0
  17345. */
  17346. float getBrightness() const throw();
  17347. /** Returns the colour's hue, saturation and brightness components all at once.
  17348. The values returned are in the range 0.0 to 1.0
  17349. */
  17350. void getHSB (float& hue,
  17351. float& saturation,
  17352. float& brightness) const throw();
  17353. /** Returns a copy of this colour with a different hue. */
  17354. const Colour withHue (float newHue) const throw();
  17355. /** Returns a copy of this colour with a different saturation. */
  17356. const Colour withSaturation (float newSaturation) const throw();
  17357. /** Returns a copy of this colour with a different brightness.
  17358. @see brighter, darker, withMultipliedBrightness
  17359. */
  17360. const Colour withBrightness (float newBrightness) const throw();
  17361. /** Returns a copy of this colour with it hue rotated.
  17362. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  17363. @see brighter, darker, withMultipliedBrightness
  17364. */
  17365. const Colour withRotatedHue (float amountToRotate) const throw();
  17366. /** Returns a copy of this colour with its saturation multiplied by the given value.
  17367. The new colour's saturation is (this->getSaturation() * multiplier)
  17368. (the result is clipped to legal limits).
  17369. */
  17370. const Colour withMultipliedSaturation (float multiplier) const throw();
  17371. /** Returns a copy of this colour with its brightness multiplied by the given value.
  17372. The new colour's saturation is (this->getBrightness() * multiplier)
  17373. (the result is clipped to legal limits).
  17374. */
  17375. const Colour withMultipliedBrightness (float amount) const throw();
  17376. /** Returns a brighter version of this colour.
  17377. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  17378. unchanged, and higher values make it brighter
  17379. @see withMultipliedBrightness
  17380. */
  17381. const Colour brighter (float amountBrighter = 0.4f) const throw();
  17382. /** Returns a darker version of this colour.
  17383. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  17384. unchanged, and higher values make it darker
  17385. @see withMultipliedBrightness
  17386. */
  17387. const Colour darker (float amountDarker = 0.4f) const throw();
  17388. /** Returns a colour that will be clearly visible against this colour.
  17389. The amount parameter indicates how contrasting the new colour should
  17390. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  17391. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  17392. return white; Colours::white.contrasting (1.0f) will return black, etc.
  17393. */
  17394. const Colour contrasting (float amount = 1.0f) const throw();
  17395. /** Returns a colour that contrasts against two colours.
  17396. Looks for a colour that contrasts with both of the colours passed-in.
  17397. Handy for things like choosing a highlight colour in text editors, etc.
  17398. */
  17399. static const Colour contrasting (const Colour& colour1,
  17400. const Colour& colour2) throw();
  17401. /** Returns an opaque shade of grey.
  17402. @param brightness the level of grey to return - 0 is black, 1.0 is white
  17403. */
  17404. static const Colour greyLevel (float brightness) throw();
  17405. /** Returns a stringified version of this colour.
  17406. The string can be turned back into a colour using the fromString() method.
  17407. */
  17408. const String toString() const;
  17409. /** Reads the colour from a string that was created with toString().
  17410. */
  17411. static const Colour fromString (const String& encodedColourString);
  17412. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  17413. const String toDisplayString (bool includeAlphaValue) const;
  17414. juce_UseDebuggingNewOperator
  17415. private:
  17416. PixelARGB argb;
  17417. };
  17418. #endif // __JUCE_COLOUR_JUCEHEADER__
  17419. /*** End of inlined file: juce_Colour.h ***/
  17420. /**
  17421. Contains a set of predefined named colours (mostly standard HTML colours)
  17422. @see Colour, Colours::greyLevel
  17423. */
  17424. class Colours
  17425. {
  17426. public:
  17427. static JUCE_API const Colour
  17428. transparentBlack, /**< ARGB = 0x00000000 */
  17429. transparentWhite, /**< ARGB = 0x00ffffff */
  17430. black, /**< ARGB = 0xff000000 */
  17431. white, /**< ARGB = 0xffffffff */
  17432. blue, /**< ARGB = 0xff0000ff */
  17433. grey, /**< ARGB = 0xff808080 */
  17434. green, /**< ARGB = 0xff008000 */
  17435. red, /**< ARGB = 0xffff0000 */
  17436. yellow, /**< ARGB = 0xffffff00 */
  17437. aliceblue, antiquewhite, aqua, aquamarine,
  17438. azure, beige, bisque, blanchedalmond,
  17439. blueviolet, brown, burlywood, cadetblue,
  17440. chartreuse, chocolate, coral, cornflowerblue,
  17441. cornsilk, crimson, cyan, darkblue,
  17442. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  17443. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  17444. darkorchid, darkred, darksalmon, darkseagreen,
  17445. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  17446. deeppink, deepskyblue, dimgrey, dodgerblue,
  17447. firebrick, floralwhite, forestgreen, fuchsia,
  17448. gainsboro, gold, goldenrod, greenyellow,
  17449. honeydew, hotpink, indianred, indigo,
  17450. ivory, khaki, lavender, lavenderblush,
  17451. lemonchiffon, lightblue, lightcoral, lightcyan,
  17452. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  17453. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  17454. lightsteelblue, lightyellow, lime, limegreen,
  17455. linen, magenta, maroon, mediumaquamarine,
  17456. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  17457. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  17458. midnightblue, mintcream, mistyrose, navajowhite,
  17459. navy, oldlace, olive, olivedrab,
  17460. orange, orangered, orchid, palegoldenrod,
  17461. palegreen, paleturquoise, palevioletred, papayawhip,
  17462. peachpuff, peru, pink, plum,
  17463. powderblue, purple, rosybrown, royalblue,
  17464. saddlebrown, salmon, sandybrown, seagreen,
  17465. seashell, sienna, silver, skyblue,
  17466. slateblue, slategrey, snow, springgreen,
  17467. steelblue, tan, teal, thistle,
  17468. tomato, turquoise, violet, wheat,
  17469. whitesmoke, yellowgreen;
  17470. /** Attempts to look up a string in the list of known colour names, and return
  17471. the appropriate colour.
  17472. A non-case-sensitive search is made of the list of predefined colours, and
  17473. if a match is found, that colour is returned. If no match is found, the
  17474. colour passed in as the defaultColour parameter is returned.
  17475. */
  17476. static JUCE_API const Colour findColourForName (const String& colourName,
  17477. const Colour& defaultColour);
  17478. private:
  17479. // this isn't a class you should ever instantiate - it's just here for the
  17480. // static values in it.
  17481. Colours();
  17482. Colours (const Colours&);
  17483. Colours& operator= (const Colours&);
  17484. };
  17485. #endif // __JUCE_COLOURS_JUCEHEADER__
  17486. /*** End of inlined file: juce_Colours.h ***/
  17487. /*** Start of inlined file: juce_FillType.h ***/
  17488. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  17489. #define __JUCE_FILLTYPE_JUCEHEADER__
  17490. /*** Start of inlined file: juce_ColourGradient.h ***/
  17491. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  17492. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  17493. /**
  17494. Describes the layout and colours that should be used to paint a colour gradient.
  17495. @see Graphics::setGradientFill
  17496. */
  17497. class JUCE_API ColourGradient
  17498. {
  17499. public:
  17500. /** Creates a gradient object.
  17501. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  17502. colour2 should be. In between them there's a gradient.
  17503. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  17504. its centre.
  17505. The alpha transparencies of the colours are used, so note that
  17506. if you blend from transparent to a solid colour, the RGB of the transparent
  17507. colour will become visible in parts of the gradient. e.g. blending
  17508. from Colour::transparentBlack to Colours::white will produce a
  17509. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  17510. will be white all the way across.
  17511. @see ColourGradient
  17512. */
  17513. ColourGradient (const Colour& colour1, float x1, float y1,
  17514. const Colour& colour2, float x2, float y2,
  17515. bool isRadial);
  17516. /** Creates an uninitialised gradient.
  17517. If you use this constructor instead of the other one, be sure to set all the
  17518. object's public member variables before using it!
  17519. */
  17520. ColourGradient() throw();
  17521. /** Destructor */
  17522. ~ColourGradient();
  17523. /** Removes any colours that have been added.
  17524. This will also remove any start and end colours, so the gradient won't work. You'll
  17525. need to add more colours with addColour().
  17526. */
  17527. void clearColours();
  17528. /** Adds a colour at a point along the length of the gradient.
  17529. This allows the gradient to go through a spectrum of colours, instead of just a
  17530. start and end colour.
  17531. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  17532. of the distance along the line between the two points
  17533. at which the colour should occur.
  17534. @param colour the colour that should be used at this point
  17535. */
  17536. void addColour (double proportionAlongGradient,
  17537. const Colour& colour);
  17538. /** Multiplies the alpha value of all the colours by the given scale factor */
  17539. void multiplyOpacity (float multiplier) throw();
  17540. /** Returns the number of colour-stops that have been added. */
  17541. int getNumColours() const throw();
  17542. /** Returns the position along the length of the gradient of the colour with this index.
  17543. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  17544. */
  17545. double getColourPosition (int index) const throw();
  17546. /** Returns the colour that was added with a given index.
  17547. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  17548. */
  17549. const Colour getColour (int index) const throw();
  17550. /** Returns the an interpolated colour at any position along the gradient.
  17551. @param position the position along the gradient, between 0 and 1
  17552. */
  17553. const Colour getColourAtPosition (float position) const throw();
  17554. /** Creates a set of interpolated premultiplied ARGB values.
  17555. This will resize the HeapBlock, fill it with the colours, and will return the number of
  17556. colours that it added.
  17557. */
  17558. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  17559. /** Returns true if all colours are opaque. */
  17560. bool isOpaque() const throw();
  17561. /** Returns true if all colours are completely transparent. */
  17562. bool isInvisible() const throw();
  17563. Point<float> point1, point2;
  17564. /** If true, the gradient should be filled circularly, centred around
  17565. point1, with point2 defining a point on the circumference.
  17566. If false, the gradient is linear between the two points.
  17567. */
  17568. bool isRadial;
  17569. bool operator== (const ColourGradient& other) const throw();
  17570. bool operator!= (const ColourGradient& other) const throw();
  17571. juce_UseDebuggingNewOperator
  17572. private:
  17573. struct ColourPoint
  17574. {
  17575. ColourPoint() throw() {}
  17576. ColourPoint (uint32 position_, const Colour& colour_) throw()
  17577. : position (position_), colour (colour_)
  17578. {}
  17579. bool operator== (const ColourPoint& other) const throw() { return position == other.position && colour == other.colour; }
  17580. bool operator!= (const ColourPoint& other) const throw() { return position != other.position || colour != other.colour; }
  17581. uint32 position;
  17582. Colour colour;
  17583. };
  17584. Array <ColourPoint> colours;
  17585. };
  17586. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  17587. /*** End of inlined file: juce_ColourGradient.h ***/
  17588. class Image;
  17589. /**
  17590. Represents a colour or fill pattern to use for rendering paths.
  17591. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  17592. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  17593. @see Graphics::setFillType, DrawablePath::setFill
  17594. */
  17595. class JUCE_API FillType
  17596. {
  17597. public:
  17598. /** Creates a default fill type, of solid black. */
  17599. FillType() throw();
  17600. /** Creates a fill type of a solid colour.
  17601. @see setColour
  17602. */
  17603. FillType (const Colour& colour) throw();
  17604. /** Creates a gradient fill type.
  17605. @see setGradient
  17606. */
  17607. FillType (const ColourGradient& gradient);
  17608. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  17609. and rotation of the pattern.
  17610. @see setTiledImage
  17611. */
  17612. FillType (const Image& image, const AffineTransform& transform) throw();
  17613. /** Creates a copy of another FillType. */
  17614. FillType (const FillType& other);
  17615. /** Makes a copy of another FillType. */
  17616. FillType& operator= (const FillType& other);
  17617. /** Destructor. */
  17618. ~FillType() throw();
  17619. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  17620. bool isColour() const throw() { return gradient == 0 && image == 0; }
  17621. /** Returns true if this is a gradient fill. */
  17622. bool isGradient() const throw() { return gradient != 0; }
  17623. /** Returns true if this is a tiled image pattern fill. */
  17624. bool isTiledImage() const throw() { return image != 0; }
  17625. /** Turns this object into a solid colour fill.
  17626. If the object was an image or gradient, those fields will no longer be valid. */
  17627. void setColour (const Colour& newColour) throw();
  17628. /** Turns this object into a gradient fill. */
  17629. void setGradient (const ColourGradient& newGradient);
  17630. /** Turns this object into a tiled image fill type. The transform allows you to set
  17631. the scaling, offset and rotation of the pattern.
  17632. */
  17633. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  17634. /** Changes the opacity that should be used.
  17635. If the fill is a solid colour, this just changes the opacity of that colour. For
  17636. gradients and image tiles, it changes the opacity that will be used for them.
  17637. */
  17638. void setOpacity (float newOpacity) throw();
  17639. /** Returns the current opacity to be applied to the colour, gradient, or image.
  17640. @see setOpacity
  17641. */
  17642. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  17643. /** Returns true if this fill type is completely transparent. */
  17644. bool isInvisible() const throw();
  17645. bool operator== (const FillType& other) const;
  17646. bool operator!= (const FillType& other) const;
  17647. /** The solid colour being used.
  17648. If the fill type is not a solid colour, the alpha channel of this colour indicates
  17649. the opacity that should be used for the fill, and the RGB channels are ignored.
  17650. */
  17651. Colour colour;
  17652. /** Returns the gradient that should be used for filling.
  17653. This will be zero if the object is some other type of fill.
  17654. If a gradient is active, the overall opacity with which it should be applied
  17655. is indicated by the alpha channel of the colour variable.
  17656. */
  17657. ScopedPointer <ColourGradient> gradient;
  17658. /** Returns the image that should be used for tiling.
  17659. The FillType object just keeps a pointer to this image, it doesn't own it, so you have to
  17660. be careful to make sure the image doesn't get deleted while it's being used.
  17661. If an image fill is active, the overall opacity with which it should be applied
  17662. is indicated by the alpha channel of the colour variable.
  17663. */
  17664. const Image* image;
  17665. /** The transform that should be applied to the image or gradient that's being drawn.
  17666. */
  17667. AffineTransform transform;
  17668. juce_UseDebuggingNewOperator
  17669. };
  17670. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  17671. /*** End of inlined file: juce_FillType.h ***/
  17672. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  17673. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17674. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17675. /**
  17676. Defines the method used to postion some kind of rectangular object within
  17677. a rectangular viewport.
  17678. Although similar to Justification, this is more specific, and has some extra
  17679. options.
  17680. */
  17681. class JUCE_API RectanglePlacement
  17682. {
  17683. public:
  17684. /** Creates a RectanglePlacement object using a combination of flags. */
  17685. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  17686. /** Creates a copy of another RectanglePlacement object. */
  17687. RectanglePlacement (const RectanglePlacement& other) throw();
  17688. /** Copies another RectanglePlacement object. */
  17689. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  17690. /** Flag values that can be combined and used in the constructor. */
  17691. enum
  17692. {
  17693. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  17694. xLeft = 1,
  17695. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  17696. xRight = 2,
  17697. /** Indicates that the source should be placed in the centre between the left and right
  17698. sides of the available space. */
  17699. xMid = 4,
  17700. /** Indicates that the source's top edge should be aligned with the top edge of the
  17701. destination rectangle. */
  17702. yTop = 8,
  17703. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  17704. destination rectangle. */
  17705. yBottom = 16,
  17706. /** Indicates that the source should be placed in the centre between the top and bottom
  17707. sides of the available space. */
  17708. yMid = 32,
  17709. /** If this flag is set, then the source rectangle will be resized to completely fill
  17710. the destination rectangle, and all other flags are ignored.
  17711. */
  17712. stretchToFit = 64,
  17713. /** If this flag is set, then the source rectangle will be resized so that it is the
  17714. minimum size to completely fill the destination rectangle, without changing its
  17715. aspect ratio. This means that some of the source rectangle may fall outside
  17716. the destination.
  17717. If this flag is not set, the source will be given the maximum size at which none
  17718. of it falls outside the destination rectangle.
  17719. */
  17720. fillDestination = 128,
  17721. /** Indicates that the source rectangle can be reduced in size if required, but should
  17722. never be made larger than its original size.
  17723. */
  17724. onlyReduceInSize = 256,
  17725. /** Indicates that the source rectangle can be enlarged if required, but should
  17726. never be made smaller than its original size.
  17727. */
  17728. onlyIncreaseInSize = 512,
  17729. /** Indicates that the source rectangle's size should be left unchanged.
  17730. */
  17731. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  17732. /** A shorthand value that is equivalent to (xMid | yMid). */
  17733. centred = 4 + 32
  17734. };
  17735. /** Returns the raw flags that are set for this object. */
  17736. inline int getFlags() const throw() { return flags; }
  17737. /** Tests a set of flags for this object.
  17738. @returns true if any of the flags passed in are set on this object.
  17739. */
  17740. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  17741. /** Adjusts the position and size of a rectangle to fit it into a space.
  17742. The source rectangle co-ordinates will be adjusted so that they fit into
  17743. the destination rectangle based on this object's flags.
  17744. */
  17745. void applyTo (double& sourceX,
  17746. double& sourceY,
  17747. double& sourceW,
  17748. double& sourceH,
  17749. double destinationX,
  17750. double destinationY,
  17751. double destinationW,
  17752. double destinationH) const throw();
  17753. /** Returns the transform that should be applied to these source co-ordinates to fit them
  17754. into the destination rectangle using the current flags.
  17755. */
  17756. const AffineTransform getTransformToFit (float sourceX,
  17757. float sourceY,
  17758. float sourceW,
  17759. float sourceH,
  17760. float destinationX,
  17761. float destinationY,
  17762. float destinationW,
  17763. float destinationH) const throw();
  17764. private:
  17765. int flags;
  17766. };
  17767. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17768. /*** End of inlined file: juce_RectanglePlacement.h ***/
  17769. class LowLevelGraphicsContext;
  17770. class Image;
  17771. class RectangleList;
  17772. /**
  17773. A graphics context, used for drawing a component or image.
  17774. When a Component needs painting, a Graphics context is passed to its
  17775. Component::paint() method, and this you then call methods within this
  17776. object to actually draw the component's content.
  17777. A Graphics can also be created from an image, to allow drawing directly onto
  17778. that image.
  17779. @see Component::paint
  17780. */
  17781. class JUCE_API Graphics
  17782. {
  17783. public:
  17784. /** Creates a Graphics object to draw directly onto the given image.
  17785. The graphics object that is created will be set up to draw onto the image,
  17786. with the context's clipping area being the entire size of the image, and its
  17787. origin being the image's origin. To draw into a subsection of an image, use the
  17788. reduceClipRegion() and setOrigin() methods.
  17789. Obviously you shouldn't delete the image before this context is deleted.
  17790. */
  17791. explicit Graphics (Image& imageToDrawOnto);
  17792. /** Destructor. */
  17793. ~Graphics();
  17794. /** Changes the current drawing colour.
  17795. This sets the colour that will now be used for drawing operations - it also
  17796. sets the opacity to that of the colour passed-in.
  17797. If a brush is being used when this method is called, the brush will be deselected,
  17798. and any subsequent drawing will be done with a solid colour brush instead.
  17799. @see setOpacity
  17800. */
  17801. void setColour (const Colour& newColour);
  17802. /** Changes the opacity to use with the current colour.
  17803. If a solid colour is being used for drawing, this changes its opacity
  17804. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  17805. If a gradient is being used, this will have no effect on it.
  17806. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  17807. */
  17808. void setOpacity (const float newOpacity);
  17809. /** Sets the context to use a gradient for its fill pattern.
  17810. */
  17811. void setGradientFill (const ColourGradient& gradient);
  17812. /** Sets the context to use a tiled image pattern for filling.
  17813. Make sure that you don't delete this image while it's still being used by
  17814. this context!
  17815. */
  17816. void setTiledImageFill (const Image& imageToUse,
  17817. int anchorX, int anchorY,
  17818. float opacity);
  17819. /** Changes the current fill settings.
  17820. @see setColour, setGradientFill, setTiledImageFill
  17821. */
  17822. void setFillType (const FillType& newFill);
  17823. /** Changes the font to use for subsequent text-drawing functions.
  17824. Note there's also a setFont (float, int) method to quickly change the size and
  17825. style of the current font.
  17826. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  17827. */
  17828. void setFont (const Font& newFont);
  17829. /** Changes the size and style of the currently-selected font.
  17830. This is a convenient shortcut that changes the context's current font to a
  17831. different size or style. The typeface won't be changed.
  17832. @see Font
  17833. */
  17834. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  17835. /** Returns the currently selected font. */
  17836. const Font getCurrentFont() const;
  17837. /** Draws a one-line text string.
  17838. This will use the current colour (or brush) to fill the text. The font is the last
  17839. one specified by setFont().
  17840. @param text the string to draw
  17841. @param startX the position to draw the left-hand edge of the text
  17842. @param baselineY the position of the text's baseline
  17843. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  17844. */
  17845. void drawSingleLineText (const String& text,
  17846. int startX, int baselineY) const;
  17847. /** Draws text across multiple lines.
  17848. This will break the text onto a new line where there's a new-line or
  17849. carriage-return character, or at a word-boundary when the text becomes wider
  17850. than the size specified by the maximumLineWidth parameter.
  17851. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  17852. */
  17853. void drawMultiLineText (const String& text,
  17854. int startX, int baselineY,
  17855. int maximumLineWidth) const;
  17856. /** Renders a string of text as a vector path.
  17857. This allows a string to be transformed with an arbitrary AffineTransform and
  17858. rendered using the current colour/brush. It's much slower than the normal text methods
  17859. but more accurate.
  17860. @see setFont
  17861. */
  17862. void drawTextAsPath (const String& text,
  17863. const AffineTransform& transform) const;
  17864. /** Draws a line of text within a specified rectangle.
  17865. The text will be positioned within the rectangle based on the justification
  17866. flags passed-in. If the string is too long to fit inside the rectangle, it will
  17867. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  17868. flag is true).
  17869. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  17870. */
  17871. void drawText (const String& text,
  17872. int x, int y, int width, int height,
  17873. const Justification& justificationType,
  17874. bool useEllipsesIfTooBig) const;
  17875. /** Tries to draw a text string inside a given space.
  17876. This does its best to make the given text readable within the specified rectangle,
  17877. so it useful for labelling things.
  17878. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  17879. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  17880. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  17881. it's been truncated.
  17882. A Justification parameter lets you specify how the text is laid out within the rectangle,
  17883. both horizontally and vertically.
  17884. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  17885. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  17886. can set this value to 1.0f.
  17887. @see GlyphArrangement::addFittedText
  17888. */
  17889. void drawFittedText (const String& text,
  17890. int x, int y, int width, int height,
  17891. const Justification& justificationFlags,
  17892. int maximumNumberOfLines,
  17893. float minimumHorizontalScale = 0.7f) const;
  17894. /** Fills the context's entire clip region with the current colour or brush.
  17895. (See also the fillAll (const Colour&) method which is a quick way of filling
  17896. it with a given colour).
  17897. */
  17898. void fillAll() const;
  17899. /** Fills the context's entire clip region with a given colour.
  17900. This leaves the context's current colour and brush unchanged, it just
  17901. uses the specified colour temporarily.
  17902. */
  17903. void fillAll (const Colour& colourToUse) const;
  17904. /** Fills a rectangle with the current colour or brush.
  17905. @see drawRect, fillRoundedRectangle
  17906. */
  17907. void fillRect (int x, int y, int width, int height) const;
  17908. /** Fills a rectangle with the current colour or brush. */
  17909. void fillRect (const Rectangle<int>& rectangle) const;
  17910. /** Fills a rectangle with the current colour or brush.
  17911. This uses sub-pixel positioning so is slower than the fillRect method which
  17912. takes integer co-ordinates.
  17913. */
  17914. void fillRect (float x, float y, float width, float height) const;
  17915. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  17916. @see drawRoundedRectangle, Path::addRoundedRectangle
  17917. */
  17918. void fillRoundedRectangle (float x, float y, float width, float height,
  17919. float cornerSize) const;
  17920. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  17921. @see drawRoundedRectangle, Path::addRoundedRectangle
  17922. */
  17923. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  17924. float cornerSize) const;
  17925. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  17926. */
  17927. void fillCheckerBoard (int x, int y, int width, int height,
  17928. int checkWidth, int checkHeight,
  17929. const Colour& colour1, const Colour& colour2) const;
  17930. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  17931. The lines are drawn inside the given rectangle, and greater line thicknesses
  17932. extend inwards.
  17933. @see fillRect
  17934. */
  17935. void drawRect (int x, int y, int width, int height,
  17936. int lineThickness = 1) const;
  17937. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  17938. The lines are drawn inside the given rectangle, and greater line thicknesses
  17939. extend inwards.
  17940. @see fillRect
  17941. */
  17942. void drawRect (float x, float y, float width, float height,
  17943. float lineThickness = 1.0f) const;
  17944. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  17945. The lines are drawn inside the given rectangle, and greater line thicknesses
  17946. extend inwards.
  17947. @see fillRect
  17948. */
  17949. void drawRect (const Rectangle<int>& rectangle,
  17950. int lineThickness = 1) const;
  17951. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  17952. @see fillRoundedRectangle, Path::addRoundedRectangle
  17953. */
  17954. void drawRoundedRectangle (float x, float y, float width, float height,
  17955. float cornerSize, float lineThickness) const;
  17956. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  17957. @see fillRoundedRectangle, Path::addRoundedRectangle
  17958. */
  17959. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  17960. float cornerSize, float lineThickness) const;
  17961. /** Draws a 3D raised (or indented) bevel using two colours.
  17962. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  17963. extend inwards.
  17964. The top-left colour is used for the top- and left-hand edges of the
  17965. bevel; the bottom-right colour is used for the bottom- and right-hand
  17966. edges.
  17967. If useGradient is true, then the bevel fades out to make it look more curved
  17968. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  17969. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  17970. the centre edges are sharp and it fades towards the outside.
  17971. */
  17972. void drawBevel (int x, int y, int width, int height,
  17973. int bevelThickness,
  17974. const Colour& topLeftColour = Colours::white,
  17975. const Colour& bottomRightColour = Colours::black,
  17976. bool useGradient = true,
  17977. bool sharpEdgeOnOutside = true) const;
  17978. /** Draws a pixel using the current colour or brush.
  17979. */
  17980. void setPixel (int x, int y) const;
  17981. /** Fills an ellipse with the current colour or brush.
  17982. The ellipse is drawn to fit inside the given rectangle.
  17983. @see drawEllipse, Path::addEllipse
  17984. */
  17985. void fillEllipse (float x, float y, float width, float height) const;
  17986. /** Draws an elliptical stroke using the current colour or brush.
  17987. @see fillEllipse, Path::addEllipse
  17988. */
  17989. void drawEllipse (float x, float y, float width, float height,
  17990. float lineThickness) const;
  17991. /** Draws a line between two points.
  17992. The line is 1 pixel wide and drawn with the current colour or brush.
  17993. */
  17994. void drawLine (float startX, float startY, float endX, float endY) const;
  17995. /** Draws a line between two points with a given thickness.
  17996. @see Path::addLineSegment
  17997. */
  17998. void drawLine (float startX, float startY, float endX, float endY,
  17999. float lineThickness) const;
  18000. /** Draws a line between two points.
  18001. The line is 1 pixel wide and drawn with the current colour or brush.
  18002. */
  18003. void drawLine (const Line<float>& line) const;
  18004. /** Draws a line between two points with a given thickness.
  18005. @see Path::addLineSegment
  18006. */
  18007. void drawLine (const Line<float>& line, float lineThickness) const;
  18008. /** Draws a dashed line using a custom set of dash-lengths.
  18009. @param startX the line's start x co-ordinate
  18010. @param startY the line's start y co-ordinate
  18011. @param endX the line's end x co-ordinate
  18012. @param endY the line's end y co-ordinate
  18013. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  18014. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  18015. draw 6 pixels, skip 7 pixels, and then repeat.
  18016. @param numDashLengths the number of elements in the array (this must be an even number).
  18017. @param lineThickness the thickness of the line to draw
  18018. @see PathStrokeType::createDashedStroke
  18019. */
  18020. void drawDashedLine (float startX, float startY,
  18021. float endX, float endY,
  18022. const float* dashLengths, int numDashLengths,
  18023. float lineThickness = 1.0f) const;
  18024. /** Draws a vertical line of pixels at a given x position.
  18025. The x position is an integer, but the top and bottom of the line can be sub-pixel
  18026. positions, and these will be anti-aliased if necessary.
  18027. */
  18028. void drawVerticalLine (int x, float top, float bottom) const;
  18029. /** Draws a horizontal line of pixels at a given y position.
  18030. The y position is an integer, but the left and right ends of the line can be sub-pixel
  18031. positions, and these will be anti-aliased if necessary.
  18032. */
  18033. void drawHorizontalLine (int y, float left, float right) const;
  18034. /** Fills a path using the currently selected colour or brush.
  18035. */
  18036. void fillPath (const Path& path,
  18037. const AffineTransform& transform = AffineTransform::identity) const;
  18038. /** Draws a path's outline using the currently selected colour or brush.
  18039. */
  18040. void strokePath (const Path& path,
  18041. const PathStrokeType& strokeType,
  18042. const AffineTransform& transform = AffineTransform::identity) const;
  18043. /** Draws a line with an arrowhead.
  18044. @param startX the line's start x co-ordinate
  18045. @param startY the line's start y co-ordinate
  18046. @param endX the line's end x co-ordinate (the tip of the arrowhead)
  18047. @param endY the line's end y co-ordinate (the tip of the arrowhead)
  18048. @param lineThickness the thickness of the line
  18049. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  18050. @param arrowheadLength the length of the arrow head (along the length of the line)
  18051. */
  18052. void drawArrow (float startX, float startY,
  18053. float endX, float endY,
  18054. float lineThickness,
  18055. float arrowheadWidth,
  18056. float arrowheadLength) const;
  18057. /** Types of rendering quality that can be specified when drawing images.
  18058. @see blendImage, Graphics::setImageResamplingQuality
  18059. */
  18060. enum ResamplingQuality
  18061. {
  18062. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  18063. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  18064. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  18065. };
  18066. /** Changes the quality that will be used when resampling images.
  18067. By default a Graphics object will be set to mediumRenderingQuality.
  18068. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  18069. */
  18070. void setImageResamplingQuality (const ResamplingQuality newQuality);
  18071. /** Draws an image.
  18072. This will draw the whole of an image, positioning its top-left corner at the
  18073. given co-ordinates, and keeping its size the same. This is the simplest image
  18074. drawing method - the others give more control over the scaling and clipping
  18075. of the images.
  18076. Images are composited using the context's current opacity, so if you
  18077. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18078. (or setColour() with an opaque colour) before drawing images.
  18079. */
  18080. void drawImageAt (const Image* const imageToDraw, int topLeftX, int topLeftY,
  18081. bool fillAlphaChannelWithCurrentBrush = false) const;
  18082. /** Draws part of an image, rescaling it to fit in a given target region.
  18083. The specified area of the source image is rescaled and drawn to fill the
  18084. specifed destination rectangle.
  18085. Images are composited using the context's current opacity, so if you
  18086. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18087. (or setColour() with an opaque colour) before drawing images.
  18088. @param imageToDraw the image to overlay
  18089. @param destX the left of the destination rectangle
  18090. @param destY the top of the destination rectangle
  18091. @param destWidth the width of the destination rectangle
  18092. @param destHeight the height of the destination rectangle
  18093. @param sourceX the left of the rectangle to copy from the source image
  18094. @param sourceY the top of the rectangle to copy from the source image
  18095. @param sourceWidth the width of the rectangle to copy from the source image
  18096. @param sourceHeight the height of the rectangle to copy from the source image
  18097. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  18098. the source image's alpha channel is used as a mask with
  18099. which to fill the destination using the current colour
  18100. or brush. (If the source is has no alpha channel, then
  18101. it will just fill the target with a solid rectangle)
  18102. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  18103. */
  18104. void drawImage (const Image* const imageToDraw,
  18105. int destX, int destY, int destWidth, int destHeight,
  18106. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  18107. bool fillAlphaChannelWithCurrentBrush = false) const;
  18108. /** Draws part of an image, having applied an affine transform to it.
  18109. This lets you throw the image around in some wacky ways, rotate it, shear,
  18110. scale it, etc.
  18111. A subregion is specified within the source image, and all transformations
  18112. will be treated as relative to the origin of this sub-region. So, for example if
  18113. your subregion is (50, 50, 100, 100), and your transform is a translation of (20, 20),
  18114. the resulting pixel drawn at (20, 20) in the destination context is from (50, 50) in
  18115. your image. If you want to use the whole image, then Image::getBounds() returns a
  18116. suitable rectangle to use as the imageSubRegion parameter.
  18117. Images are composited using the context's current opacity, so if you
  18118. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18119. (or setColour() with an opaque colour) before drawing images.
  18120. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  18121. are ignored and it is filled with the current brush, masked by its alpha channel.
  18122. @see setImageResamplingQuality, drawImage
  18123. */
  18124. void drawImageTransformed (const Image* imageToDraw,
  18125. const Rectangle<int>& imageSubRegion,
  18126. const AffineTransform& transform,
  18127. bool fillAlphaChannelWithCurrentBrush = false) const;
  18128. /** Draws an image to fit within a designated rectangle.
  18129. If the image is too big or too small for the space, it will be rescaled
  18130. to fit as nicely as it can do without affecting its aspect ratio. It will
  18131. then be placed within the target rectangle according to the justification flags
  18132. specified.
  18133. @param imageToDraw the source image to draw
  18134. @param destX top-left of the target rectangle to fit it into
  18135. @param destY top-left of the target rectangle to fit it into
  18136. @param destWidth size of the target rectangle to fit the image into
  18137. @param destHeight size of the target rectangle to fit the image into
  18138. @param placementWithinTarget this specifies how the image should be positioned
  18139. within the target rectangle - see the RectanglePlacement
  18140. class for more details about this.
  18141. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  18142. alpha channel will be used as a mask with which to
  18143. draw with the current brush or colour. This is
  18144. similar to fillAlphaMap(), and see also drawImage()
  18145. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  18146. */
  18147. void drawImageWithin (const Image* imageToDraw,
  18148. int destX, int destY, int destWidth, int destHeight,
  18149. const RectanglePlacement& placementWithinTarget,
  18150. bool fillAlphaChannelWithCurrentBrush = false) const;
  18151. /** Returns the position of the bounding box for the current clipping region.
  18152. @see getClipRegion, clipRegionIntersects
  18153. */
  18154. const Rectangle<int> getClipBounds() const;
  18155. /** Checks whether a rectangle overlaps the context's clipping region.
  18156. If this returns false, no part of the given area can be drawn onto, so this
  18157. method can be used to optimise a component's paint() method, by letting it
  18158. avoid drawing complex objects that aren't within the region being repainted.
  18159. */
  18160. bool clipRegionIntersects (int x, int y, int width, int height) const;
  18161. /** Intersects the current clipping region with another region.
  18162. @returns true if the resulting clipping region is non-zero in size
  18163. @see setOrigin, clipRegionIntersects
  18164. */
  18165. bool reduceClipRegion (int x, int y, int width, int height);
  18166. /** Intersects the current clipping region with a rectangle list region.
  18167. @returns true if the resulting clipping region is non-zero in size
  18168. @see setOrigin, clipRegionIntersects
  18169. */
  18170. bool reduceClipRegion (const RectangleList& clipRegion);
  18171. /** Intersects the current clipping region with a path.
  18172. @returns true if the resulting clipping region is non-zero in size
  18173. @see reduceClipRegion
  18174. */
  18175. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  18176. /** Intersects the current clipping region with an image's alpha-channel.
  18177. The current clipping path is intersected with the area covered by this image's
  18178. alpha-channel, after the image has been transformed by the specified matrix.
  18179. @param image the image whose alpha-channel should be used. If the image doesn't
  18180. have an alpha-channel, it is treated as entirely opaque.
  18181. @param sourceClipRegion a subsection of the image that should be used. To use the
  18182. entire image, just pass a rectangle of bounds
  18183. (0, 0, image.getWidth(), image.getHeight()).
  18184. @param transform a matrix to apply to the image
  18185. @returns true if the resulting clipping region is non-zero in size
  18186. @see reduceClipRegion
  18187. */
  18188. bool reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion,
  18189. const AffineTransform& transform);
  18190. /** Excludes a rectangle to stop it being drawn into. */
  18191. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  18192. /** Returns true if no drawing can be done because the clip region is zero. */
  18193. bool isClipEmpty() const;
  18194. /** Saves the current graphics state on an internal stack.
  18195. To restore the state, use restoreState().
  18196. */
  18197. void saveState();
  18198. /** Restores a graphics state that was previously saved with saveState().
  18199. */
  18200. void restoreState();
  18201. /** Moves the position of the context's origin.
  18202. This changes the position that the context considers to be (0, 0) to
  18203. the specified position.
  18204. So if you call setOrigin (100, 100), then the position that was previously
  18205. referred to as (100, 100) will subsequently be considered to be (0, 0).
  18206. @see reduceClipRegion
  18207. */
  18208. void setOrigin (int newOriginX, int newOriginY);
  18209. /** Resets the current colour, brush, and font to default settings. */
  18210. void resetToDefaultState();
  18211. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  18212. bool isVectorDevice() const;
  18213. juce_UseDebuggingNewOperator
  18214. /** Create a graphics that uses a given low-level renderer.
  18215. For internal use only.
  18216. NB. The context will NOT be deleted by this object when it is deleted.
  18217. */
  18218. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  18219. /** @internal */
  18220. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  18221. private:
  18222. LowLevelGraphicsContext* const context;
  18223. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  18224. bool saveStatePending;
  18225. void saveStateIfPending();
  18226. Graphics (const Graphics&);
  18227. Graphics& operator= (const Graphics& other);
  18228. };
  18229. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  18230. /*** End of inlined file: juce_Graphics.h ***/
  18231. /**
  18232. A graphical effect filter that can be applied to components.
  18233. An ImageEffectFilter can be applied to the image that a component
  18234. paints before it hits the screen.
  18235. This is used for adding effects like shadows, blurs, etc.
  18236. @see Component::setComponentEffect
  18237. */
  18238. class JUCE_API ImageEffectFilter
  18239. {
  18240. public:
  18241. /** Overridden to render the effect.
  18242. The implementation of this method must use the image that is passed in
  18243. as its source, and should render its output to the graphics context passed in.
  18244. @param sourceImage the image that the source component has just rendered with
  18245. its paint() method. The image may or may not have an alpha
  18246. channel, depending on whether the component is opaque.
  18247. @param destContext the graphics context to use to draw the resultant image.
  18248. */
  18249. virtual void applyEffect (Image& sourceImage,
  18250. Graphics& destContext) = 0;
  18251. /** Destructor. */
  18252. virtual ~ImageEffectFilter() {}
  18253. };
  18254. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18255. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  18256. /*** Start of inlined file: juce_RectangleList.h ***/
  18257. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  18258. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  18259. /**
  18260. Maintains a set of rectangles as a complex region.
  18261. This class allows a set of rectangles to be treated as a solid shape, and can
  18262. add and remove rectangular sections of it, and simplify overlapping or
  18263. adjacent rectangles.
  18264. @see Rectangle
  18265. */
  18266. class JUCE_API RectangleList
  18267. {
  18268. public:
  18269. /** Creates an empty RectangleList */
  18270. RectangleList() throw();
  18271. /** Creates a copy of another list */
  18272. RectangleList (const RectangleList& other);
  18273. /** Creates a list containing just one rectangle. */
  18274. RectangleList (const Rectangle<int>& rect);
  18275. /** Copies this list from another one. */
  18276. RectangleList& operator= (const RectangleList& other);
  18277. /** Destructor. */
  18278. ~RectangleList();
  18279. /** Returns true if the region is empty. */
  18280. bool isEmpty() const throw();
  18281. /** Returns the number of rectangles in the list. */
  18282. int getNumRectangles() const throw() { return rects.size(); }
  18283. /** Returns one of the rectangles at a particular index.
  18284. @returns the rectangle at the index, or an empty rectangle if the
  18285. index is out-of-range.
  18286. */
  18287. const Rectangle<int> getRectangle (int index) const throw();
  18288. /** Removes all rectangles to leave an empty region. */
  18289. void clear();
  18290. /** Merges a new rectangle into the list.
  18291. The rectangle being added will first be clipped to remove any parts of it
  18292. that overlap existing rectangles in the list.
  18293. */
  18294. void add (int x, int y, int width, int height);
  18295. /** Merges a new rectangle into the list.
  18296. The rectangle being added will first be clipped to remove any parts of it
  18297. that overlap existing rectangles in the list, and adjacent rectangles will be
  18298. merged into it.
  18299. */
  18300. void add (const Rectangle<int>& rect);
  18301. /** Dumbly adds a rectangle to the list without checking for overlaps.
  18302. This simply adds the rectangle to the end, it doesn't merge it or remove
  18303. any overlapping bits.
  18304. */
  18305. void addWithoutMerging (const Rectangle<int>& rect);
  18306. /** Merges another rectangle list into this one.
  18307. Any overlaps between the two lists will be clipped, so that the result is
  18308. the union of both lists.
  18309. */
  18310. void add (const RectangleList& other);
  18311. /** Removes a rectangular region from the list.
  18312. Any rectangles in the list which overlap this will be clipped and subdivided
  18313. if necessary.
  18314. */
  18315. void subtract (const Rectangle<int>& rect);
  18316. /** Removes all areas in another RectangleList from this one.
  18317. Any rectangles in the list which overlap this will be clipped and subdivided
  18318. if necessary.
  18319. @returns true if the resulting list is non-empty.
  18320. */
  18321. bool subtract (const RectangleList& otherList);
  18322. /** Removes any areas of the region that lie outside a given rectangle.
  18323. Any rectangles in the list which overlap this will be clipped and subdivided
  18324. if necessary.
  18325. Returns true if the resulting region is not empty, false if it is empty.
  18326. @see getIntersectionWith
  18327. */
  18328. bool clipTo (const Rectangle<int>& rect);
  18329. /** Removes any areas of the region that lie outside a given rectangle list.
  18330. Any rectangles in this object which overlap the specified list will be clipped
  18331. and subdivided if necessary.
  18332. Returns true if the resulting region is not empty, false if it is empty.
  18333. @see getIntersectionWith
  18334. */
  18335. bool clipTo (const RectangleList& other);
  18336. /** Creates a region which is the result of clipping this one to a given rectangle.
  18337. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  18338. resulting region into the list whose reference is passed-in.
  18339. Returns true if the resulting region is not empty, false if it is empty.
  18340. @see clipTo
  18341. */
  18342. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  18343. /** Swaps the contents of this and another list.
  18344. This swaps their internal pointers, so is hugely faster than using copy-by-value
  18345. to swap them.
  18346. */
  18347. void swapWith (RectangleList& otherList) throw();
  18348. /** Checks whether the region contains a given point.
  18349. @returns true if the point lies within one of the rectangles in the list
  18350. */
  18351. bool containsPoint (int x, int y) const throw();
  18352. /** Checks whether the region contains the whole of a given rectangle.
  18353. @returns true all parts of the rectangle passed in lie within the region
  18354. defined by this object
  18355. @see intersectsRectangle, containsPoint
  18356. */
  18357. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  18358. /** Checks whether the region contains any part of a given rectangle.
  18359. @returns true if any part of the rectangle passed in lies within the region
  18360. defined by this object
  18361. @see containsRectangle
  18362. */
  18363. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  18364. /** Checks whether this region intersects any part of another one.
  18365. @see intersectsRectangle
  18366. */
  18367. bool intersects (const RectangleList& other) const throw();
  18368. /** Returns the smallest rectangle that can enclose the whole of this region. */
  18369. const Rectangle<int> getBounds() const throw();
  18370. /** Optimises the list into a minimum number of constituent rectangles.
  18371. This will try to combine any adjacent rectangles into larger ones where
  18372. possible, to simplify lists that might have been fragmented by repeated
  18373. add/subtract calls.
  18374. */
  18375. void consolidate();
  18376. /** Adds an x and y value to all the co-ordinates. */
  18377. void offsetAll (int dx, int dy) throw();
  18378. /** Creates a Path object to represent this region. */
  18379. const Path toPath() const;
  18380. /** An iterator for accessing all the rectangles in a RectangleList. */
  18381. class Iterator
  18382. {
  18383. public:
  18384. Iterator (const RectangleList& list) throw();
  18385. ~Iterator();
  18386. /** Advances to the next rectangle, and returns true if it's not finished.
  18387. Call this before using getRectangle() to find the rectangle that was returned.
  18388. */
  18389. bool next() throw();
  18390. /** Returns the current rectangle. */
  18391. const Rectangle<int>* getRectangle() const throw() { return current; }
  18392. juce_UseDebuggingNewOperator
  18393. private:
  18394. const Rectangle<int>* current;
  18395. const RectangleList& owner;
  18396. int index;
  18397. Iterator (const Iterator&);
  18398. Iterator& operator= (const Iterator&);
  18399. };
  18400. juce_UseDebuggingNewOperator
  18401. private:
  18402. friend class Iterator;
  18403. Array <Rectangle<int> > rects;
  18404. };
  18405. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  18406. /*** End of inlined file: juce_RectangleList.h ***/
  18407. /*** Start of inlined file: juce_BorderSize.h ***/
  18408. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  18409. #define __JUCE_BORDERSIZE_JUCEHEADER__
  18410. /**
  18411. Specifies a set of gaps to be left around the sides of a rectangle.
  18412. This is basically the size of the spaces at the top, bottom, left and right of
  18413. a rectangle. It's used by various component classes to specify borders.
  18414. @see Rectangle
  18415. */
  18416. class JUCE_API BorderSize
  18417. {
  18418. public:
  18419. /** Creates a null border.
  18420. All sizes are left as 0.
  18421. */
  18422. BorderSize() throw();
  18423. /** Creates a copy of another border. */
  18424. BorderSize (const BorderSize& other) throw();
  18425. /** Creates a border with the given gaps. */
  18426. BorderSize (int topGap,
  18427. int leftGap,
  18428. int bottomGap,
  18429. int rightGap) throw();
  18430. /** Creates a border with the given gap on all sides. */
  18431. explicit BorderSize (int allGaps) throw();
  18432. /** Destructor. */
  18433. ~BorderSize() throw();
  18434. /** Returns the gap that should be left at the top of the region. */
  18435. int getTop() const throw() { return top; }
  18436. /** Returns the gap that should be left at the top of the region. */
  18437. int getLeft() const throw() { return left; }
  18438. /** Returns the gap that should be left at the top of the region. */
  18439. int getBottom() const throw() { return bottom; }
  18440. /** Returns the gap that should be left at the top of the region. */
  18441. int getRight() const throw() { return right; }
  18442. /** Returns the sum of the top and bottom gaps. */
  18443. int getTopAndBottom() const throw() { return top + bottom; }
  18444. /** Returns the sum of the left and right gaps. */
  18445. int getLeftAndRight() const throw() { return left + right; }
  18446. /** Changes the top gap. */
  18447. void setTop (int newTopGap) throw();
  18448. /** Changes the left gap. */
  18449. void setLeft (int newLeftGap) throw();
  18450. /** Changes the bottom gap. */
  18451. void setBottom (int newBottomGap) throw();
  18452. /** Changes the right gap. */
  18453. void setRight (int newRightGap) throw();
  18454. /** Returns a rectangle with these borders removed from it. */
  18455. const Rectangle<int> subtractedFrom (const Rectangle<int>& original) const throw();
  18456. /** Removes this border from a given rectangle. */
  18457. void subtractFrom (Rectangle<int>& rectangle) const throw();
  18458. /** Returns a rectangle with these borders added around it. */
  18459. const Rectangle<int> addedTo (const Rectangle<int>& original) const throw();
  18460. /** Adds this border around a given rectangle. */
  18461. void addTo (Rectangle<int>& original) const throw();
  18462. bool operator== (const BorderSize& other) const throw();
  18463. bool operator!= (const BorderSize& other) const throw();
  18464. juce_UseDebuggingNewOperator
  18465. private:
  18466. int top, left, bottom, right;
  18467. };
  18468. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  18469. /*** End of inlined file: juce_BorderSize.h ***/
  18470. class LookAndFeel;
  18471. class MouseInputSource;
  18472. class MouseInputSourceInternal;
  18473. class ComponentPeer;
  18474. /**
  18475. The base class for all JUCE user-interface objects.
  18476. */
  18477. class JUCE_API Component : public MouseListener,
  18478. public MessageListener
  18479. {
  18480. public:
  18481. /** Creates a component.
  18482. To get it to actually appear, you'll also need to:
  18483. - Either add it to a parent component or use the addToDesktop() method to
  18484. make it a desktop window
  18485. - Set its size and position to something sensible
  18486. - Use setVisible() to make it visible
  18487. And for it to serve any useful purpose, you'll need to write a
  18488. subclass of Component or use one of the other types of component from
  18489. the library.
  18490. */
  18491. Component();
  18492. /** Destructor.
  18493. Note that when a component is deleted, any child components it might
  18494. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  18495. */
  18496. virtual ~Component();
  18497. /** Creates a component, setting its name at the same time.
  18498. @see getName, setName
  18499. */
  18500. explicit Component (const String& componentName);
  18501. /** Returns the name of this component.
  18502. @see setName
  18503. */
  18504. const String& getName() const throw() { return componentName_; }
  18505. /** Sets the name of this component.
  18506. When the name changes, all registered ComponentListeners will receive a
  18507. ComponentListener::componentNameChanged() callback.
  18508. @see getName
  18509. */
  18510. virtual void setName (const String& newName);
  18511. /** Checks whether this Component object has been deleted.
  18512. This will check whether this object is still a valid component, or whether
  18513. it's been deleted.
  18514. It's safe to call this on null or dangling pointers, but note that there is a
  18515. small risk if another new (but different) component has been created at the
  18516. same memory address which this one occupied, this methods can return a
  18517. false positive.
  18518. */
  18519. bool isValidComponent() const;
  18520. /** Makes the component visible or invisible.
  18521. This method will show or hide the component.
  18522. Note that components default to being non-visible when first created.
  18523. Also note that visible components won't be seen unless all their parent components
  18524. are also visible.
  18525. This method will call visibilityChanged() and also componentVisibilityChanged()
  18526. for any component listeners that are interested in this component.
  18527. @param shouldBeVisible whether to show or hide the component
  18528. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  18529. */
  18530. virtual void setVisible (bool shouldBeVisible);
  18531. /** Tests whether the component is visible or not.
  18532. this doesn't necessarily tell you whether this comp is actually on the screen
  18533. because this depends on whether all the parent components are also visible - use
  18534. isShowing() to find this out.
  18535. @see isShowing, setVisible
  18536. */
  18537. bool isVisible() const throw() { return flags.visibleFlag; }
  18538. /** Called when this component's visiblility changes.
  18539. @see setVisible, isVisible
  18540. */
  18541. virtual void visibilityChanged();
  18542. /** Tests whether this component and all its parents are visible.
  18543. @returns true only if this component and all its parents are visible.
  18544. @see isVisible
  18545. */
  18546. bool isShowing() const;
  18547. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  18548. To do this, this function will cunningly:
  18549. - take a snapshot of the component as it currently looks
  18550. - call setVisible(false) on the component
  18551. - replace it with a special component that will continue drawing the
  18552. snapshot, animating it and gradually making it more transparent
  18553. - when it's gone, the special component will also be deleted
  18554. As soon as this method returns, the component can be safely removed and deleted
  18555. leaving the proxy to do the fade-out, so it's even ok to call this in a
  18556. component's destructor.
  18557. Passing non-zero x and y values will cause the ghostly component image to
  18558. also whizz off by this distance while fading out. If the scale factor is
  18559. not 1.0, it will also zoom from the component's current size to this new size.
  18560. One thing to be careful about is that the parent component must be able to cope
  18561. with this unknown component type being added to it.
  18562. */
  18563. void fadeOutComponent (int lengthOfFadeOutInMilliseconds,
  18564. int deltaXToMove = 0,
  18565. int deltaYToMove = 0,
  18566. float scaleFactorAtEnd = 1.0f);
  18567. /** Makes this component appear as a window on the desktop.
  18568. Note that before calling this, you should make sure that the component's opacity is
  18569. set correctly using setOpaque(). If the component is non-opaque, the windowing
  18570. system will try to create a special transparent window for it, which will generally take
  18571. a lot more CPU to operate (and might not even be possible on some platforms).
  18572. If the component is inside a parent component at the time this method is called, it
  18573. will be first be removed from that parent. Likewise if a component on the desktop
  18574. is subsequently added to another component, it'll be removed from the desktop.
  18575. @param windowStyleFlags a combination of the flags specified in the
  18576. ComponentPeer::StyleFlags enum, which define the
  18577. window's characteristics.
  18578. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  18579. in which the juce component should place itself. On Windows,
  18580. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  18581. supported on all platforms, and best left as 0 unless you know
  18582. what you're doing
  18583. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  18584. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  18585. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  18586. */
  18587. virtual void addToDesktop (int windowStyleFlags,
  18588. void* nativeWindowToAttachTo = 0);
  18589. /** If the component is currently showing on the desktop, this will hide it.
  18590. You can also use setVisible() to hide a desktop window temporarily, but
  18591. removeFromDesktop() will free any system resources that are being used up.
  18592. @see addToDesktop, isOnDesktop
  18593. */
  18594. void removeFromDesktop();
  18595. /** Returns true if this component is currently showing on the desktop.
  18596. @see addToDesktop, removeFromDesktop
  18597. */
  18598. bool isOnDesktop() const throw();
  18599. /** Returns the heavyweight window that contains this component.
  18600. If this component is itself on the desktop, this will return the window
  18601. object that it is using. Otherwise, it will return the window of
  18602. its top-level parent component.
  18603. This may return 0 if there isn't a desktop component.
  18604. @see addToDesktop, isOnDesktop
  18605. */
  18606. ComponentPeer* getPeer() const;
  18607. /** For components on the desktop, this is called if the system wants to close the window.
  18608. This is a signal that either the user or the system wants the window to close. The
  18609. default implementation of this method will trigger an assertion to warn you that your
  18610. component should do something about it, but you can override this to ignore the event
  18611. if you want.
  18612. */
  18613. virtual void userTriedToCloseWindow();
  18614. /** Called for a desktop component which has just been minimised or un-minimised.
  18615. This will only be called for components on the desktop.
  18616. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  18617. */
  18618. virtual void minimisationStateChanged (bool isNowMinimised);
  18619. /** Brings the component to the front of its siblings.
  18620. If some of the component's siblings have had their 'always-on-top' flag set,
  18621. then they will still be kept in front of this one (unless of course this
  18622. one is also 'always-on-top').
  18623. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  18624. to the component (see grabKeyboardFocus() for more details)
  18625. @see toBack, toBehind, setAlwaysOnTop
  18626. */
  18627. void toFront (bool shouldAlsoGainFocus);
  18628. /** Changes this component's z-order to be at the back of all its siblings.
  18629. If the component is set to be 'always-on-top', it will only be moved to the
  18630. back of the other other 'always-on-top' components.
  18631. @see toFront, toBehind, setAlwaysOnTop
  18632. */
  18633. void toBack();
  18634. /** Changes this component's z-order so that it's just behind another component.
  18635. @see toFront, toBack
  18636. */
  18637. void toBehind (Component* other);
  18638. /** Sets whether the component should always be kept at the front of its siblings.
  18639. @see isAlwaysOnTop
  18640. */
  18641. void setAlwaysOnTop (bool shouldStayOnTop);
  18642. /** Returns true if this component is set to always stay in front of its siblings.
  18643. @see setAlwaysOnTop
  18644. */
  18645. bool isAlwaysOnTop() const throw();
  18646. /** Returns the x co-ordinate of the component's left edge.
  18647. This is a distance in pixels from the left edge of the component's parent.
  18648. @see getScreenX
  18649. */
  18650. inline int getX() const throw() { return bounds_.getX(); }
  18651. /** Returns the y co-ordinate of the top of this component.
  18652. This is a distance in pixels from the top edge of the component's parent.
  18653. @see getScreenY
  18654. */
  18655. inline int getY() const throw() { return bounds_.getY(); }
  18656. /** Returns the component's width in pixels. */
  18657. inline int getWidth() const throw() { return bounds_.getWidth(); }
  18658. /** Returns the component's height in pixels. */
  18659. inline int getHeight() const throw() { return bounds_.getHeight(); }
  18660. /** Returns the x co-ordinate of the component's right-hand edge.
  18661. This is a distance in pixels from the left edge of the component's parent.
  18662. */
  18663. int getRight() const throw() { return bounds_.getRight(); }
  18664. /** Returns the component's top-left position as a Point. */
  18665. const Point<int> getPosition() const throw() { return bounds_.getPosition(); }
  18666. /** Returns the y co-ordinate of the bottom edge of this component.
  18667. This is a distance in pixels from the top edge of the component's parent.
  18668. */
  18669. int getBottom() const throw() { return bounds_.getBottom(); }
  18670. /** Returns this component's bounding box.
  18671. The rectangle returned is relative to the top-left of the component's parent.
  18672. */
  18673. const Rectangle<int>& getBounds() const throw() { return bounds_; }
  18674. /** Returns the component's bounds, relative to its own origin.
  18675. This is like getBounds(), but returns the rectangle in local co-ordinates, In practice, it'll
  18676. return a rectangle with position (0, 0), and the same size as this component.
  18677. */
  18678. const Rectangle<int> getLocalBounds() const throw();
  18679. /** Returns the region of this component that's not obscured by other, opaque components.
  18680. The RectangleList that is returned represents the area of this component
  18681. which isn't covered by opaque child components.
  18682. If includeSiblings is true, it will also take into account any siblings
  18683. that may be overlapping the component.
  18684. */
  18685. void getVisibleArea (RectangleList& result,
  18686. bool includeSiblings) const;
  18687. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  18688. @see getX, relativePositionToGlobal
  18689. */
  18690. int getScreenX() const;
  18691. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  18692. @see getY, relativePositionToGlobal
  18693. */
  18694. int getScreenY() const;
  18695. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  18696. @see getScreenBounds
  18697. */
  18698. const Point<int> getScreenPosition() const;
  18699. /** Returns the bounds of this component, relative to the screen's top-left.
  18700. @see getScreenPosition
  18701. */
  18702. const Rectangle<int> getScreenBounds() const;
  18703. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  18704. @see globalPositionToRelative, relativePositionToOtherComponent
  18705. */
  18706. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) const;
  18707. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  18708. @see relativePositionToGlobal, relativePositionToOtherComponent
  18709. */
  18710. const Point<int> globalPositionToRelative (const Point<int>& screenPosition) const;
  18711. /** Converts a position relative to this component's top-left into a position
  18712. relative to another component's top-left.
  18713. @see relativePositionToGlobal, globalPositionToRelative
  18714. */
  18715. const Point<int> relativePositionToOtherComponent (const Component* targetComponent,
  18716. const Point<int>& positionRelativeToThis) const;
  18717. /** Moves the component to a new position.
  18718. Changes the component's top-left position (without changing its size).
  18719. The position is relative to the top-left of the component's parent.
  18720. If the component actually moves, this method will make a synchronous call to moved().
  18721. @see setBounds, ComponentListener::componentMovedOrResized
  18722. */
  18723. void setTopLeftPosition (int x, int y);
  18724. /** Moves the component to a new position.
  18725. Changes the position of the component's top-right corner (keeping it the same size).
  18726. The position is relative to the top-left of the component's parent.
  18727. If the component actually moves, this method will make a synchronous call to moved().
  18728. */
  18729. void setTopRightPosition (int x, int y);
  18730. /** Changes the size of the component.
  18731. A synchronous call to resized() will be occur if the size actually changes.
  18732. */
  18733. void setSize (int newWidth, int newHeight);
  18734. /** Changes the component's position and size.
  18735. The co-ordinates are relative to the top-left of the component's parent, or relative
  18736. to the origin of the screen is the component is on the desktop.
  18737. If this method changes the component's top-left position, it will make a synchronous
  18738. call to moved(). If it changes the size, it will also make a call to resized().
  18739. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  18740. */
  18741. void setBounds (int x, int y, int width, int height);
  18742. /** Changes the component's position and size.
  18743. @see setBounds
  18744. */
  18745. void setBounds (const Rectangle<int>& newBounds);
  18746. /** Changes the component's position and size in terms of fractions of its parent's size.
  18747. The values are factors of the parent's size, so for example
  18748. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  18749. width and height of the parent, with its top-left position 20% of
  18750. the way across and down the parent.
  18751. */
  18752. void setBoundsRelative (float proportionalX, float proportionalY,
  18753. float proportionalWidth, float proportionalHeight);
  18754. /** Changes the component's position and size based on the amount of space to leave around it.
  18755. This will position the component within its parent, leaving the specified number of
  18756. pixels around each edge.
  18757. */
  18758. void setBoundsInset (const BorderSize& borders);
  18759. /** Positions the component within a given rectangle, keeping its proportions
  18760. unchanged.
  18761. If onlyReduceInSize is false, the component will be resized to fill as much of the
  18762. rectangle as possible without changing its aspect ratio (the component's
  18763. current size is used to determine its aspect ratio, so a zero-size component
  18764. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  18765. too big to fit inside the rectangle.
  18766. It will then be positioned within the rectangle according to the justification flags
  18767. specified.
  18768. */
  18769. void setBoundsToFit (int x, int y, int width, int height,
  18770. const Justification& justification,
  18771. bool onlyReduceInSize);
  18772. /** Changes the position of the component's centre.
  18773. Leaves the component's size unchanged, but sets the position of its centre
  18774. relative to its parent's top-left.
  18775. */
  18776. void setCentrePosition (int x, int y);
  18777. /** Changes the position of the component's centre.
  18778. Leaves the position unchanged, but positions its centre relative to its
  18779. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  18780. its parent.
  18781. */
  18782. void setCentreRelative (float x, float y);
  18783. /** Changes the component's size and centres it within its parent.
  18784. After changing the size, the component will be moved so that it's
  18785. centred within its parent.
  18786. */
  18787. void centreWithSize (int width, int height);
  18788. /** Returns a proportion of the component's width.
  18789. This is a handy equivalent of (getWidth() * proportion).
  18790. */
  18791. int proportionOfWidth (float proportion) const throw();
  18792. /** Returns a proportion of the component's height.
  18793. This is a handy equivalent of (getHeight() * proportion).
  18794. */
  18795. int proportionOfHeight (float proportion) const throw();
  18796. /** Returns the width of the component's parent.
  18797. If the component has no parent (i.e. if it's on the desktop), this will return
  18798. the width of the screen.
  18799. */
  18800. int getParentWidth() const throw();
  18801. /** Returns the height of the component's parent.
  18802. If the component has no parent (i.e. if it's on the desktop), this will return
  18803. the height of the screen.
  18804. */
  18805. int getParentHeight() const throw();
  18806. /** Returns the screen co-ordinates of the monitor that contains this component.
  18807. If there's only one monitor, this will return its size - if there are multiple
  18808. monitors, it will return the area of the monitor that contains the component's
  18809. centre.
  18810. */
  18811. const Rectangle<int> getParentMonitorArea() const;
  18812. /** Returns the number of child components that this component contains.
  18813. @see getChildComponent, getIndexOfChildComponent
  18814. */
  18815. int getNumChildComponents() const throw();
  18816. /** Returns one of this component's child components, by it index.
  18817. The component with index 0 is at the back of the z-order, the one at the
  18818. front will have index (getNumChildComponents() - 1).
  18819. If the index is out-of-range, this will return a null pointer.
  18820. @see getNumChildComponents, getIndexOfChildComponent
  18821. */
  18822. Component* getChildComponent (int index) const throw();
  18823. /** Returns the index of this component in the list of child components.
  18824. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  18825. values are further towards the front.
  18826. Returns -1 if the component passed-in is not a child of this component.
  18827. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  18828. */
  18829. int getIndexOfChildComponent (const Component* child) const throw();
  18830. /** Adds a child component to this one.
  18831. @param child the new component to add. If the component passed-in is already
  18832. the child of another component, it'll first be removed from that.
  18833. @param zOrder The index in the child-list at which this component should be inserted.
  18834. A value of -1 will insert it in front of the others, 0 is the back.
  18835. @see removeChildComponent, addAndMakeVisible, getChild,
  18836. ComponentListener::componentChildrenChanged
  18837. */
  18838. void addChildComponent (Component* child, int zOrder = -1);
  18839. /** Adds a child component to this one, and also makes the child visible if it isn't.
  18840. Quite a useful function, this is just the same as calling addChildComponent()
  18841. followed by setVisible (true) on the child.
  18842. */
  18843. void addAndMakeVisible (Component* child, int zOrder = -1);
  18844. /** Removes one of this component's child-components.
  18845. If the child passed-in isn't actually a child of this component (either because
  18846. it's invalid or is the child of a different parent), then nothing is done.
  18847. Note that removing a child will not delete it!
  18848. @see addChildComponent, ComponentListener::componentChildrenChanged
  18849. */
  18850. void removeChildComponent (Component* childToRemove);
  18851. /** Removes one of this component's child-components by index.
  18852. This will return a pointer to the component that was removed, or null if
  18853. the index was out-of-range.
  18854. Note that removing a child will not delete it!
  18855. @see addChildComponent, ComponentListener::componentChildrenChanged
  18856. */
  18857. Component* removeChildComponent (int childIndexToRemove);
  18858. /** Removes all this component's children.
  18859. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  18860. */
  18861. void removeAllChildren();
  18862. /** Removes all this component's children, and deletes them.
  18863. @see removeAllChildren
  18864. */
  18865. void deleteAllChildren();
  18866. /** Returns the component which this component is inside.
  18867. If this is the highest-level component or hasn't yet been added to
  18868. a parent, this will return null.
  18869. */
  18870. Component* getParentComponent() const throw() { return parentComponent_; }
  18871. /** Searches the parent components for a component of a specified class.
  18872. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  18873. component that can be dynamically cast to a MyComp, or will return 0 if none
  18874. of the parents are suitable.
  18875. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  18876. */
  18877. template <class TargetClass>
  18878. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  18879. {
  18880. (void) dummyParameter;
  18881. Component* p = parentComponent_;
  18882. while (p != 0)
  18883. {
  18884. TargetClass* target = dynamic_cast <TargetClass*> (p);
  18885. if (target != 0)
  18886. return target;
  18887. p = p->parentComponent_;
  18888. }
  18889. return 0;
  18890. }
  18891. /** Returns the highest-level component which contains this one or its parents.
  18892. This will search upwards in the parent-hierarchy from this component, until it
  18893. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  18894. not yet added to a parent), and will return that.
  18895. */
  18896. Component* getTopLevelComponent() const throw();
  18897. /** Checks whether a component is anywhere inside this component or its children.
  18898. This will recursively check through this components children to see if the
  18899. given component is anywhere inside.
  18900. */
  18901. bool isParentOf (const Component* possibleChild) const throw();
  18902. /** Called to indicate that the component's parents have changed.
  18903. When a component is added or removed from its parent, this method will
  18904. be called on all of its children (recursively - so all children of its
  18905. children will also be called as well).
  18906. Subclasses can override this if they need to react to this in some way.
  18907. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  18908. */
  18909. virtual void parentHierarchyChanged();
  18910. /** Subclasses can use this callback to be told when children are added or removed.
  18911. @see parentHierarchyChanged
  18912. */
  18913. virtual void childrenChanged();
  18914. /** Tests whether a given point inside the component.
  18915. Overriding this method allows you to create components which only intercept
  18916. mouse-clicks within a user-defined area.
  18917. This is called to find out whether a particular x, y co-ordinate is
  18918. considered to be inside the component or not, and is used by methods such
  18919. as contains() and getComponentAt() to work out which component
  18920. the mouse is clicked on.
  18921. Components with custom shapes will probably want to override it to perform
  18922. some more complex hit-testing.
  18923. The default implementation of this method returns either true or false,
  18924. depending on the value that was set by calling setInterceptsMouseClicks() (true
  18925. is the default return value).
  18926. Note that the hit-test region is not related to the opacity with which
  18927. areas of a component are painted.
  18928. Applications should never call hitTest() directly - instead use the
  18929. contains() method, because this will also test for occlusion by the
  18930. component's parent.
  18931. Note that for components on the desktop, this method will be ignored, because it's
  18932. not always possible to implement this behaviour on all platforms.
  18933. @param x the x co-ordinate to test, relative to the left hand edge of this
  18934. component. This value is guaranteed to be greater than or equal to
  18935. zero, and less than the component's width
  18936. @param y the y co-ordinate to test, relative to the top edge of this
  18937. component. This value is guaranteed to be greater than or equal to
  18938. zero, and less than the component's height
  18939. @returns true if the click is considered to be inside the component
  18940. @see setInterceptsMouseClicks, contains
  18941. */
  18942. virtual bool hitTest (int x, int y);
  18943. /** Changes the default return value for the hitTest() method.
  18944. Setting this to false is an easy way to make a component pass its mouse-clicks
  18945. through to the components behind it.
  18946. When a component is created, the default setting for this is true.
  18947. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  18948. return false (or true for child components if allowClicksOnChildComponents
  18949. is true)
  18950. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  18951. components can be clicked on as normal but clicks on this component pass
  18952. straight through; if this is false and allowClicksOnThisComponent
  18953. is false, then neither this component nor any child components can
  18954. be clicked on
  18955. @see hitTest, getInterceptsMouseClicks
  18956. */
  18957. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  18958. bool allowClicksOnChildComponents) throw();
  18959. /** Retrieves the current state of the mouse-click interception flags.
  18960. On return, the two parameters are set to the state used in the last call to
  18961. setInterceptsMouseClicks().
  18962. @see setInterceptsMouseClicks
  18963. */
  18964. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  18965. bool& allowsClicksOnChildComponents) const throw();
  18966. /** Returns true if a given point lies within this component or one of its children.
  18967. Never override this method! Use hitTest to create custom hit regions.
  18968. @param x the x co-ordinate to test, relative to this component's left hand edge.
  18969. @param y the y co-ordinate to test, relative to this component's top edge.
  18970. @returns true if the point is within the component's hit-test area, but only if
  18971. that part of the component isn't clipped by its parent component. Note
  18972. that this won't take into account any overlapping sibling components
  18973. which might be in the way - for that, see reallyContains()
  18974. @see hitTest, reallyContains, getComponentAt
  18975. */
  18976. virtual bool contains (int x, int y);
  18977. /** Returns true if a given point lies in this component, taking any overlapping
  18978. siblings into account.
  18979. @param x the x co-ordinate to test, relative to this component's left hand edge.
  18980. @param y the y co-ordinate to test, relative to this component's top edge.
  18981. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  18982. component, this determines the value that will
  18983. be returned.
  18984. @see contains, getComponentAt
  18985. */
  18986. bool reallyContains (int x, int y, bool returnTrueIfWithinAChild);
  18987. /** Returns the component at a certain point within this one.
  18988. @param x the x co-ordinate to test, relative to this component's left hand edge.
  18989. @param y the y co-ordinate to test, relative to this component's top edge.
  18990. @returns the component that is at this position - which may be 0, this component,
  18991. or one of its children. Note that overlapping siblings that might actually
  18992. be in the way are not taken into account by this method - to account for these,
  18993. instead call getComponentAt on the top-level parent of this component.
  18994. @see hitTest, contains, reallyContains
  18995. */
  18996. Component* getComponentAt (int x, int y);
  18997. /** Returns the component at a certain point within this one.
  18998. @param position the co-ordinates to test, relative to this component's top-left.
  18999. @returns the component that is at this position - which may be 0, this component,
  19000. or one of its children. Note that overlapping siblings that might actually
  19001. be in the way are not taken into account by this method - to account for these,
  19002. instead call getComponentAt on the top-level parent of this component.
  19003. @see hitTest, contains, reallyContains
  19004. */
  19005. Component* getComponentAt (const Point<int>& position);
  19006. /** Marks the whole component as needing to be redrawn.
  19007. Calling this will not do any repainting immediately, but will mark the component
  19008. as 'dirty'. At some point in the near future the operating system will send a paint
  19009. message, which will redraw all the dirty regions of all components.
  19010. There's no guarantee about how soon after calling repaint() the redraw will actually
  19011. happen, and other queued events may be delivered before a redraw is done.
  19012. If the setBufferedToImage() method has been used to cause this component
  19013. to use a buffer, the repaint() call will invalidate the component's buffer.
  19014. To redraw just a subsection of the component rather than the whole thing,
  19015. use the repaint (int, int, int, int) method.
  19016. @see paint
  19017. */
  19018. void repaint();
  19019. /** Marks a subsection of this component as needing to be redrawn.
  19020. Calling this will not do any repainting immediately, but will mark the given region
  19021. of the component as 'dirty'. At some point in the near future the operating system
  19022. will send a paint message, which will redraw all the dirty regions of all components.
  19023. There's no guarantee about how soon after calling repaint() the redraw will actually
  19024. happen, and other queued events may be delivered before a redraw is done.
  19025. The region that is passed in will be clipped to keep it within the bounds of this
  19026. component.
  19027. @see repaint()
  19028. */
  19029. void repaint (int x, int y, int width, int height);
  19030. /** Marks a subsection of this component as needing to be redrawn.
  19031. Calling this will not do any repainting immediately, but will mark the given region
  19032. of the component as 'dirty'. At some point in the near future the operating system
  19033. will send a paint message, which will redraw all the dirty regions of all components.
  19034. There's no guarantee about how soon after calling repaint() the redraw will actually
  19035. happen, and other queued events may be delivered before a redraw is done.
  19036. The region that is passed in will be clipped to keep it within the bounds of this
  19037. component.
  19038. @see repaint()
  19039. */
  19040. void repaint (const Rectangle<int>& area);
  19041. /** Makes the component use an internal buffer to optimise its redrawing.
  19042. Setting this flag to true will cause the component to allocate an
  19043. internal buffer into which it paints itself, so that when asked to
  19044. redraw itself, it can use this buffer rather than actually calling the
  19045. paint() method.
  19046. The buffer is kept until the repaint() method is called directly on
  19047. this component (or until it is resized), when the image is invalidated
  19048. and then redrawn the next time the component is painted.
  19049. Note that only the drawing that happens within the component's paint()
  19050. method is drawn into the buffer, it's child components are not buffered, and
  19051. nor is the paintOverChildren() method.
  19052. @see repaint, paint, createComponentSnapshot
  19053. */
  19054. void setBufferedToImage (bool shouldBeBuffered);
  19055. /** Generates a snapshot of part of this component.
  19056. This will return a new Image, the size of the rectangle specified,
  19057. containing a snapshot of the specified area of the component and all
  19058. its children.
  19059. The image may or may not have an alpha-channel, depending on whether the
  19060. image is opaque or not.
  19061. If the clipImageToComponentBounds parameter is true and the area is greater than
  19062. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  19063. then parts of the component beyond its bounds can be drawn.
  19064. The caller is responsible for deleting the image that is returned.
  19065. @see paintEntireComponent
  19066. */
  19067. Image* createComponentSnapshot (const Rectangle<int>& areaToGrab,
  19068. bool clipImageToComponentBounds = true);
  19069. /** Draws this component and all its subcomponents onto the specified graphics
  19070. context.
  19071. You should very rarely have to use this method, it's simply there in case you need
  19072. to draw a component with a custom graphics context for some reason, e.g. for
  19073. creating a snapshot of the component.
  19074. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  19075. on its children in order to render the entire tree.
  19076. The graphics context may be left in an undefined state after this method returns,
  19077. so you may need to reset it if you're going to use it again.
  19078. */
  19079. void paintEntireComponent (Graphics& context);
  19080. /** Adds an effect filter to alter the component's appearance.
  19081. When a component has an effect filter set, then this is applied to the
  19082. results of its paint() method. There are a few preset effects, such as
  19083. a drop-shadow or glow, but they can be user-defined as well.
  19084. The effect that is passed in will not be deleted by the component - the
  19085. caller must take care of deleting it.
  19086. To remove an effect from a component, pass a null pointer in as the parameter.
  19087. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  19088. */
  19089. void setComponentEffect (ImageEffectFilter* newEffect);
  19090. /** Returns the current component effect.
  19091. @see setComponentEffect
  19092. */
  19093. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  19094. /** Finds the appropriate look-and-feel to use for this component.
  19095. If the component hasn't had a look-and-feel explicitly set, this will
  19096. return the parent's look-and-feel, or just the default one if there's no
  19097. parent.
  19098. @see setLookAndFeel, lookAndFeelChanged
  19099. */
  19100. LookAndFeel& getLookAndFeel() const throw();
  19101. /** Sets the look and feel to use for this component.
  19102. This will also change the look and feel for any child components that haven't
  19103. had their look set explicitly.
  19104. The object passed in will not be deleted by the component, so it's the caller's
  19105. responsibility to manage it. It may be used at any time until this component
  19106. has been deleted.
  19107. Calling this method will also invoke the sendLookAndFeelChange() method.
  19108. @see getLookAndFeel, lookAndFeelChanged
  19109. */
  19110. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  19111. /** Called to let the component react to a change in the look-and-feel setting.
  19112. When the look-and-feel is changed for a component, this will be called in
  19113. all its child components, recursively.
  19114. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  19115. an application uses a LookAndFeel class that might have changed internally.
  19116. @see sendLookAndFeelChange, getLookAndFeel
  19117. */
  19118. virtual void lookAndFeelChanged();
  19119. /** Calls the lookAndFeelChanged() method in this component and all its children.
  19120. This will recurse through the children and their children, calling lookAndFeelChanged()
  19121. on them all.
  19122. @see lookAndFeelChanged
  19123. */
  19124. void sendLookAndFeelChange();
  19125. /** Indicates whether any parts of the component might be transparent.
  19126. Components that always paint all of their contents with solid colour and
  19127. thus completely cover any components behind them should use this method
  19128. to tell the repaint system that they are opaque.
  19129. This information is used to optimise drawing, because it means that
  19130. objects underneath opaque windows don't need to be painted.
  19131. By default, components are considered transparent, unless this is used to
  19132. make it otherwise.
  19133. @see isOpaque, getVisibleArea
  19134. */
  19135. void setOpaque (bool shouldBeOpaque);
  19136. /** Returns true if no parts of this component are transparent.
  19137. @returns the value that was set by setOpaque, (the default being false)
  19138. @see setOpaque
  19139. */
  19140. bool isOpaque() const throw();
  19141. /** Indicates whether the component should be brought to the front when clicked.
  19142. Setting this flag to true will cause the component to be brought to the front
  19143. when the mouse is clicked somewhere inside it or its child components.
  19144. Note that a top-level desktop window might still be brought to the front by the
  19145. operating system when it's clicked, depending on how the OS works.
  19146. By default this is set to false.
  19147. @see setMouseClickGrabsKeyboardFocus
  19148. */
  19149. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  19150. /** Indicates whether the component should be brought to the front when clicked-on.
  19151. @see setBroughtToFrontOnMouseClick
  19152. */
  19153. bool isBroughtToFrontOnMouseClick() const throw();
  19154. // Keyboard focus methods
  19155. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  19156. By default components aren't actually interested in gaining the
  19157. focus, but this method can be used to turn this on.
  19158. See the grabKeyboardFocus() method for details about the way a component
  19159. is chosen to receive the focus.
  19160. @see grabKeyboardFocus, getWantsKeyboardFocus
  19161. */
  19162. void setWantsKeyboardFocus (bool wantsFocus) throw();
  19163. /** Returns true if the component is interested in getting keyboard focus.
  19164. This returns the flag set by setWantsKeyboardFocus(). The default
  19165. setting is false.
  19166. @see setWantsKeyboardFocus
  19167. */
  19168. bool getWantsKeyboardFocus() const throw();
  19169. /** Chooses whether a click on this component automatically grabs the focus.
  19170. By default this is set to true, but you might want a component which can
  19171. be focused, but where you don't want the user to be able to affect it directly
  19172. by clicking.
  19173. */
  19174. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  19175. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  19176. See setMouseClickGrabsKeyboardFocus() for more info.
  19177. */
  19178. bool getMouseClickGrabsKeyboardFocus() const throw();
  19179. /** Tries to give keyboard focus to this component.
  19180. When the user clicks on a component or its grabKeyboardFocus()
  19181. method is called, the following procedure is used to work out which
  19182. component should get it:
  19183. - if the component that was clicked on actually wants focus (as indicated
  19184. by calling getWantsKeyboardFocus), it gets it.
  19185. - if the component itself doesn't want focus, it will try to pass it
  19186. on to whichever of its children is the default component, as determined by
  19187. KeyboardFocusTraverser::getDefaultComponent()
  19188. - if none of its children want focus at all, it will pass it up to its
  19189. parent instead, unless it's a top-level component without a parent,
  19190. in which case it just takes the focus itself.
  19191. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  19192. getCurrentlyFocusedComponent, focusGained, focusLost,
  19193. keyPressed, keyStateChanged
  19194. */
  19195. void grabKeyboardFocus();
  19196. /** Returns true if this component currently has the keyboard focus.
  19197. @param trueIfChildIsFocused if this is true, then the method returns true if
  19198. either this component or any of its children (recursively)
  19199. have the focus. If false, the method only returns true if
  19200. this component has the focus.
  19201. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  19202. focusGained, focusLost
  19203. */
  19204. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  19205. /** Returns the component that currently has the keyboard focus.
  19206. @returns the focused component, or null if nothing is focused.
  19207. */
  19208. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  19209. /** Tries to move the keyboard focus to one of this component's siblings.
  19210. This will try to move focus to either the next or previous component. (This
  19211. is the method that is used when shifting focus by pressing the tab key).
  19212. Components for which getWantsKeyboardFocus() returns false are not looked at.
  19213. @param moveToNext if true, the focus will move forwards; if false, it will
  19214. move backwards
  19215. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  19216. */
  19217. void moveKeyboardFocusToSibling (bool moveToNext);
  19218. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  19219. which focus should be passed from this component.
  19220. The default implementation of this method will return a default
  19221. KeyboardFocusTraverser if this component is a focus container (as determined
  19222. by the setFocusContainer() method). If the component isn't a focus
  19223. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  19224. If you overrride this to return a custom KeyboardFocusTraverser, then
  19225. this component and all its sub-components will use the new object to
  19226. make their focusing decisions.
  19227. The method should return a new object, which the caller is required to
  19228. delete when no longer needed.
  19229. */
  19230. virtual KeyboardFocusTraverser* createFocusTraverser();
  19231. /** Returns the focus order of this component, if one has been specified.
  19232. By default components don't have a focus order - in that case, this
  19233. will return 0. Lower numbers indicate that the component will be
  19234. earlier in the focus traversal order.
  19235. To change the order, call setExplicitFocusOrder().
  19236. The focus order may be used by the KeyboardFocusTraverser class as part of
  19237. its algorithm for deciding the order in which components should be traversed.
  19238. See the KeyboardFocusTraverser class for more details on this.
  19239. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  19240. */
  19241. int getExplicitFocusOrder() const;
  19242. /** Sets the index used in determining the order in which focusable components
  19243. should be traversed.
  19244. A value of 0 or less is taken to mean that no explicit order is wanted, and
  19245. that traversal should use other factors, like the component's position.
  19246. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  19247. */
  19248. void setExplicitFocusOrder (int newFocusOrderIndex);
  19249. /** Indicates whether this component is a parent for components that can have
  19250. their focus traversed.
  19251. This flag is used by the default implementation of the createFocusTraverser()
  19252. method, which uses the flag to find the first parent component (of the currently
  19253. focused one) which wants to be a focus container.
  19254. So using this method to set the flag to 'true' causes this component to
  19255. act as the top level within which focus is passed around.
  19256. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  19257. */
  19258. void setFocusContainer (bool shouldBeFocusContainer) throw();
  19259. /** Returns true if this component has been marked as a focus container.
  19260. See setFocusContainer() for more details.
  19261. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  19262. */
  19263. bool isFocusContainer() const throw();
  19264. /** Returns true if the component (and all its parents) are enabled.
  19265. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  19266. what difference this makes to the component depends on the type. E.g. buttons
  19267. and sliders will choose to draw themselves differently, etc.
  19268. Note that if one of this component's parents is disabled, this will always
  19269. return false, even if this component itself is enabled.
  19270. @see setEnabled, enablementChanged
  19271. */
  19272. bool isEnabled() const throw();
  19273. /** Enables or disables this component.
  19274. Disabling a component will also cause all of its child components to become
  19275. disabled.
  19276. Similarly, enabling a component which is inside a disabled parent
  19277. component won't make any difference until the parent is re-enabled.
  19278. @see isEnabled, enablementChanged
  19279. */
  19280. void setEnabled (bool shouldBeEnabled);
  19281. /** Callback to indicate that this component has been enabled or disabled.
  19282. This can be triggered by one of the component's parent components
  19283. being enabled or disabled, as well as changes to the component itself.
  19284. The default implementation of this method does nothing; your class may
  19285. wish to repaint itself or something when this happens.
  19286. @see setEnabled, isEnabled
  19287. */
  19288. virtual void enablementChanged();
  19289. /** Changes the mouse cursor shape to use when the mouse is over this component.
  19290. Note that the cursor set by this method can be overridden by the getMouseCursor
  19291. method.
  19292. @see MouseCursor
  19293. */
  19294. void setMouseCursor (const MouseCursor& cursorType);
  19295. /** Returns the mouse cursor shape to use when the mouse is over this component.
  19296. The default implementation will return the cursor that was set by setCursor()
  19297. but can be overridden for more specialised purposes, e.g. returning different
  19298. cursors depending on the mouse position.
  19299. @see MouseCursor
  19300. */
  19301. virtual const MouseCursor getMouseCursor();
  19302. /** Forces the current mouse cursor to be updated.
  19303. If you're overriding the getMouseCursor() method to control which cursor is
  19304. displayed, then this will only be checked each time the user moves the mouse. So
  19305. if you want to force the system to check that the cursor being displayed is
  19306. up-to-date (even if the mouse is just sitting there), call this method.
  19307. This isn't needed if you're only using setMouseCursor().
  19308. */
  19309. void updateMouseCursor() const;
  19310. /** Components can override this method to draw their content.
  19311. The paint() method gets called when a region of a component needs redrawing,
  19312. either because the component's repaint() method has been called, or because
  19313. something has happened on the screen that means a section of a window needs
  19314. to be redrawn.
  19315. Any child components will draw themselves over whatever this method draws. If
  19316. you need to paint over the top of your child components, you can also implement
  19317. the paintOverChildren() method to do this.
  19318. If you want to cause a component to redraw itself, this is done asynchronously -
  19319. calling the repaint() method marks a region of the component as "dirty", and the
  19320. paint() method will automatically be called sometime later, by the message thread,
  19321. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  19322. you never redraw something synchronously.
  19323. You should never need to call this method directly - to take a snapshot of the
  19324. component you could use createComponentSnapshot() or paintEntireComponent().
  19325. @param g the graphics context that must be used to do the drawing operations.
  19326. @see repaint, paintOverChildren, Graphics
  19327. */
  19328. virtual void paint (Graphics& g);
  19329. /** Components can override this method to draw over the top of their children.
  19330. For most drawing operations, it's better to use the normal paint() method,
  19331. but if you need to overlay something on top of the children, this can be
  19332. used.
  19333. @see paint, Graphics
  19334. */
  19335. virtual void paintOverChildren (Graphics& g);
  19336. /** Called when the mouse moves inside this component.
  19337. If the mouse button isn't pressed and the mouse moves over a component,
  19338. this will be called to let the component react to this.
  19339. A component will always get a mouseEnter callback before a mouseMove.
  19340. @param e details about the position and status of the mouse event
  19341. @see mouseEnter, mouseExit, mouseDrag, contains
  19342. */
  19343. virtual void mouseMove (const MouseEvent& e);
  19344. /** Called when the mouse first enters this component.
  19345. If the mouse button isn't pressed and the mouse moves into a component,
  19346. this will be called to let the component react to this.
  19347. When the mouse button is pressed and held down while being moved in
  19348. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  19349. mouseDrag messages are sent to the component that the mouse was originally
  19350. clicked on, until the button is released.
  19351. If you're writing a component that needs to repaint itself when the mouse
  19352. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  19353. method.
  19354. @param e details about the position and status of the mouse event
  19355. @see mouseExit, mouseDrag, mouseMove, contains
  19356. */
  19357. virtual void mouseEnter (const MouseEvent& e);
  19358. /** Called when the mouse moves out of this component.
  19359. This will be called when the mouse moves off the edge of this
  19360. component.
  19361. If the mouse button was pressed, and it was then dragged off the
  19362. edge of the component and released, then this callback will happen
  19363. when the button is released, after the mouseUp callback.
  19364. If you're writing a component that needs to repaint itself when the mouse
  19365. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  19366. method.
  19367. @param e details about the position and status of the mouse event
  19368. @see mouseEnter, mouseDrag, mouseMove, contains
  19369. */
  19370. virtual void mouseExit (const MouseEvent& e);
  19371. /** Called when a mouse button is pressed while it's over this component.
  19372. The MouseEvent object passed in contains lots of methods for finding out
  19373. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  19374. were held down at the time.
  19375. Once a button is held down, the mouseDrag method will be called when the
  19376. mouse moves, until the button is released.
  19377. @param e details about the position and status of the mouse event
  19378. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  19379. */
  19380. virtual void mouseDown (const MouseEvent& e);
  19381. /** Called when the mouse is moved while a button is held down.
  19382. When a mouse button is pressed inside a component, that component
  19383. receives mouseDrag callbacks each time the mouse moves, even if the
  19384. mouse strays outside the component's bounds.
  19385. If you want to be able to drag things off the edge of a component
  19386. and have the component scroll when you get to the edges, the
  19387. beginDragAutoRepeat() method might be useful.
  19388. @param e details about the position and status of the mouse event
  19389. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  19390. */
  19391. virtual void mouseDrag (const MouseEvent& e);
  19392. /** Called when a mouse button is released.
  19393. A mouseUp callback is sent to the component in which a button was pressed
  19394. even if the mouse is actually over a different component when the
  19395. button is released.
  19396. The MouseEvent object passed in contains lots of methods for finding out
  19397. which buttons were down just before they were released.
  19398. @param e details about the position and status of the mouse event
  19399. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  19400. */
  19401. virtual void mouseUp (const MouseEvent& e);
  19402. /** Called when a mouse button has been double-clicked in this component.
  19403. The MouseEvent object passed in contains lots of methods for finding out
  19404. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  19405. were held down at the time.
  19406. For altering the time limit used to detect double-clicks,
  19407. see MouseEvent::setDoubleClickTimeout.
  19408. @param e details about the position and status of the mouse event
  19409. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  19410. MouseEvent::getDoubleClickTimeout
  19411. */
  19412. virtual void mouseDoubleClick (const MouseEvent& e);
  19413. /** Called when the mouse-wheel is moved.
  19414. This callback is sent to the component that the mouse is over when the
  19415. wheel is moved.
  19416. If not overridden, the component will forward this message to its parent, so
  19417. that parent components can collect mouse-wheel messages that happen to
  19418. child components which aren't interested in them.
  19419. @param e details about the position and status of the mouse event
  19420. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  19421. value means the wheel has been pushed to the right, negative means it
  19422. was pushed to the left
  19423. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  19424. value means the wheel has been pushed upwards, negative means it
  19425. was pushed downwards
  19426. */
  19427. virtual void mouseWheelMove (const MouseEvent& e,
  19428. float wheelIncrementX,
  19429. float wheelIncrementY);
  19430. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  19431. next mouse-drag operation.
  19432. This allows you to make sure that mouseDrag() events sent continuously, even
  19433. when the mouse isn't moving. This can be useful for things like auto-scrolling
  19434. components when the mouse is near an edge.
  19435. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  19436. minimum interval between consecutive mouse drag callbacks. The callbacks
  19437. will continue until the mouse is released, and then the interval will be reset,
  19438. so you need to make sure it's called every time you begin a drag event. If it
  19439. is called when the mouse isn't actually being pressed, it will apply to the next
  19440. mouse-drag operation that happens.
  19441. Passing an interval of 0 or less will cancel the auto-repeat.
  19442. @see mouseDrag
  19443. */
  19444. static void beginDragAutoRepeat (int millisecondIntervalBetweenCallbacks);
  19445. /** Causes automatic repaints when the mouse enters or exits this component.
  19446. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  19447. on the component, it will trigger a repaint.
  19448. This is handy for things like buttons that need to draw themselves differently when
  19449. the mouse moves over them, and it avoids having to override all the different mouse
  19450. callbacks and call repaint().
  19451. @see mouseEnter, mouseExit, mouseDown, mouseUp
  19452. */
  19453. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  19454. /** Registers a listener to be told when mouse events occur in this component.
  19455. If you need to get informed about mouse events in a component but can't or
  19456. don't want to override its methods, you can attach any number of listeners
  19457. to the component, and these will get told about the events in addition to
  19458. the component's own callbacks being called.
  19459. Note that a MouseListener can also be attached to more than one component.
  19460. @param newListener the listener to register
  19461. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  19462. for events that happen to any child component
  19463. within this component, including deeply-nested
  19464. child components. If false, it will only be
  19465. told about events that this component handles.
  19466. @see MouseListener, removeMouseListener
  19467. */
  19468. void addMouseListener (MouseListener* newListener,
  19469. bool wantsEventsForAllNestedChildComponents);
  19470. /** Deregisters a mouse listener.
  19471. @see addMouseListener, MouseListener
  19472. */
  19473. void removeMouseListener (MouseListener* listenerToRemove);
  19474. /** Adds a listener that wants to hear about keypresses that this component receives.
  19475. The listeners that are registered with a component are called by its keyPressed() or
  19476. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  19477. If you add an object as a key listener, be careful to remove it when the object
  19478. is deleted, or the component will be left with a dangling pointer.
  19479. @see keyPressed, keyStateChanged, removeKeyListener
  19480. */
  19481. void addKeyListener (KeyListener* newListener);
  19482. /** Removes a previously-registered key listener.
  19483. @see addKeyListener
  19484. */
  19485. void removeKeyListener (KeyListener* listenerToRemove);
  19486. /** Called when a key is pressed.
  19487. When a key is pressed, the component that has the keyboard focus will have this
  19488. method called. Remember that a component will only be given the focus if its
  19489. setWantsKeyboardFocus() method has been used to enable this.
  19490. If your implementation returns true, the event will be consumed and not passed
  19491. on to any other listeners. If it returns false, the key will be passed to any
  19492. KeyListeners that have been registered with this component. As soon as one of these
  19493. returns true, the process will stop, but if they all return false, the event will
  19494. be passed upwards to this component's parent, and so on.
  19495. The default implementation of this method does nothing and returns false.
  19496. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  19497. */
  19498. virtual bool keyPressed (const KeyPress& key);
  19499. /** Called when a key is pressed or released.
  19500. Whenever a key on the keyboard is pressed or released (including modifier keys
  19501. like shift and ctrl), this method will be called on the component that currently
  19502. has the keyboard focus. Remember that a component will only be given the focus if
  19503. its setWantsKeyboardFocus() method has been used to enable this.
  19504. If your implementation returns true, the event will be consumed and not passed
  19505. on to any other listeners. If it returns false, then any KeyListeners that have
  19506. been registered with this component will have their keyStateChanged methods called.
  19507. As soon as one of these returns true, the process will stop, but if they all return
  19508. false, the event will be passed upwards to this component's parent, and so on.
  19509. The default implementation of this method does nothing and returns false.
  19510. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  19511. method.
  19512. @param isKeyDown true if a key has been pressed; false if it has been released
  19513. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  19514. */
  19515. virtual bool keyStateChanged (bool isKeyDown);
  19516. /** Called when a modifier key is pressed or released.
  19517. Whenever the shift, control, alt or command keys are pressed or released,
  19518. this method will be called on the component that currently has the keyboard focus.
  19519. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  19520. method has been used to enable this.
  19521. The default implementation of this method actually calls its parent's modifierKeysChanged
  19522. method, so that focused components which aren't interested in this will give their
  19523. parents a chance to act on the event instead.
  19524. @see keyStateChanged, ModifierKeys
  19525. */
  19526. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  19527. /** Enumeration used by the focusChanged() and focusLost() methods. */
  19528. enum FocusChangeType
  19529. {
  19530. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  19531. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  19532. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  19533. };
  19534. /** Called to indicate that this component has just acquired the keyboard focus.
  19535. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19536. */
  19537. virtual void focusGained (FocusChangeType cause);
  19538. /** Called to indicate that this component has just lost the keyboard focus.
  19539. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19540. */
  19541. virtual void focusLost (FocusChangeType cause);
  19542. /** Called to indicate that one of this component's children has been focused or unfocused.
  19543. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  19544. changed. It happens when focus moves from one of this component's children (at any depth)
  19545. to a component that isn't contained in this one, (or vice-versa).
  19546. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  19547. */
  19548. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  19549. /** Returns true if the mouse is currently over this component.
  19550. If the mouse isn't over the component, this will return false, even if the
  19551. mouse is currently being dragged - so you can use this in your mouseDrag
  19552. method to find out whether it's really over the component or not.
  19553. Note that when the mouse button is being held down, then the only component
  19554. for which this method will return true is the one that was originally
  19555. clicked on.
  19556. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  19557. */
  19558. bool isMouseOver() const throw();
  19559. /** Returns true if the mouse button is currently held down in this component.
  19560. Note that this is a test to see whether the mouse is being pressed in this
  19561. component, so it'll return false if called on component A when the mouse
  19562. is actually being dragged in component B.
  19563. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  19564. */
  19565. bool isMouseButtonDown() const throw();
  19566. /** True if the mouse is over this component, or if it's being dragged in this component.
  19567. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  19568. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  19569. */
  19570. bool isMouseOverOrDragging() const throw();
  19571. /** Returns true if a mouse button is currently down.
  19572. Unlike isMouseButtonDown, this will test the current state of the
  19573. buttons without regard to which component (if any) it has been
  19574. pressed in.
  19575. @see isMouseButtonDown, ModifierKeys
  19576. */
  19577. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  19578. /** Returns the mouse's current position, relative to this component.
  19579. The co-ordinates are relative to the component's top-left corner.
  19580. */
  19581. const Point<int> getMouseXYRelative() const;
  19582. /** Called when this component's size has been changed.
  19583. A component can implement this method to do things such as laying out its
  19584. child components when its width or height changes.
  19585. The method is called synchronously as a result of the setBounds or setSize
  19586. methods, so repeatedly changing a components size will repeatedly call its
  19587. resized method (unlike things like repainting, where multiple calls to repaint
  19588. are coalesced together).
  19589. If the component is a top-level window on the desktop, its size could also
  19590. be changed by operating-system factors beyond the application's control.
  19591. @see moved, setSize
  19592. */
  19593. virtual void resized();
  19594. /** Called when this component's position has been changed.
  19595. This is called when the position relative to its parent changes, not when
  19596. its absolute position on the screen changes (so it won't be called for
  19597. all child components when a parent component is moved).
  19598. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  19599. or any of the other repositioning methods, and like resized(), it will be
  19600. called each time those methods are called.
  19601. If the component is a top-level window on the desktop, its position could also
  19602. be changed by operating-system factors beyond the application's control.
  19603. @see resized, setBounds
  19604. */
  19605. virtual void moved();
  19606. /** Called when one of this component's children is moved or resized.
  19607. If the parent wants to know about changes to its immediate children (not
  19608. to children of its children), this is the method to override.
  19609. @see moved, resized, parentSizeChanged
  19610. */
  19611. virtual void childBoundsChanged (Component* child);
  19612. /** Called when this component's immediate parent has been resized.
  19613. If the component is a top-level window, this indicates that the screen size
  19614. has changed.
  19615. @see childBoundsChanged, moved, resized
  19616. */
  19617. virtual void parentSizeChanged();
  19618. /** Called when this component has been moved to the front of its siblings.
  19619. The component may have been brought to the front by the toFront() method, or
  19620. by the operating system if it's a top-level window.
  19621. @see toFront
  19622. */
  19623. virtual void broughtToFront();
  19624. /** Adds a listener to be told about changes to the component hierarchy or position.
  19625. Component listeners get called when this component's size, position or children
  19626. change - see the ComponentListener class for more details.
  19627. @param newListener the listener to register - if this is already registered, it
  19628. will be ignored.
  19629. @see ComponentListener, removeComponentListener
  19630. */
  19631. void addComponentListener (ComponentListener* newListener);
  19632. /** Removes a component listener.
  19633. @see addComponentListener
  19634. */
  19635. void removeComponentListener (ComponentListener* listenerToRemove);
  19636. /** Dispatches a numbered message to this component.
  19637. This is a quick and cheap way of allowing simple asynchronous messages to
  19638. be sent to components. It's also safe, because if the component that you
  19639. send the message to is a null or dangling pointer, this won't cause an error.
  19640. The command ID is later delivered to the component's handleCommandMessage() method by
  19641. the application's message queue.
  19642. @see handleCommandMessage
  19643. */
  19644. void postCommandMessage (int commandId);
  19645. /** Called to handle a command that was sent by postCommandMessage().
  19646. This is called by the message thread when a command message arrives, and
  19647. the component can override this method to process it in any way it needs to.
  19648. @see postCommandMessage
  19649. */
  19650. virtual void handleCommandMessage (int commandId);
  19651. /** Runs a component modally, waiting until the loop terminates.
  19652. This method first makes the component visible, brings it to the front and
  19653. gives it the keyboard focus.
  19654. It then runs a loop, dispatching messages from the system message queue, but
  19655. blocking all mouse or keyboard messages from reaching any components other
  19656. than this one and its children.
  19657. This loop continues until the component's exitModalState() method is called (or
  19658. the component is deleted), and then this method returns, returning the value
  19659. passed into exitModalState().
  19660. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  19661. isCurrentlyBlockedByAnotherModalComponent, MessageManager::dispatchNextMessage
  19662. */
  19663. int runModalLoop();
  19664. /** Puts the component into a modal state.
  19665. This makes the component modal, so that messages are blocked from reaching
  19666. any components other than this one and its children, but unlike runModalLoop(),
  19667. this method returns immediately.
  19668. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  19669. get the focus, which is usually what you'll want it to do. If not, it will leave
  19670. the focus unchanged.
  19671. @see exitModalState, runModalLoop
  19672. */
  19673. void enterModalState (bool takeKeyboardFocus = true);
  19674. /** Ends a component's modal state.
  19675. If this component is currently modal, this will turn of its modalness, and return
  19676. a value to the runModalLoop() method that might have be running its modal loop.
  19677. @see runModalLoop, enterModalState, isCurrentlyModal
  19678. */
  19679. void exitModalState (int returnValue);
  19680. /** Returns true if this component is the modal one.
  19681. It's possible to have nested modal components, e.g. a pop-up dialog box
  19682. that launches another pop-up, but this will only return true for
  19683. the one at the top of the stack.
  19684. @see getCurrentlyModalComponent
  19685. */
  19686. bool isCurrentlyModal() const throw();
  19687. /** Returns the number of components that are currently in a modal state.
  19688. @see getCurrentlyModalComponent
  19689. */
  19690. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  19691. /** Returns one of the components that are currently modal.
  19692. The index specifies which of the possible modal components to return. The order
  19693. of the components in this list is the reverse of the order in which they became
  19694. modal - so the component at index 0 is always the active component, and the others
  19695. are progressively earlier ones that are themselves now blocked by later ones.
  19696. @returns the modal component, or null if no components are modal (or if the
  19697. index is out of range)
  19698. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  19699. */
  19700. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  19701. /** Checks whether there's a modal component somewhere that's stopping this one
  19702. from receiving messages.
  19703. If there is a modal component, its canModalEventBeSentToComponent() method
  19704. will be called to see if it will still allow this component to receive events.
  19705. @see runModalLoop, getCurrentlyModalComponent
  19706. */
  19707. bool isCurrentlyBlockedByAnotherModalComponent() const;
  19708. /** When a component is modal, this callback allows it to choose which other
  19709. components can still receive events.
  19710. When a modal component is active and the user clicks on a non-modal component,
  19711. this method is called on the modal component, and if it returns true, the
  19712. event is allowed to reach its target. If it returns false, the event is blocked
  19713. and the inputAttemptWhenModal() callback is made.
  19714. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  19715. implementation just returns false in all cases.
  19716. */
  19717. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  19718. /** Called when the user tries to click on a component that is blocked by another
  19719. modal component.
  19720. When a component is modal and the user clicks on one of the other components,
  19721. the modal component will receive this callback.
  19722. The default implementation of this method will play a beep, and bring the currently
  19723. modal component to the front, but it can be overridden to do other tasks.
  19724. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  19725. */
  19726. virtual void inputAttemptWhenModal();
  19727. /** Returns the set of properties that belong to this component.
  19728. Each component has a NamedValueSet object which you can use to attach arbitrary
  19729. items of data to it.
  19730. */
  19731. NamedValueSet& getProperties() throw() { return properties; }
  19732. /** Returns the set of properties that belong to this component.
  19733. Each component has a NamedValueSet object which you can use to attach arbitrary
  19734. items of data to it.
  19735. */
  19736. const NamedValueSet& getProperties() const throw() { return properties; }
  19737. /** Looks for a colour that has been registered with the given colour ID number.
  19738. If a colour has been set for this ID number using setColour(), then it is
  19739. returned. If none has been set, the method will try calling the component's
  19740. LookAndFeel class's findColour() method. If none has been registered with the
  19741. look-and-feel either, it will just return black.
  19742. The colour IDs for various purposes are stored as enums in the components that
  19743. they are relevent to - for an example, see Slider::ColourIds,
  19744. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  19745. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  19746. */
  19747. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  19748. /** Registers a colour to be used for a particular purpose.
  19749. Changing a colour will cause a synchronous callback to the colourChanged()
  19750. method, which your component can override if it needs to do something when
  19751. colours are altered.
  19752. For more details about colour IDs, see the comments for findColour().
  19753. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  19754. */
  19755. void setColour (int colourId, const Colour& colour);
  19756. /** If a colour has been set with setColour(), this will remove it.
  19757. This allows you to make a colour revert to its default state.
  19758. */
  19759. void removeColour (int colourId);
  19760. /** Returns true if the specified colour ID has been explicitly set for this
  19761. component using the setColour() method.
  19762. */
  19763. bool isColourSpecified (int colourId) const;
  19764. /** This looks for any colours that have been specified for this component,
  19765. and copies them to the specified target component.
  19766. */
  19767. void copyAllExplicitColoursTo (Component& target) const;
  19768. /** This method is called when a colour is changed by the setColour() method.
  19769. @see setColour, findColour
  19770. */
  19771. virtual void colourChanged();
  19772. /** Returns the underlying native window handle for this component.
  19773. This is platform-dependent and strictly for power-users only!
  19774. */
  19775. void* getWindowHandle() const;
  19776. /** When created, each component is given a number to uniquely identify it.
  19777. The number is incremented each time a new component is created, so it's a more
  19778. unique way of identifying a component than using its memory location (which
  19779. may be reused after the component is deleted, of course).
  19780. */
  19781. uint32 getComponentUID() const throw() { return componentUID; }
  19782. /** Holds a pointer to some type of Component, which automatically becomes null if
  19783. the component is deleted.
  19784. If you're using a component which may be deleted by another event that's outside
  19785. of your control, use a SafePointer instead of a normal pointer to refer to it,
  19786. and you can test whether it's null before using it to see if something has deleted
  19787. it.
  19788. The ComponentType typedef must be Component, or some subclass of Component.
  19789. Note that this class isn't thread-safe, and assumes that all the code that uses
  19790. it is running on the message thread.
  19791. */
  19792. template <class ComponentType>
  19793. class SafePointer : private ComponentListener
  19794. {
  19795. public:
  19796. /** Creates a null SafePointer. */
  19797. SafePointer() : comp (0) {}
  19798. /** Creates a SafePointer that points at the given component. */
  19799. SafePointer (ComponentType* const component) : comp (component) { attach(); }
  19800. /** Creates a copy of another SafePointer. */
  19801. SafePointer (const SafePointer& other) : comp (other.comp) { attach(); }
  19802. /** Destructor. */
  19803. ~SafePointer() { detach(); }
  19804. /** Copies another pointer to this one. */
  19805. SafePointer& operator= (const SafePointer& other) { return operator= (other.comp); }
  19806. /** Copies another pointer to this one. */
  19807. SafePointer& operator= (ComponentType* const newComponent)
  19808. {
  19809. detach();
  19810. comp = newComponent;
  19811. attach();
  19812. return *this;
  19813. }
  19814. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  19815. operator ComponentType*() const throw() { return comp; }
  19816. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  19817. ComponentType* getComponent() const throw() { return comp; }
  19818. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  19819. ComponentType* operator->() throw() { jassert (comp != 0); return comp; }
  19820. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  19821. const ComponentType* operator->() const throw() { jassert (comp != 0); return comp; }
  19822. juce_UseDebuggingNewOperator
  19823. private:
  19824. ComponentType* comp;
  19825. void attach() { if (comp != 0) comp->addComponentListener (this); }
  19826. void detach() { if (comp != 0) comp->removeComponentListener (this); }
  19827. void componentBeingDeleted (Component&) { comp = 0; }
  19828. };
  19829. /** A class to keep an eye on one or two components and check for them being deleted.
  19830. This is designed for use with the ListenerList::callChecked() methods, to allow
  19831. the list iterator to stop cleanly if the component is deleted by a listener callback
  19832. while the list is still being iterated.
  19833. */
  19834. class BailOutChecker
  19835. {
  19836. public:
  19837. /** Creates a checker that watches either one or two components.
  19838. component1 must be a valid component; component2 can be null if you only need
  19839. to check on one component.
  19840. */
  19841. BailOutChecker (Component* component1,
  19842. Component* component2 = 0);
  19843. /** Returns true if either of the two components have been deleted since this
  19844. object was created. */
  19845. bool shouldBailOut() const throw();
  19846. private:
  19847. typedef SafePointer<Component> SafeComponentPtr;
  19848. SafeComponentPtr safePointer1, safePointer2;
  19849. Component* const component2;
  19850. BailOutChecker (const BailOutChecker&);
  19851. BailOutChecker& operator= (const BailOutChecker&);
  19852. };
  19853. juce_UseDebuggingNewOperator
  19854. private:
  19855. friend class ComponentPeer;
  19856. friend class InternalDragRepeater;
  19857. friend class MouseInputSource;
  19858. friend class MouseInputSourceInternal;
  19859. static Component* currentlyFocusedComponent;
  19860. String componentName_;
  19861. Component* parentComponent_;
  19862. uint32 componentUID;
  19863. Rectangle<int> bounds_;
  19864. int numDeepMouseListeners;
  19865. Array <Component*> childComponentList_;
  19866. LookAndFeel* lookAndFeel_;
  19867. MouseCursor cursor_;
  19868. ImageEffectFilter* effect_;
  19869. Image* bufferedImage_;
  19870. Array <MouseListener*>* mouseListeners_;
  19871. Array <KeyListener*>* keyListeners_;
  19872. ListenerList <ComponentListener> componentListeners;
  19873. NamedValueSet properties;
  19874. struct ComponentFlags
  19875. {
  19876. bool hasHeavyweightPeerFlag : 1;
  19877. bool visibleFlag : 1;
  19878. bool opaqueFlag : 1;
  19879. bool ignoresMouseClicksFlag : 1;
  19880. bool allowChildMouseClicksFlag : 1;
  19881. bool wantsFocusFlag : 1;
  19882. bool isFocusContainerFlag : 1;
  19883. bool dontFocusOnMouseClickFlag : 1;
  19884. bool alwaysOnTopFlag : 1;
  19885. bool bufferToImageFlag : 1;
  19886. bool bringToFrontOnClickFlag : 1;
  19887. bool repaintOnMouseActivityFlag : 1;
  19888. bool draggingFlag : 1;
  19889. bool mouseOverFlag : 1;
  19890. bool mouseInsideFlag : 1;
  19891. bool currentlyModalFlag : 1;
  19892. bool isDisabledFlag : 1;
  19893. bool childCompFocusedFlag : 1;
  19894. #if JUCE_DEBUG
  19895. bool isInsidePaintCall : 1;
  19896. #endif
  19897. };
  19898. union
  19899. {
  19900. uint32 componentFlags_;
  19901. ComponentFlags flags;
  19902. };
  19903. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  19904. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  19905. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  19906. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  19907. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  19908. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  19909. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  19910. void internalBroughtToFront();
  19911. void internalFocusGain (const FocusChangeType cause);
  19912. void internalFocusLoss (const FocusChangeType cause);
  19913. void internalChildFocusChange (FocusChangeType cause);
  19914. void internalModalInputAttempt();
  19915. void internalModifierKeysChanged();
  19916. void internalChildrenChanged();
  19917. void internalHierarchyChanged();
  19918. void renderComponent (Graphics& context);
  19919. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  19920. void repaintParent();
  19921. void sendFakeMouseMove() const;
  19922. void takeKeyboardFocus (const FocusChangeType cause);
  19923. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  19924. static void giveAwayFocus();
  19925. void sendEnablementChangeMessage();
  19926. static void* runModalLoopCallback (void*);
  19927. static void bringModalComponentToFront();
  19928. void subtractObscuredRegions (RectangleList& result, const Point<int>& delta,
  19929. const Rectangle<int>& clipRect,
  19930. const Component* const compToAvoid) const;
  19931. void clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  19932. int deltaX, int deltaY) const;
  19933. // how much of the component is not off the edges of its parents
  19934. const Rectangle<int> getUnclippedArea() const;
  19935. void sendVisibilityChangeMessage();
  19936. // This is included here just to cause a compile error if your code is still handling
  19937. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  19938. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  19939. // implement its methods instead of this Component method).
  19940. virtual void filesDropped (const StringArray&, int, int) {}
  19941. // components aren't allowed to have copy constructors, as this would mess up parent
  19942. // hierarchies. You might need to give your subclasses a private dummy constructor like
  19943. // this one to avoid compiler warnings.
  19944. Component (const Component&);
  19945. Component& operator= (const Component&);
  19946. protected:
  19947. /** @internal */
  19948. virtual void internalRepaint (int x, int y, int w, int h);
  19949. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  19950. /** Overridden from the MessageListener parent class.
  19951. You can override this if you really need to, but be sure to pass your unwanted messages up
  19952. to this base class implementation, as the Component class needs to send itself messages
  19953. to work properly.
  19954. */
  19955. void handleMessage (const Message&);
  19956. };
  19957. #endif // __JUCE_COMPONENT_JUCEHEADER__
  19958. /*** End of inlined file: juce_Component.h ***/
  19959. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  19960. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  19961. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  19962. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  19963. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  19964. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  19965. /** A type used to hold the unique ID for an application command.
  19966. This is a numeric type, so it can be stored as an integer.
  19967. @see ApplicationCommandInfo, ApplicationCommandManager,
  19968. ApplicationCommandTarget, KeyPressMappingSet
  19969. */
  19970. typedef int CommandID;
  19971. /** A set of general-purpose application command IDs.
  19972. Because these commands are likely to be used in most apps, they're defined
  19973. here to help different apps to use the same numeric values for them.
  19974. Of course you don't have to use these, but some of them are used internally by
  19975. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  19976. @see ApplicationCommandInfo, ApplicationCommandManager,
  19977. ApplicationCommandTarget, KeyPressMappingSet
  19978. */
  19979. namespace StandardApplicationCommandIDs
  19980. {
  19981. /** This command ID should be used to send a "Quit the App" command.
  19982. This command is recognised by the JUCEApplication class, so if it is invoked
  19983. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  19984. object will catch it and call JUCEApplication::systemRequestedQuit().
  19985. */
  19986. static const CommandID quit = 0x1001;
  19987. /** The command ID that should be used to send a "Delete" command. */
  19988. static const CommandID del = 0x1002;
  19989. /** The command ID that should be used to send a "Cut" command. */
  19990. static const CommandID cut = 0x1003;
  19991. /** The command ID that should be used to send a "Copy to clipboard" command. */
  19992. static const CommandID copy = 0x1004;
  19993. /** The command ID that should be used to send a "Paste from clipboard" command. */
  19994. static const CommandID paste = 0x1005;
  19995. /** The command ID that should be used to send a "Select all" command. */
  19996. static const CommandID selectAll = 0x1006;
  19997. /** The command ID that should be used to send a "Deselect all" command. */
  19998. static const CommandID deselectAll = 0x1007;
  19999. }
  20000. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20001. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  20002. /**
  20003. Holds information describing an application command.
  20004. This object is used to pass information about a particular command, such as its
  20005. name, description and other usage flags.
  20006. When an ApplicationCommandTarget is asked to provide information about the commands
  20007. it can perform, this is the structure gets filled-in to describe each one.
  20008. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  20009. ApplicationCommandManager
  20010. */
  20011. struct JUCE_API ApplicationCommandInfo
  20012. {
  20013. explicit ApplicationCommandInfo (CommandID commandID) throw();
  20014. /** Sets a number of the structures values at once.
  20015. The meanings of each of the parameters is described below, in the appropriate
  20016. member variable's description.
  20017. */
  20018. void setInfo (const String& shortName,
  20019. const String& description,
  20020. const String& categoryName,
  20021. int flags) throw();
  20022. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  20023. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  20024. is false, the bit is set.
  20025. */
  20026. void setActive (bool isActive) throw();
  20027. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  20028. */
  20029. void setTicked (bool isTicked) throw();
  20030. /** Handy method for adding a keypress to the defaultKeypresses array.
  20031. This is just so you can write things like:
  20032. @code
  20033. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  20034. @endcode
  20035. instead of
  20036. @code
  20037. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  20038. @endcode
  20039. */
  20040. void addDefaultKeypress (int keyCode,
  20041. const ModifierKeys& modifiers) throw();
  20042. /** The command's unique ID number.
  20043. */
  20044. CommandID commandID;
  20045. /** A short name to describe the command.
  20046. This should be suitable for use in menus, on buttons that trigger the command, etc.
  20047. You can use the setInfo() method to quickly set this and some of the command's
  20048. other properties.
  20049. */
  20050. String shortName;
  20051. /** A longer description of the command.
  20052. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  20053. pop-up tooltip describing what the command does.
  20054. You can use the setInfo() method to quickly set this and some of the command's
  20055. other properties.
  20056. */
  20057. String description;
  20058. /** A named category that the command fits into.
  20059. You can give your commands any category you like, and these will be displayed in
  20060. contexts such as the KeyMappingEditorComponent, where the category is used to group
  20061. commands together.
  20062. You can use the setInfo() method to quickly set this and some of the command's
  20063. other properties.
  20064. */
  20065. String categoryName;
  20066. /** A list of zero or more keypresses that should be used as the default keys for
  20067. this command.
  20068. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  20069. this list to initialise the default set of key-to-command mappings.
  20070. @see addDefaultKeypress
  20071. */
  20072. Array <KeyPress> defaultKeypresses;
  20073. /** Flags describing the ways in which this command should be used.
  20074. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  20075. variable.
  20076. */
  20077. enum CommandFlags
  20078. {
  20079. /** Indicates that the command can't currently be performed.
  20080. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  20081. not currently permissable to perform the command. If the flag is set, then
  20082. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  20083. command or show themselves as not being enabled.
  20084. @see ApplicationCommandInfo::setActive
  20085. */
  20086. isDisabled = 1 << 0,
  20087. /** Indicates that the command should have a tick next to it on a menu.
  20088. If your command is shown on a menu and this is set, it'll show a tick next to
  20089. it. Other components such as buttons may also use this flag to indicate that it
  20090. is a value that can be toggled, and is currently in the 'on' state.
  20091. @see ApplicationCommandInfo::setTicked
  20092. */
  20093. isTicked = 1 << 1,
  20094. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  20095. it will call the command twice, once on key-down and again on key-up.
  20096. @see ApplicationCommandTarget::InvocationInfo
  20097. */
  20098. wantsKeyUpDownCallbacks = 1 << 2,
  20099. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  20100. command in its list.
  20101. */
  20102. hiddenFromKeyEditor = 1 << 3,
  20103. /** If this flag is present, then a KeyMappingEditorComponent will display the
  20104. command in its list, but won't allow the assigned keypress to be changed.
  20105. */
  20106. readOnlyInKeyEditor = 1 << 4,
  20107. /** If this flag is present and the command is invoked from a keypress, then any
  20108. buttons or menus that are also connected to the command will not flash to
  20109. indicate that they've been triggered.
  20110. */
  20111. dontTriggerVisualFeedback = 1 << 5
  20112. };
  20113. /** A bitwise-OR of the values specified in the CommandFlags enum.
  20114. You can use the setInfo() method to quickly set this and some of the command's
  20115. other properties.
  20116. */
  20117. int flags;
  20118. };
  20119. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20120. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  20121. /**
  20122. A command target publishes a list of command IDs that it can perform.
  20123. An ApplicationCommandManager despatches commands to targets, which must be
  20124. able to provide information about what commands they can handle.
  20125. To create a target, you'll need to inherit from this class, implementing all of
  20126. its pure virtual methods.
  20127. For info about how a target is chosen to receive a command, see
  20128. ApplicationCommandManager::getFirstCommandTarget().
  20129. @see ApplicationCommandManager, ApplicationCommandInfo
  20130. */
  20131. class JUCE_API ApplicationCommandTarget
  20132. {
  20133. public:
  20134. /** Creates a command target. */
  20135. ApplicationCommandTarget();
  20136. /** Destructor. */
  20137. virtual ~ApplicationCommandTarget();
  20138. /**
  20139. */
  20140. struct JUCE_API InvocationInfo
  20141. {
  20142. InvocationInfo (const CommandID commandID) throw();
  20143. /** The UID of the command that should be performed. */
  20144. CommandID commandID;
  20145. /** The command's flags.
  20146. See ApplicationCommandInfo for a description of these flag values.
  20147. */
  20148. int commandFlags;
  20149. /** The types of context in which the command might be called. */
  20150. enum InvocationMethod
  20151. {
  20152. direct = 0, /**< The command is being invoked directly by a piece of code. */
  20153. fromKeyPress, /**< The command is being invoked by a key-press. */
  20154. fromMenu, /**< The command is being invoked by a menu selection. */
  20155. fromButton /**< The command is being invoked by a button click. */
  20156. };
  20157. /** The type of event that triggered this command. */
  20158. InvocationMethod invocationMethod;
  20159. /** If triggered by a keypress or menu, this will be the component that had the
  20160. keyboard focus at the time.
  20161. If triggered by a button, it may be set to that component, or it may be null.
  20162. */
  20163. Component* originatingComponent;
  20164. /** The keypress that was used to invoke it.
  20165. Note that this will be an invalid keypress if the command was invoked
  20166. by some other means than a keyboard shortcut.
  20167. */
  20168. KeyPress keyPress;
  20169. /** True if the callback is being invoked when the key is pressed,
  20170. false if the key is being released.
  20171. @see KeyPressMappingSet::addCommand()
  20172. */
  20173. bool isKeyDown;
  20174. /** If the key is being released, this indicates how long it had been held
  20175. down for.
  20176. (Only relevant if isKeyDown is false.)
  20177. */
  20178. int millisecsSinceKeyPressed;
  20179. };
  20180. /** This must return the next target to try after this one.
  20181. When a command is being sent, and the first target can't handle
  20182. that command, this method is used to determine the next target that should
  20183. be tried.
  20184. It may return 0 if it doesn't know of another target.
  20185. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  20186. method to return a parent component that might want to handle it.
  20187. @see invoke
  20188. */
  20189. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  20190. /** This must return a complete list of commands that this target can handle.
  20191. Your target should add all the command IDs that it handles to the array that is
  20192. passed-in.
  20193. */
  20194. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  20195. /** This must provide details about one of the commands that this target can perform.
  20196. This will be called with one of the command IDs that the target provided in its
  20197. getAllCommands() methods.
  20198. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  20199. suitable information about the command. (The commandID field will already have been filled-in
  20200. by the caller).
  20201. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  20202. set all the fields at once.
  20203. If the command is currently inactive for some reason, this method must use
  20204. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  20205. bit of the ApplicationCommandInfo::flags field).
  20206. Any default key-presses for the command should be appended to the
  20207. ApplicationCommandInfo::defaultKeypresses field.
  20208. Note that if you change something that affects the status of the commands
  20209. that would be returned by this method (e.g. something that makes some commands
  20210. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  20211. to cause the manager to refresh its status.
  20212. */
  20213. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  20214. /** This must actually perform the specified command.
  20215. If this target is able to perform the command specified by the commandID field of the
  20216. InvocationInfo structure, then it should do so, and must return true.
  20217. If it can't handle this command, it should return false, which tells the caller to pass
  20218. the command on to the next target in line.
  20219. @see invoke, ApplicationCommandManager::invoke
  20220. */
  20221. virtual bool perform (const InvocationInfo& info) = 0;
  20222. /** Makes this target invoke a command.
  20223. Your code can call this method to invoke a command on this target, but normally
  20224. you'd call it indirectly via ApplicationCommandManager::invoke() or
  20225. ApplicationCommandManager::invokeDirectly().
  20226. If this target can perform the given command, it will call its perform() method to
  20227. do so. If not, then getNextCommandTarget() will be used to determine the next target
  20228. to try, and the command will be passed along to it.
  20229. @param invocationInfo this must be correctly filled-in, describing the context for
  20230. the invocation.
  20231. @param asynchronously if false, the command will be performed before this method returns.
  20232. If true, a message will be posted so that the command will be performed
  20233. later on the message thread, and this method will return immediately.
  20234. @see perform, ApplicationCommandManager::invoke
  20235. */
  20236. bool invoke (const InvocationInfo& invocationInfo,
  20237. const bool asynchronously);
  20238. /** Invokes a given command directly on this target.
  20239. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  20240. structure.
  20241. */
  20242. bool invokeDirectly (const CommandID commandID,
  20243. const bool asynchronously);
  20244. /** Searches this target and all subsequent ones for the first one that can handle
  20245. the specified command.
  20246. This will use getNextCommandTarget() to determine the chain of targets to try
  20247. after this one.
  20248. */
  20249. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  20250. /** Checks whether this command can currently be performed by this target.
  20251. This will return true only if a call to getCommandInfo() doesn't set the
  20252. isDisabled flag to indicate that the command is inactive.
  20253. */
  20254. bool isCommandActive (const CommandID commandID);
  20255. /** If this object is a Component, this method will seach upwards in its current
  20256. UI hierarchy for the next parent component that implements the
  20257. ApplicationCommandTarget class.
  20258. If your target is a Component, this is a very handy method to use in your
  20259. getNextCommandTarget() implementation.
  20260. */
  20261. ApplicationCommandTarget* findFirstTargetParentComponent();
  20262. juce_UseDebuggingNewOperator
  20263. private:
  20264. // (for async invocation of commands)
  20265. class CommandTargetMessageInvoker : public MessageListener
  20266. {
  20267. public:
  20268. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  20269. ~CommandTargetMessageInvoker();
  20270. void handleMessage (const Message& message);
  20271. private:
  20272. ApplicationCommandTarget* const owner;
  20273. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  20274. CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  20275. };
  20276. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  20277. friend class CommandTargetMessageInvoker;
  20278. bool tryToInvoke (const InvocationInfo& info, const bool async);
  20279. ApplicationCommandTarget (const ApplicationCommandTarget&);
  20280. ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  20281. };
  20282. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  20283. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  20284. /*** Start of inlined file: juce_ActionListener.h ***/
  20285. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  20286. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  20287. /**
  20288. Receives callbacks to indicate that some kind of event has occurred.
  20289. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  20290. about something that's happened.
  20291. @see ActionListenerList, ActionBroadcaster, ChangeListener
  20292. */
  20293. class JUCE_API ActionListener
  20294. {
  20295. public:
  20296. /** Destructor. */
  20297. virtual ~ActionListener() {}
  20298. /** Overridden by your subclass to receive the callback.
  20299. @param message the string that was specified when the event was triggered
  20300. by a call to ActionListenerList::sendActionMessage()
  20301. */
  20302. virtual void actionListenerCallback (const String& message) = 0;
  20303. };
  20304. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  20305. /*** End of inlined file: juce_ActionListener.h ***/
  20306. /**
  20307. An instance of this class is used to specify initialisation and shutdown
  20308. code for the application.
  20309. An application that wants to run in the JUCE framework needs to declare a
  20310. subclass of JUCEApplication and implement its various pure virtual methods.
  20311. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  20312. to declare an instance of this class and generate a suitable platform-specific
  20313. main() function.
  20314. e.g. @code
  20315. class MyJUCEApp : public JUCEApplication
  20316. {
  20317. // NEVER put objects inside a JUCEApplication class - only use pointers to
  20318. // objects, which you must create in the initialise() method.
  20319. MyApplicationWindow* myMainWindow;
  20320. public:
  20321. MyJUCEApp()
  20322. : myMainWindow (0)
  20323. {
  20324. // never create any Juce objects in the constructor - do all your initialisation
  20325. // in the initialise() method.
  20326. }
  20327. ~MyJUCEApp()
  20328. {
  20329. // all your shutdown code must have already been done in the shutdown() method -
  20330. // nothing should happen in this destructor.
  20331. }
  20332. void initialise (const String& commandLine)
  20333. {
  20334. myMainWindow = new MyApplicationWindow();
  20335. myMainWindow->setBounds (100, 100, 400, 500);
  20336. myMainWindow->setVisible (true);
  20337. }
  20338. void shutdown()
  20339. {
  20340. delete myMainWindow;
  20341. }
  20342. const String getApplicationName()
  20343. {
  20344. return "Super JUCE-o-matic";
  20345. }
  20346. const String getApplicationVersion()
  20347. {
  20348. return "1.0";
  20349. }
  20350. };
  20351. // this creates wrapper code to actually launch the app properly.
  20352. START_JUCE_APPLICATION (MyJUCEApp)
  20353. @endcode
  20354. Because this object will be created before Juce has properly initialised, you must
  20355. NEVER add any member variable objects that will be automatically constructed. Likewise
  20356. don't put ANY code in the constructor that could call Juce functions. Any objects that
  20357. you want to add to the class must be pointers, which you should instantiate during the
  20358. initialise() method, and delete in the shutdown() method.
  20359. @see MessageManager, DeletedAtShutdown
  20360. */
  20361. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  20362. private ActionListener
  20363. {
  20364. protected:
  20365. /** Constructs a JUCE app object.
  20366. If subclasses implement a constructor or destructor, they shouldn't call any
  20367. JUCE code in there - put your startup/shutdown code in initialise() and
  20368. shutdown() instead.
  20369. */
  20370. JUCEApplication();
  20371. public:
  20372. /** Destructor.
  20373. If subclasses implement a constructor or destructor, they shouldn't call any
  20374. JUCE code in there - put your startup/shutdown code in initialise() and
  20375. shutdown() instead.
  20376. */
  20377. virtual ~JUCEApplication();
  20378. /** Returns the global instance of the application object being run. */
  20379. static JUCEApplication* getInstance() throw();
  20380. /** Called when the application starts.
  20381. This will be called once to let the application do whatever initialisation
  20382. it needs, create its windows, etc.
  20383. After the method returns, the normal event-dispatch loop will be run,
  20384. until the quit() method is called, at which point the shutdown()
  20385. method will be called to let the application clear up anything it needs
  20386. to delete.
  20387. If during the initialise() method, the application decides not to start-up
  20388. after all, it can just call the quit() method and the event loop won't be run.
  20389. @param commandLineParameters the line passed in does not include the
  20390. name of the executable, just the parameter list.
  20391. @see shutdown, quit
  20392. */
  20393. virtual void initialise (const String& commandLineParameters) = 0;
  20394. /** Returns true if the application hasn't yet completed its initialise() method
  20395. and entered the main event loop.
  20396. This is handy for things like splash screens to know when the app's up-and-running
  20397. properly.
  20398. */
  20399. bool isInitialising() const throw();
  20400. /* Called to allow the application to clear up before exiting.
  20401. After JUCEApplication::quit() has been called, the event-dispatch loop will
  20402. terminate, and this method will get called to allow the app to sort itself
  20403. out.
  20404. Be careful that nothing happens in this method that might rely on messages
  20405. being sent, or any kind of window activity, because the message loop is no
  20406. longer running at this point.
  20407. @see DeletedAtShutdown
  20408. */
  20409. virtual void shutdown() = 0;
  20410. /** Returns the application's name.
  20411. An application must implement this to name itself.
  20412. */
  20413. virtual const String getApplicationName() = 0;
  20414. /** Returns the application's version number.
  20415. An application can implement this to give itself a version.
  20416. (The default implementation of this just returns an empty string).
  20417. */
  20418. virtual const String getApplicationVersion();
  20419. /** Checks whether multiple instances of the app are allowed.
  20420. If you application class returns true for this, more than one instance is
  20421. permitted to run (except on the Mac where this isn't possible).
  20422. If it's false, the second instance won't start, but it you will still get a
  20423. callback to anotherInstanceStarted() to tell you about this - which
  20424. gives you a chance to react to what the user was trying to do.
  20425. */
  20426. virtual bool moreThanOneInstanceAllowed();
  20427. /** Indicates that the user has tried to start up another instance of the app.
  20428. This will get called even if moreThanOneInstanceAllowed() is false.
  20429. */
  20430. virtual void anotherInstanceStarted (const String& commandLine);
  20431. /** Called when the operating system is trying to close the application.
  20432. The default implementation of this method is to call quit(), but it may
  20433. be overloaded to ignore the request or do some other special behaviour
  20434. instead. For example, you might want to offer the user the chance to save
  20435. their changes before quitting, and give them the chance to cancel.
  20436. If you want to send a quit signal to your app, this is the correct method
  20437. to call, because it means that requests that come from the system get handled
  20438. in the same way as those from your own application code. So e.g. you'd
  20439. call this method from a "quit" item on a menu bar.
  20440. */
  20441. virtual void systemRequestedQuit();
  20442. /** If any unhandled exceptions make it through to the message dispatch loop, this
  20443. callback will be triggered, in case you want to log them or do some other
  20444. type of error-handling.
  20445. If the type of exception is derived from the std::exception class, the pointer
  20446. passed-in will be valid. If the exception is of unknown type, this pointer
  20447. will be null.
  20448. */
  20449. virtual void unhandledException (const std::exception* e,
  20450. const String& sourceFilename,
  20451. int lineNumber);
  20452. /** Signals that the main message loop should stop and the application should terminate.
  20453. This isn't synchronous, it just posts a quit message to the main queue, and
  20454. when this message arrives, the message loop will stop, the shutdown() method
  20455. will be called, and the app will exit.
  20456. Note that this will cause an unconditional quit to happen, so if you need an
  20457. extra level before this, e.g. to give the user the chance to save their work
  20458. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  20459. method - see that method's help for more info.
  20460. @see MessageManager, DeletedAtShutdown
  20461. */
  20462. static void quit();
  20463. /** Sets the value that should be returned as the application's exit code when the
  20464. app quits.
  20465. This is the value that's returned by the main() function. Normally you'd leave this
  20466. as 0 unless you want to indicate an error code.
  20467. @see getApplicationReturnValue
  20468. */
  20469. void setApplicationReturnValue (int newReturnValue) throw();
  20470. /** Returns the value that has been set as the application's exit code.
  20471. @see setApplicationReturnValue
  20472. */
  20473. int getApplicationReturnValue() const throw() { return appReturnValue; }
  20474. /** Returns the application's command line params.
  20475. */
  20476. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  20477. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  20478. /** @internal */
  20479. static int main (String& commandLine, JUCEApplication* newApp);
  20480. /** @internal */
  20481. static int main (int argc, const char* argv[], JUCEApplication* newApp);
  20482. /** @internal */
  20483. static void sendUnhandledException (const std::exception* e,
  20484. const char* sourceFile,
  20485. int lineNumber);
  20486. /** @internal */
  20487. ApplicationCommandTarget* getNextCommandTarget();
  20488. /** @internal */
  20489. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  20490. /** @internal */
  20491. void getAllCommands (Array <CommandID>& commands);
  20492. /** @internal */
  20493. bool perform (const InvocationInfo& info);
  20494. /** @internal */
  20495. void actionListenerCallback (const String& message);
  20496. private:
  20497. String commandLineParameters;
  20498. int appReturnValue;
  20499. bool stillInitialising;
  20500. ScopedPointer<InterProcessLock> appLock;
  20501. JUCEApplication (const JUCEApplication&);
  20502. JUCEApplication& operator= (const JUCEApplication&);
  20503. public:
  20504. /** @internal */
  20505. bool initialiseApp (String& commandLine);
  20506. /** @internal */
  20507. static int shutdownAppAndClearUp();
  20508. };
  20509. #endif // __JUCE_APPLICATION_JUCEHEADER__
  20510. /*** End of inlined file: juce_Application.h ***/
  20511. #endif
  20512. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20513. #endif
  20514. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20515. #endif
  20516. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20517. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  20518. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20519. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  20520. /*** Start of inlined file: juce_Desktop.h ***/
  20521. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  20522. #define __JUCE_DESKTOP_JUCEHEADER__
  20523. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  20524. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20525. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20526. /**
  20527. Classes derived from this will be automatically deleted when the application exits.
  20528. After JUCEApplication::shutdown() has been called, any objects derived from
  20529. DeletedAtShutdown which are still in existence will be deleted in the reverse
  20530. order to that in which they were created.
  20531. So if you've got a singleton and don't want to have to explicitly delete it, just
  20532. inherit from this and it'll be taken care of.
  20533. */
  20534. class JUCE_API DeletedAtShutdown
  20535. {
  20536. protected:
  20537. /** Creates a DeletedAtShutdown object. */
  20538. DeletedAtShutdown();
  20539. /** Destructor.
  20540. It's ok to delete these objects explicitly - it's only the ones left
  20541. dangling at the end that will be deleted automatically.
  20542. */
  20543. virtual ~DeletedAtShutdown();
  20544. public:
  20545. /** Deletes all extant objects.
  20546. This shouldn't be used by applications, as it's called automatically
  20547. in the shutdown code of the JUCEApplication class.
  20548. */
  20549. static void deleteAll();
  20550. private:
  20551. DeletedAtShutdown (const DeletedAtShutdown&);
  20552. DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  20553. static CriticalSection& getLock();
  20554. static Array <DeletedAtShutdown*>& getObjects();
  20555. };
  20556. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  20557. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  20558. /*** Start of inlined file: juce_Timer.h ***/
  20559. #ifndef __JUCE_TIMER_JUCEHEADER__
  20560. #define __JUCE_TIMER_JUCEHEADER__
  20561. class InternalTimerThread;
  20562. /**
  20563. Repeatedly calls a user-defined method at a specified time interval.
  20564. A Timer's timerCallback() method will be repeatedly called at a given
  20565. interval. Initially when a Timer object is created, they will do nothing
  20566. until the startTimer() method is called, then the message thread will
  20567. start calling it back until stopTimer() is called.
  20568. The time interval isn't guaranteed to be precise to any more than maybe
  20569. 10-20ms, and the intervals may end up being much longer than requested if the
  20570. system is busy. Because it's the message thread that is doing the callbacks,
  20571. any messages that take a significant amount of time to process will block
  20572. all the timers for that period.
  20573. If you need to have a single callback that is shared by multiple timers with
  20574. different frequencies, then the MultiTimer class allows you to do that - its
  20575. structure is very similar to the Timer class, but contains multiple timers
  20576. internally, each one identified by an ID number.
  20577. @see MultiTimer
  20578. */
  20579. class JUCE_API Timer
  20580. {
  20581. protected:
  20582. /** Creates a Timer.
  20583. When created, the timer is stopped, so use startTimer() to get it going.
  20584. */
  20585. Timer() throw();
  20586. /** Creates a copy of another timer.
  20587. Note that this timer won't be started, even if the one you're copying
  20588. is running.
  20589. */
  20590. Timer (const Timer& other) throw();
  20591. public:
  20592. /** Destructor. */
  20593. virtual ~Timer();
  20594. /** The user-defined callback routine that actually gets called periodically.
  20595. It's perfectly ok to call startTimer() or stopTimer() from within this
  20596. callback to change the subsequent intervals.
  20597. */
  20598. virtual void timerCallback() = 0;
  20599. /** Starts the timer and sets the length of interval required.
  20600. If the timer is already started, this will reset it, so the
  20601. time between calling this method and the next timer callback
  20602. will not be less than the interval length passed in.
  20603. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  20604. rounded up to 1)
  20605. */
  20606. void startTimer (int intervalInMilliseconds) throw();
  20607. /** Stops the timer.
  20608. No more callbacks will be made after this method returns.
  20609. If this is called from a different thread, any callbacks that may
  20610. be currently executing may be allowed to finish before the method
  20611. returns.
  20612. */
  20613. void stopTimer() throw();
  20614. /** Checks if the timer has been started.
  20615. @returns true if the timer is running.
  20616. */
  20617. bool isTimerRunning() const throw() { return periodMs > 0; }
  20618. /** Returns the timer's interval.
  20619. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  20620. */
  20621. int getTimerInterval() const throw() { return periodMs; }
  20622. private:
  20623. friend class InternalTimerThread;
  20624. int countdownMs, periodMs;
  20625. Timer* previous;
  20626. Timer* next;
  20627. Timer& operator= (const Timer&);
  20628. };
  20629. #endif // __JUCE_TIMER_JUCEHEADER__
  20630. /*** End of inlined file: juce_Timer.h ***/
  20631. class MouseInputSource;
  20632. class MouseInputSourceInternal;
  20633. class MouseListener;
  20634. /**
  20635. Classes can implement this interface and register themselves with the Desktop class
  20636. to receive callbacks when the currently focused component changes.
  20637. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  20638. */
  20639. class JUCE_API FocusChangeListener
  20640. {
  20641. public:
  20642. /** Destructor. */
  20643. virtual ~FocusChangeListener() {}
  20644. /** Callback to indicate that the currently focused component has changed. */
  20645. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  20646. };
  20647. /**
  20648. Describes and controls aspects of the computer's desktop.
  20649. */
  20650. class JUCE_API Desktop : private DeletedAtShutdown,
  20651. private Timer,
  20652. private AsyncUpdater
  20653. {
  20654. public:
  20655. /** There's only one dektop object, and this method will return it.
  20656. */
  20657. static Desktop& JUCE_CALLTYPE getInstance();
  20658. /** Returns a list of the positions of all the monitors available.
  20659. The first rectangle in the list will be the main monitor area.
  20660. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  20661. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  20662. */
  20663. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  20664. /** Returns the position and size of the main monitor.
  20665. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  20666. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  20667. */
  20668. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  20669. /** Returns the position and size of the monitor which contains this co-ordinate.
  20670. If none of the monitors contains the point, this will just return the
  20671. main monitor.
  20672. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  20673. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  20674. */
  20675. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  20676. /** Returns the mouse position.
  20677. The co-ordinates are relative to the top-left of the main monitor.
  20678. */
  20679. static const Point<int> getMousePosition();
  20680. /** Makes the mouse pointer jump to a given location.
  20681. The co-ordinates are relative to the top-left of the main monitor.
  20682. */
  20683. static void setMousePosition (const Point<int>& newPosition);
  20684. /** Returns the last position at which a mouse button was pressed.
  20685. */
  20686. static const Point<int> getLastMouseDownPosition() throw();
  20687. /** Returns the number of times the mouse button has been clicked since the
  20688. app started.
  20689. Each mouse-down event increments this number by 1.
  20690. */
  20691. static int getMouseButtonClickCounter() throw();
  20692. /** This lets you prevent the screensaver from becoming active.
  20693. Handy if you're running some sort of presentation app where having a screensaver
  20694. appear would be annoying.
  20695. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  20696. won't enable a screensaver unless the user has actually set one up).
  20697. The disablement will only happen while the Juce application is the foreground
  20698. process - if another task is running in front of it, then the screensaver will
  20699. be unaffected.
  20700. @see isScreenSaverEnabled
  20701. */
  20702. static void setScreenSaverEnabled (bool isEnabled);
  20703. /** Returns true if the screensaver has not been turned off.
  20704. This will return the last value passed into setScreenSaverEnabled(). Note that
  20705. it won't tell you whether the user is actually using a screen saver, just
  20706. whether this app is deliberately preventing one from running.
  20707. @see setScreenSaverEnabled
  20708. */
  20709. static bool isScreenSaverEnabled();
  20710. /** Registers a MouseListener that will receive all mouse events that occur on
  20711. any component.
  20712. @see removeGlobalMouseListener
  20713. */
  20714. void addGlobalMouseListener (MouseListener* listener);
  20715. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  20716. method.
  20717. @see addGlobalMouseListener
  20718. */
  20719. void removeGlobalMouseListener (MouseListener* listener);
  20720. /** Registers a MouseListener that will receive a callback whenever the focused
  20721. component changes.
  20722. */
  20723. void addFocusChangeListener (FocusChangeListener* listener);
  20724. /** Unregisters a listener that was added with addFocusChangeListener(). */
  20725. void removeFocusChangeListener (FocusChangeListener* listener);
  20726. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  20727. The component must already be on the desktop for this method to work. It will
  20728. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  20729. etc will be hidden.
  20730. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  20731. the component that's currently being used will be resized back to the size
  20732. and position it was in before being put into this mode.
  20733. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  20734. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  20735. to hide as much on-screen paraphenalia as possible.
  20736. */
  20737. void setKioskModeComponent (Component* componentToUse,
  20738. bool allowMenusAndBars = true);
  20739. /** Returns the component that is currently being used in kiosk-mode.
  20740. This is the component that was last set by setKioskModeComponent(). If none
  20741. has been set, this returns 0.
  20742. */
  20743. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  20744. /** Returns the number of components that are currently active as top-level
  20745. desktop windows.
  20746. @see getComponent, Component::addToDesktop
  20747. */
  20748. int getNumComponents() const throw();
  20749. /** Returns one of the top-level desktop window components.
  20750. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  20751. index is out-of-range.
  20752. @see getNumComponents, Component::addToDesktop
  20753. */
  20754. Component* getComponent (int index) const throw();
  20755. /** Finds the component at a given screen location.
  20756. This will drill down into top-level windows to find the child component at
  20757. the given position.
  20758. Returns 0 if the co-ordinates are inside a non-Juce window.
  20759. */
  20760. Component* findComponentAt (const Point<int>& screenPosition) const;
  20761. /** Returns the number of MouseInputSource objects the system has at its disposal.
  20762. In a traditional single-mouse system, there might be only one object. On a multi-touch
  20763. system, there could be one input source per potential finger.
  20764. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  20765. @see getMouseSource
  20766. */
  20767. int getNumMouseSources() const throw() { return mouseSources.size(); }
  20768. /** Returns one of the system's MouseInputSource objects.
  20769. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  20770. a null pointer.
  20771. In a traditional single-mouse system, there might be only one object. On a multi-touch
  20772. system, there could be one input source per potential finger.
  20773. */
  20774. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  20775. /** Returns the main mouse input device that the system is using.
  20776. @see getNumMouseSources()
  20777. */
  20778. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  20779. /** Returns the number of mouse-sources that are currently being dragged.
  20780. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  20781. juce component has the button down on it. In a multi-touch system, this could
  20782. be any number from 0 to the number of simultaneous touches that can be detected.
  20783. */
  20784. int getNumDraggingMouseSources() const throw();
  20785. /** Returns one of the mouse sources that's currently being dragged.
  20786. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  20787. out of range, or if no mice or fingers are down, this will return a null pointer.
  20788. */
  20789. MouseInputSource* getDraggingMouseSource (int index) const throw();
  20790. juce_UseDebuggingNewOperator
  20791. /** Tells this object to refresh its idea of what the screen resolution is.
  20792. (Called internally by the native code).
  20793. */
  20794. void refreshMonitorSizes();
  20795. /** True if the OS supports semitransparent windows */
  20796. static bool canUseSemiTransparentWindows() throw();
  20797. private:
  20798. static Desktop* instance;
  20799. friend class Component;
  20800. friend class ComponentPeer;
  20801. friend class MouseInputSource;
  20802. friend class MouseInputSourceInternal;
  20803. friend class DeletedAtShutdown;
  20804. friend class TopLevelWindowManager;
  20805. OwnedArray <MouseInputSource> mouseSources;
  20806. void createMouseInputSources();
  20807. ListenerList <MouseListener> mouseListeners;
  20808. ListenerList <FocusChangeListener> focusListeners;
  20809. Array <Component*> desktopComponents;
  20810. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  20811. Point<int> lastFakeMouseMove;
  20812. void sendMouseMove();
  20813. int mouseClickCounter;
  20814. void incrementMouseClickCounter() throw();
  20815. Component* kioskModeComponent;
  20816. Rectangle<int> kioskComponentOriginalBounds;
  20817. void timerCallback();
  20818. void resetTimer();
  20819. int getNumDisplayMonitors() const throw();
  20820. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  20821. void addDesktopComponent (Component* c);
  20822. void removeDesktopComponent (Component* c);
  20823. void componentBroughtToFront (Component* c);
  20824. void triggerFocusCallback();
  20825. void handleAsyncUpdate();
  20826. Desktop();
  20827. ~Desktop();
  20828. Desktop (const Desktop&);
  20829. Desktop& operator= (const Desktop&);
  20830. };
  20831. #endif // __JUCE_DESKTOP_JUCEHEADER__
  20832. /*** End of inlined file: juce_Desktop.h ***/
  20833. class KeyPressMappingSet;
  20834. class ApplicationCommandManagerListener;
  20835. /**
  20836. One of these objects holds a list of all the commands your app can perform,
  20837. and despatches these commands when needed.
  20838. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  20839. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  20840. to invoke automatically, which means you don't have to handle the result of a menu
  20841. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  20842. which can choose which events they want to handle.
  20843. This architecture also allows for nested ApplicationCommandTargets, so that for example
  20844. you could have two different objects, one inside the other, both of which can respond to
  20845. a "delete" command. Depending on which one has focus, the command will be sent to the
  20846. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  20847. method.
  20848. To set up your app to use commands, you'll need to do the following:
  20849. - Create a global ApplicationCommandManager to hold the list of all possible
  20850. commands. (This will also manage a set of key-mappings for them).
  20851. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  20852. This allows the object to provide a list of commands that it can perform, and
  20853. to handle them.
  20854. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  20855. or ApplicationCommandManager::registerCommand().
  20856. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  20857. method to access the key-mapper object, which you will need to register as a key-listener
  20858. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  20859. about setting this up.
  20860. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  20861. cause these commands to be invoked automatically.
  20862. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  20863. When a command is invoked, the ApplicationCommandManager will try to choose the best
  20864. ApplicationCommandTarget to receive the specified command. To do this it will use the
  20865. current keyboard focus to see which component might be interested, and will search the
  20866. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  20867. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  20868. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  20869. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  20870. point if the command still hasn't been performed, it will be passed to the current
  20871. JUCEApplication object (which is itself an ApplicationCommandTarget).
  20872. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  20873. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  20874. the object yourself.
  20875. @see ApplicationCommandTarget, ApplicationCommandInfo
  20876. */
  20877. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  20878. private FocusChangeListener
  20879. {
  20880. public:
  20881. /** Creates an ApplicationCommandManager.
  20882. Once created, you'll need to register all your app's commands with it, using
  20883. ApplicationCommandManager::registerAllCommandsForTarget() or
  20884. ApplicationCommandManager::registerCommand().
  20885. */
  20886. ApplicationCommandManager();
  20887. /** Destructor.
  20888. Make sure that you don't delete this if pointers to it are still being used by
  20889. objects such as PopupMenus or Buttons.
  20890. */
  20891. virtual ~ApplicationCommandManager();
  20892. /** Clears the current list of all commands.
  20893. Note that this will also clear the contents of the KeyPressMappingSet.
  20894. */
  20895. void clearCommands();
  20896. /** Adds a command to the list of registered commands.
  20897. @see registerAllCommandsForTarget
  20898. */
  20899. void registerCommand (const ApplicationCommandInfo& newCommand);
  20900. /** Adds all the commands that this target publishes to the manager's list.
  20901. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  20902. to get details about all the commands that this target can do, and will call
  20903. registerCommand() to add each one to the manger's list.
  20904. @see registerCommand
  20905. */
  20906. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  20907. /** Removes the command with a specified ID.
  20908. Note that this will also remove any key mappings that are mapped to the command.
  20909. */
  20910. void removeCommand (CommandID commandID);
  20911. /** This should be called to tell the manager that one of its registered commands may have changed
  20912. its active status.
  20913. Because the command manager only finds out whether a command is active or inactive by querying
  20914. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  20915. allows things like buttons to update their enablement, etc.
  20916. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  20917. for any registered listeners.
  20918. */
  20919. void commandStatusChanged();
  20920. /** Returns the number of commands that have been registered.
  20921. @see registerCommand
  20922. */
  20923. int getNumCommands() const throw() { return commands.size(); }
  20924. /** Returns the details about one of the registered commands.
  20925. The index is between 0 and (getNumCommands() - 1).
  20926. */
  20927. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  20928. /** Returns the details about a given command ID.
  20929. This will search the list of registered commands for one with the given command
  20930. ID number, and return its associated info. If no matching command is found, this
  20931. will return 0.
  20932. */
  20933. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  20934. /** Returns the name field for a command.
  20935. An empty string is returned if no command with this ID has been registered.
  20936. @see getDescriptionOfCommand
  20937. */
  20938. const String getNameOfCommand (CommandID commandID) const throw();
  20939. /** Returns the description field for a command.
  20940. An empty string is returned if no command with this ID has been registered. If the
  20941. command has no description, this will return its short name field instead.
  20942. @see getNameOfCommand
  20943. */
  20944. const String getDescriptionOfCommand (CommandID commandID) const throw();
  20945. /** Returns the list of categories.
  20946. This will go through all registered commands, and return a list of all the distict
  20947. categoryName values from their ApplicationCommandInfo structure.
  20948. @see getCommandsInCategory()
  20949. */
  20950. const StringArray getCommandCategories() const throw();
  20951. /** Returns a list of all the command UIDs in a particular category.
  20952. @see getCommandCategories()
  20953. */
  20954. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  20955. /** Returns the manager's internal set of key mappings.
  20956. This object can be used to edit the keypresses. To actually link this object up
  20957. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  20958. class.
  20959. @see KeyPressMappingSet
  20960. */
  20961. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  20962. /** Invokes the given command directly, sending it to the default target.
  20963. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  20964. structure.
  20965. */
  20966. bool invokeDirectly (CommandID commandID, bool asynchronously);
  20967. /** Sends a command to the default target.
  20968. This will choose a target using getFirstCommandTarget(), and send the specified command
  20969. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  20970. first target can't handle the command, it will be passed on to targets further down the
  20971. chain (see ApplicationCommandTarget::invoke() for more info).
  20972. @param invocationInfo this must be correctly filled-in, describing the context for
  20973. the invocation.
  20974. @param asynchronously if false, the command will be performed before this method returns.
  20975. If true, a message will be posted so that the command will be performed
  20976. later on the message thread, and this method will return immediately.
  20977. @see ApplicationCommandTarget::invoke
  20978. */
  20979. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  20980. bool asynchronously);
  20981. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  20982. Whenever the manager needs to know which target a command should be sent to, it calls
  20983. this method to determine the first one to try.
  20984. By default, this method will return the target that was set by calling setFirstCommandTarget().
  20985. If no target is set, it will return the result of findDefaultComponentTarget().
  20986. If you need to make sure all commands go via your own custom target, then you can
  20987. either use setFirstCommandTarget() to specify a single target, or override this method
  20988. if you need more complex logic to choose one.
  20989. It may return 0 if no targets are available.
  20990. @see getTargetForCommand, invoke, invokeDirectly
  20991. */
  20992. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  20993. /** Sets a target to be returned by getFirstCommandTarget().
  20994. If this is set to 0, then getFirstCommandTarget() will by default return the
  20995. result of findDefaultComponentTarget().
  20996. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  20997. deleting the target object.
  20998. */
  20999. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  21000. /** Tries to find the best target to use to perform a given command.
  21001. This will call getFirstCommandTarget() to find the preferred target, and will
  21002. check whether that target can handle the given command. If it can't, then it'll use
  21003. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  21004. so on until no more are available.
  21005. If no targets are found that can perform the command, this method will return 0.
  21006. If a target is found, then it will get the target to fill-in the upToDateInfo
  21007. structure with the latest info about that command, so that the caller can see
  21008. whether the command is disabled, ticked, etc.
  21009. */
  21010. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  21011. ApplicationCommandInfo& upToDateInfo);
  21012. /** Registers a listener that will be called when various events occur. */
  21013. void addListener (ApplicationCommandManagerListener* listener) throw();
  21014. /** Deregisters a previously-added listener. */
  21015. void removeListener (ApplicationCommandManagerListener* listener) throw();
  21016. /** Looks for a suitable command target based on which Components have the keyboard focus.
  21017. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  21018. but is exposed here in case it's useful.
  21019. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  21020. windows, etc., and using the findTargetForComponent() method.
  21021. */
  21022. static ApplicationCommandTarget* findDefaultComponentTarget();
  21023. /** Examines this component and all its parents in turn, looking for the first one
  21024. which is a ApplicationCommandTarget.
  21025. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  21026. that class.
  21027. */
  21028. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  21029. juce_UseDebuggingNewOperator
  21030. private:
  21031. OwnedArray <ApplicationCommandInfo> commands;
  21032. ListenerList <ApplicationCommandManagerListener> listeners;
  21033. ScopedPointer <KeyPressMappingSet> keyMappings;
  21034. ApplicationCommandTarget* firstTarget;
  21035. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  21036. void handleAsyncUpdate();
  21037. void globalFocusChanged (Component*);
  21038. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  21039. // version of this method.
  21040. virtual short getFirstCommandTarget() { return 0; }
  21041. ApplicationCommandManager (const ApplicationCommandManager&);
  21042. ApplicationCommandManager& operator= (const ApplicationCommandManager&);
  21043. };
  21044. /**
  21045. A listener that receives callbacks from an ApplicationCommandManager when
  21046. commands are invoked or the command list is changed.
  21047. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  21048. */
  21049. class JUCE_API ApplicationCommandManagerListener
  21050. {
  21051. public:
  21052. /** Destructor. */
  21053. virtual ~ApplicationCommandManagerListener() {}
  21054. /** Called when an app command is about to be invoked. */
  21055. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  21056. /** Called when commands are registered or deregistered from the
  21057. command manager, or when commands are made active or inactive.
  21058. Note that if you're using this to watch for changes to whether a command is disabled,
  21059. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  21060. whenever the status of your command might have changed.
  21061. */
  21062. virtual void applicationCommandListChanged() = 0;
  21063. };
  21064. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21065. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  21066. #endif
  21067. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  21068. #endif
  21069. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21070. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  21071. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21072. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21073. /*** Start of inlined file: juce_PropertiesFile.h ***/
  21074. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  21075. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  21076. /** Wrapper on a file that stores a list of key/value data pairs.
  21077. Useful for storing application settings, etc. See the PropertySet class for
  21078. the interfaces that read and write values.
  21079. Not designed for very large amounts of data, as it keeps all the values in
  21080. memory and writes them out to disk lazily when they are changed.
  21081. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  21082. with it, and these will be signalled when a value changes.
  21083. @see PropertySet
  21084. */
  21085. class JUCE_API PropertiesFile : public PropertySet,
  21086. public ChangeBroadcaster,
  21087. private Timer
  21088. {
  21089. public:
  21090. enum FileFormatOptions
  21091. {
  21092. ignoreCaseOfKeyNames = 1,
  21093. storeAsBinary = 2,
  21094. storeAsCompressedBinary = 4,
  21095. storeAsXML = 8
  21096. };
  21097. /**
  21098. Creates a PropertiesFile object.
  21099. @param file the file to use
  21100. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  21101. is changed, the object will wait for this amount
  21102. of time and then save the file. If zero, the file
  21103. will be written to disk immediately on being changed
  21104. (which might be slow, as it'll re-write synchronously
  21105. each time a value-change method is called). If it is
  21106. less than zero, the file won't be saved until
  21107. save() or saveIfNeeded() are explicitly called.
  21108. @param optionFlags a combination of the flags in the FileFormatOptions
  21109. enum, which specify the type of file to save, and other
  21110. options.
  21111. @param processLock an optional InterprocessLock object that will be used to
  21112. prevent multiple threads or processes from writing to the file
  21113. at the same time. The PropertiesFile will keep a pointer to
  21114. this object but will not take ownership of it - the caller is
  21115. responsible for making sure that the lock doesn't get deleted
  21116. before the PropertiesFile has been deleted.
  21117. */
  21118. PropertiesFile (const File& file,
  21119. int millisecondsBeforeSaving,
  21120. int optionFlags,
  21121. InterProcessLock* processLock = 0);
  21122. /** Destructor.
  21123. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  21124. */
  21125. ~PropertiesFile();
  21126. /** Returns true if this file was created from a valid (or non-existent) file.
  21127. If the file failed to load correctly because it was corrupt or had insufficient
  21128. access, this will be false.
  21129. */
  21130. bool isValidFile() const throw() { return loadedOk; }
  21131. /** This will flush all the values to disk if they've changed since the last
  21132. time they were saved.
  21133. Returns false if it fails to write to the file for some reason (maybe because
  21134. it's read-only or the directory doesn't exist or something).
  21135. @see save
  21136. */
  21137. bool saveIfNeeded();
  21138. /** This will force a write-to-disk of the current values, regardless of whether
  21139. anything has changed since the last save.
  21140. Returns false if it fails to write to the file for some reason (maybe because
  21141. it's read-only or the directory doesn't exist or something).
  21142. @see saveIfNeeded
  21143. */
  21144. bool save();
  21145. /** Returns true if the properties have been altered since the last time they were saved.
  21146. The file is flagged as needing to be saved when you change a value, but you can
  21147. explicitly set this flag with setNeedsToBeSaved().
  21148. */
  21149. bool needsToBeSaved() const;
  21150. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  21151. @see needsToBeSaved
  21152. */
  21153. void setNeedsToBeSaved (bool needsToBeSaved);
  21154. /** Returns the file that's being used. */
  21155. const File getFile() const { return file; }
  21156. /** Handy utility to create a properties file in whatever the standard OS-specific
  21157. location is for these things.
  21158. This uses getDefaultAppSettingsFile() to decide what file to create, then
  21159. creates a PropertiesFile object with the specified properties. See
  21160. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  21161. what the parameters do.
  21162. @see getDefaultAppSettingsFile
  21163. */
  21164. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  21165. const String& fileNameSuffix,
  21166. const String& folderName,
  21167. bool commonToAllUsers,
  21168. int millisecondsBeforeSaving,
  21169. int propertiesFileOptions,
  21170. InterProcessLock* processLock = 0);
  21171. /** Handy utility to choose a file in the standard OS-dependent location for application
  21172. settings files.
  21173. So on a Mac, this will return a file called:
  21174. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  21175. On Windows it'll return something like:
  21176. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  21177. On Linux it'll return
  21178. ~/.[folderName]/[applicationName].[fileNameSuffix]
  21179. If you pass an empty string as the folder name, it'll use the app name for this (or
  21180. omit the folder name on the Mac).
  21181. If commonToAllUsers is true, then this will return the same file for all users of the
  21182. computer, regardless of the current user. If it is false, the file will be specific to
  21183. only the current user. Use this to choose whether you're saving settings that are common
  21184. or user-specific.
  21185. */
  21186. static const File getDefaultAppSettingsFile (const String& applicationName,
  21187. const String& fileNameSuffix,
  21188. const String& folderName,
  21189. bool commonToAllUsers);
  21190. juce_UseDebuggingNewOperator
  21191. protected:
  21192. virtual void propertyChanged();
  21193. private:
  21194. File file;
  21195. int timerInterval;
  21196. const int options;
  21197. bool loadedOk, needsWriting;
  21198. InterProcessLock* processLock;
  21199. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  21200. InterProcessLock::ScopedLockType* createProcessLock() const;
  21201. void timerCallback();
  21202. PropertiesFile (const PropertiesFile&);
  21203. PropertiesFile& operator= (const PropertiesFile&);
  21204. };
  21205. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  21206. /*** End of inlined file: juce_PropertiesFile.h ***/
  21207. /**
  21208. Manages a collection of properties.
  21209. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  21210. as a singleton.
  21211. It holds two different PropertiesFile objects internally, one for user-specific
  21212. settings (stored in your user directory), and one for settings that are common to
  21213. all users (stored in a folder accessible to all users).
  21214. The class manages the creation of these files on-demand, allowing access via the
  21215. getUserSettings() and getCommonSettings() methods. It also has a few handy
  21216. methods like testWriteAccess() to check that the files can be saved.
  21217. If you're using one of these as a singleton, then your app's start-up code should
  21218. first of all call setStorageParameters() to tell it the parameters to use to create
  21219. the properties files.
  21220. @see PropertiesFile
  21221. */
  21222. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  21223. {
  21224. public:
  21225. /**
  21226. Creates an ApplicationProperties object.
  21227. Before using it, you must call setStorageParameters() to give it the info
  21228. it needs to create the property files.
  21229. */
  21230. ApplicationProperties() throw();
  21231. /** Destructor.
  21232. */
  21233. ~ApplicationProperties();
  21234. juce_DeclareSingleton (ApplicationProperties, false)
  21235. /** Gives the object the information it needs to create the appropriate properties files.
  21236. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  21237. info about how these parameters are used.
  21238. */
  21239. void setStorageParameters (const String& applicationName,
  21240. const String& fileNameSuffix,
  21241. const String& folderName,
  21242. int millisecondsBeforeSaving,
  21243. int propertiesFileOptions) throw();
  21244. /** Tests whether the files can be successfully written to, and can show
  21245. an error message if not.
  21246. Returns true if none of the tests fail.
  21247. @param testUserSettings if true, the user settings file will be tested
  21248. @param testCommonSettings if true, the common settings file will be tested
  21249. @param showWarningDialogOnFailure if true, the method will show a helpful error
  21250. message box if either of the tests fail
  21251. */
  21252. bool testWriteAccess (bool testUserSettings,
  21253. bool testCommonSettings,
  21254. bool showWarningDialogOnFailure);
  21255. /** Returns the user settings file.
  21256. The first time this is called, it will create and load the properties file.
  21257. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  21258. the common settings are used as a second-chance place to look. This is done via the
  21259. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  21260. to the fallback for the user settings.
  21261. @see getCommonSettings
  21262. */
  21263. PropertiesFile* getUserSettings() throw();
  21264. /** Returns the common settings file.
  21265. The first time this is called, it will create and load the properties file.
  21266. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  21267. read-only (e.g. because the user doesn't have permission to write
  21268. to shared files), then this will return the user settings instead,
  21269. (like getUserSettings() would do). This is handy if you'd like to
  21270. write a value to the common settings, but if that's no possible,
  21271. then you'd rather write to the user settings than none at all.
  21272. If returnUserPropsIfReadOnly is false, this method will always return
  21273. the common settings, even if any changes to them can't be saved.
  21274. @see getUserSettings
  21275. */
  21276. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly) throw();
  21277. /** Saves both files if they need to be saved.
  21278. @see PropertiesFile::saveIfNeeded
  21279. */
  21280. bool saveIfNeeded();
  21281. /** Flushes and closes both files if they are open.
  21282. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  21283. and closes both files. They will then be re-opened the next time getUserSettings()
  21284. or getCommonSettings() is called.
  21285. */
  21286. void closeFiles();
  21287. juce_UseDebuggingNewOperator
  21288. private:
  21289. ScopedPointer <PropertiesFile> userProps, commonProps;
  21290. String appName, fileSuffix, folderName;
  21291. int msBeforeSaving, options;
  21292. int commonSettingsAreReadOnly;
  21293. ApplicationProperties (const ApplicationProperties&);
  21294. ApplicationProperties& operator= (const ApplicationProperties&);
  21295. void openFiles() throw();
  21296. };
  21297. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21298. /*** End of inlined file: juce_ApplicationProperties.h ***/
  21299. #endif
  21300. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21301. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  21302. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21303. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  21304. /*** Start of inlined file: juce_AudioFormat.h ***/
  21305. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  21306. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  21307. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  21308. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21309. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21310. class AudioFormat;
  21311. /**
  21312. Reads samples from an audio file stream.
  21313. A subclass that reads a specific type of audio format will be created by
  21314. an AudioFormat object.
  21315. @see AudioFormat, AudioFormatWriter
  21316. */
  21317. class JUCE_API AudioFormatReader
  21318. {
  21319. protected:
  21320. /** Creates an AudioFormatReader object.
  21321. @param sourceStream the stream to read from - this will be deleted
  21322. by this object when it is no longer needed. (Some
  21323. specialised readers might not use this parameter and
  21324. can leave it as 0).
  21325. @param formatName the description that will be returned by the getFormatName()
  21326. method
  21327. */
  21328. AudioFormatReader (InputStream* sourceStream,
  21329. const String& formatName);
  21330. public:
  21331. /** Destructor. */
  21332. virtual ~AudioFormatReader();
  21333. /** Returns a description of what type of format this is.
  21334. E.g. "AIFF"
  21335. */
  21336. const String getFormatName() const throw() { return formatName; }
  21337. /** Reads samples from the stream.
  21338. @param destSamples an array of buffers into which the sample data for each
  21339. channel will be written.
  21340. If the format is fixed-point, each channel will be written
  21341. as an array of 32-bit signed integers using the full
  21342. range -0x80000000 to 0x7fffffff, regardless of the source's
  21343. bit-depth. If it is a floating-point format, you should cast
  21344. the resulting array to a (float**) to get the values (in the
  21345. range -1.0 to 1.0 or beyond)
  21346. If the format is stereo, then destSamples[0] is the left channel
  21347. data, and destSamples[1] is the right channel.
  21348. The numDestChannels parameter indicates how many pointers this array
  21349. contains, but some of these pointers can be null if you don't want to
  21350. read data for some of the channels
  21351. @param numDestChannels the number of array elements in the destChannels array
  21352. @param startSampleInSource the position in the audio file or stream at which the samples
  21353. should be read, as a number of samples from the start of the
  21354. stream. It's ok for this to be beyond the start or end of the
  21355. available data - any samples that are out-of-range will be returned
  21356. as zeros.
  21357. @param numSamplesToRead the number of samples to read. If this is greater than the number
  21358. of samples that the file or stream contains. the result will be padded
  21359. with zeros
  21360. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  21361. for some of the channels that you pass in, then they should be filled with
  21362. copies of valid source channels.
  21363. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  21364. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  21365. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  21366. was false, then only the first channel would be filled with the file's contents, and
  21367. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  21368. from a stereo file, then the last 3 would all end up with copies of the same data.
  21369. @returns true if the operation succeeded, false if there was an error. Note
  21370. that reading sections of data beyond the extent of the stream isn't an
  21371. error - the reader should just return zeros for these regions
  21372. @see readMaxLevels
  21373. */
  21374. bool read (int** destSamples,
  21375. int numDestChannels,
  21376. int64 startSampleInSource,
  21377. int numSamplesToRead,
  21378. bool fillLeftoverChannelsWithCopies);
  21379. /** Finds the highest and lowest sample levels from a section of the audio stream.
  21380. This will read a block of samples from the stream, and measure the
  21381. highest and lowest sample levels from the channels in that section, returning
  21382. these as normalised floating-point levels.
  21383. @param startSample the offset into the audio stream to start reading from. It's
  21384. ok for this to be beyond the start or end of the stream.
  21385. @param numSamples how many samples to read
  21386. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  21387. @param highestLeft on return, this is the highest absolute sample from the left channel
  21388. @param lowestRight on return, this is the lowest absolute sample from the right
  21389. channel (if there is one)
  21390. @param highestRight on return, this is the highest absolute sample from the right
  21391. channel (if there is one)
  21392. @see read
  21393. */
  21394. virtual void readMaxLevels (int64 startSample,
  21395. int64 numSamples,
  21396. float& lowestLeft,
  21397. float& highestLeft,
  21398. float& lowestRight,
  21399. float& highestRight);
  21400. /** Scans the source looking for a sample whose magnitude is in a specified range.
  21401. This will read from the source, either forwards or backwards between two sample
  21402. positions, until it finds a sample whose magnitude lies between two specified levels.
  21403. If it finds a suitable sample, it returns its position; if not, it will return -1.
  21404. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  21405. points when you're searching for a continuous range of samples
  21406. @param startSample the first sample to look at
  21407. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  21408. the search will go backwards
  21409. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  21410. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  21411. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  21412. of this many consecutive samples, all of which lie
  21413. within the target range. When it finds such a sequence,
  21414. it returns the position of the first in-range sample
  21415. it found (i.e. the earliest one if scanning forwards, the
  21416. latest one if scanning backwards)
  21417. */
  21418. int64 searchForLevel (int64 startSample,
  21419. int64 numSamplesToSearch,
  21420. double magnitudeRangeMinimum,
  21421. double magnitudeRangeMaximum,
  21422. int minimumConsecutiveSamples);
  21423. /** The sample-rate of the stream. */
  21424. double sampleRate;
  21425. /** The number of bits per sample, e.g. 16, 24, 32. */
  21426. unsigned int bitsPerSample;
  21427. /** The total number of samples in the audio stream. */
  21428. int64 lengthInSamples;
  21429. /** The total number of channels in the audio stream. */
  21430. unsigned int numChannels;
  21431. /** Indicates whether the data is floating-point or fixed. */
  21432. bool usesFloatingPointData;
  21433. /** A set of metadata values that the reader has pulled out of the stream.
  21434. Exactly what these values are depends on the format, so you can
  21435. check out the format implementation code to see what kind of stuff
  21436. they understand.
  21437. */
  21438. StringPairArray metadataValues;
  21439. /** The input stream, for use by subclasses. */
  21440. InputStream* input;
  21441. /** Subclasses must implement this method to perform the low-level read operation.
  21442. Callers should use read() instead of calling this directly.
  21443. @param destSamples the array of destination buffers to fill. Some of these
  21444. pointers may be null
  21445. @param numDestChannels the number of items in the destSamples array. This
  21446. value is guaranteed not to be greater than the number of
  21447. channels that this reader object contains
  21448. @param startOffsetInDestBuffer the number of samples from the start of the
  21449. dest data at which to begin writing
  21450. @param startSampleInFile the number of samples into the source data at which
  21451. to begin reading. This value is guaranteed to be >= 0.
  21452. @param numSamples the number of samples to read
  21453. */
  21454. virtual bool readSamples (int** destSamples,
  21455. int numDestChannels,
  21456. int startOffsetInDestBuffer,
  21457. int64 startSampleInFile,
  21458. int numSamples) = 0;
  21459. juce_UseDebuggingNewOperator
  21460. private:
  21461. String formatName;
  21462. AudioFormatReader (const AudioFormatReader&);
  21463. AudioFormatReader& operator= (const AudioFormatReader&);
  21464. };
  21465. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  21466. /*** End of inlined file: juce_AudioFormatReader.h ***/
  21467. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  21468. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21469. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21470. /*** Start of inlined file: juce_AudioSource.h ***/
  21471. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  21472. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  21473. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  21474. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21475. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21476. class AudioFormatReader;
  21477. class AudioFormatWriter;
  21478. /**
  21479. A multi-channel buffer of 32-bit floating point audio samples.
  21480. */
  21481. class JUCE_API AudioSampleBuffer
  21482. {
  21483. public:
  21484. /** Creates a buffer with a specified number of channels and samples.
  21485. The contents of the buffer will initially be undefined, so use clear() to
  21486. set all the samples to zero.
  21487. The buffer will allocate its memory internally, and this will be released
  21488. when the buffer is deleted.
  21489. */
  21490. AudioSampleBuffer (int numChannels,
  21491. int numSamples) throw();
  21492. /** Creates a buffer using a pre-allocated block of memory.
  21493. Note that if the buffer is resized or its number of channels is changed, it
  21494. will re-allocate memory internally and copy the existing data to this new area,
  21495. so it will then stop directly addressing this memory.
  21496. @param dataToReferTo a pre-allocated array containing pointers to the data
  21497. for each channel that should be used by this buffer. The
  21498. buffer will only refer to this memory, it won't try to delete
  21499. it when the buffer is deleted or resized.
  21500. @param numChannels the number of channels to use - this must correspond to the
  21501. number of elements in the array passed in
  21502. @param numSamples the number of samples to use - this must correspond to the
  21503. size of the arrays passed in
  21504. */
  21505. AudioSampleBuffer (float** dataToReferTo,
  21506. int numChannels,
  21507. int numSamples) throw();
  21508. /** Copies another buffer.
  21509. This buffer will make its own copy of the other's data, unless the buffer was created
  21510. using an external data buffer, in which case boths buffers will just point to the same
  21511. shared block of data.
  21512. */
  21513. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  21514. /** Copies another buffer onto this one.
  21515. This buffer's size will be changed to that of the other buffer.
  21516. */
  21517. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  21518. /** Destructor.
  21519. This will free any memory allocated by the buffer.
  21520. */
  21521. virtual ~AudioSampleBuffer() throw();
  21522. /** Returns the number of channels of audio data that this buffer contains.
  21523. @see getSampleData
  21524. */
  21525. int getNumChannels() const throw() { return numChannels; }
  21526. /** Returns the number of samples allocated in each of the buffer's channels.
  21527. @see getSampleData
  21528. */
  21529. int getNumSamples() const throw() { return size; }
  21530. /** Returns a pointer one of the buffer's channels.
  21531. For speed, this doesn't check whether the channel number is out of range,
  21532. so be careful when using it!
  21533. */
  21534. float* getSampleData (const int channelNumber) const throw()
  21535. {
  21536. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  21537. return channels [channelNumber];
  21538. }
  21539. /** Returns a pointer to a sample in one of the buffer's channels.
  21540. For speed, this doesn't check whether the channel and sample number
  21541. are out-of-range, so be careful when using it!
  21542. */
  21543. float* getSampleData (const int channelNumber,
  21544. const int sampleOffset) const throw()
  21545. {
  21546. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  21547. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  21548. return channels [channelNumber] + sampleOffset;
  21549. }
  21550. /** Returns an array of pointers to the channels in the buffer.
  21551. Don't modify any of the pointers that are returned, and bear in mind that
  21552. these will become invalid if the buffer is resized.
  21553. */
  21554. float** getArrayOfChannels() const throw() { return channels; }
  21555. /** Chages the buffer's size or number of channels.
  21556. This can expand or contract the buffer's length, and add or remove channels.
  21557. If keepExistingContent is true, it will try to preserve as much of the
  21558. old data as it can in the new buffer.
  21559. If clearExtraSpace is true, then any extra channels or space that is
  21560. allocated will be also be cleared. If false, then this space is left
  21561. uninitialised.
  21562. If avoidReallocating is true, then changing the buffer's size won't reduce the
  21563. amount of memory that is currently allocated (but it will still increase it if
  21564. the new size is bigger than the amount it currently has). If this is false, then
  21565. a new allocation will be done so that the buffer uses takes up the minimum amount
  21566. of memory that it needs.
  21567. */
  21568. void setSize (int newNumChannels,
  21569. int newNumSamples,
  21570. bool keepExistingContent = false,
  21571. bool clearExtraSpace = false,
  21572. bool avoidReallocating = false) throw();
  21573. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  21574. There's also a constructor that lets you specify arrays like this, but this
  21575. lets you change the channels dynamically.
  21576. Note that if the buffer is resized or its number of channels is changed, it
  21577. will re-allocate memory internally and copy the existing data to this new area,
  21578. so it will then stop directly addressing this memory.
  21579. @param dataToReferTo a pre-allocated array containing pointers to the data
  21580. for each channel that should be used by this buffer. The
  21581. buffer will only refer to this memory, it won't try to delete
  21582. it when the buffer is deleted or resized.
  21583. @param numChannels the number of channels to use - this must correspond to the
  21584. number of elements in the array passed in
  21585. @param numSamples the number of samples to use - this must correspond to the
  21586. size of the arrays passed in
  21587. */
  21588. void setDataToReferTo (float** dataToReferTo,
  21589. int numChannels,
  21590. int numSamples) throw();
  21591. /** Clears all the samples in all channels. */
  21592. void clear() throw();
  21593. /** Clears a specified region of all the channels.
  21594. For speed, this doesn't check whether the channel and sample number
  21595. are in-range, so be careful!
  21596. */
  21597. void clear (int startSample,
  21598. int numSamples) throw();
  21599. /** Clears a specified region of just one channel.
  21600. For speed, this doesn't check whether the channel and sample number
  21601. are in-range, so be careful!
  21602. */
  21603. void clear (int channel,
  21604. int startSample,
  21605. int numSamples) throw();
  21606. /** Applies a gain multiple to a region of one channel.
  21607. For speed, this doesn't check whether the channel and sample number
  21608. are in-range, so be careful!
  21609. */
  21610. void applyGain (int channel,
  21611. int startSample,
  21612. int numSamples,
  21613. float gain) throw();
  21614. /** Applies a gain multiple to a region of all the channels.
  21615. For speed, this doesn't check whether the sample numbers
  21616. are in-range, so be careful!
  21617. */
  21618. void applyGain (int startSample,
  21619. int numSamples,
  21620. float gain) throw();
  21621. /** Applies a range of gains to a region of a channel.
  21622. The gain that is applied to each sample will vary from
  21623. startGain on the first sample to endGain on the last Sample,
  21624. so it can be used to do basic fades.
  21625. For speed, this doesn't check whether the sample numbers
  21626. are in-range, so be careful!
  21627. */
  21628. void applyGainRamp (int channel,
  21629. int startSample,
  21630. int numSamples,
  21631. float startGain,
  21632. float endGain) throw();
  21633. /** Adds samples from another buffer to this one.
  21634. @param destChannel the channel within this buffer to add the samples to
  21635. @param destStartSample the start sample within this buffer's channel
  21636. @param source the source buffer to add from
  21637. @param sourceChannel the channel within the source buffer to read from
  21638. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  21639. @param numSamples the number of samples to process
  21640. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  21641. added to this buffer's samples
  21642. @see copyFrom
  21643. */
  21644. void addFrom (int destChannel,
  21645. int destStartSample,
  21646. const AudioSampleBuffer& source,
  21647. int sourceChannel,
  21648. int sourceStartSample,
  21649. int numSamples,
  21650. float gainToApplyToSource = 1.0f) throw();
  21651. /** Adds samples from an array of floats to one of the channels.
  21652. @param destChannel the channel within this buffer to add the samples to
  21653. @param destStartSample the start sample within this buffer's channel
  21654. @param source the source data to use
  21655. @param numSamples the number of samples to process
  21656. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  21657. added to this buffer's samples
  21658. @see copyFrom
  21659. */
  21660. void addFrom (int destChannel,
  21661. int destStartSample,
  21662. const float* source,
  21663. int numSamples,
  21664. float gainToApplyToSource = 1.0f) throw();
  21665. /** Adds samples from an array of floats, applying a gain ramp to them.
  21666. @param destChannel the channel within this buffer to add the samples to
  21667. @param destStartSample the start sample within this buffer's channel
  21668. @param source the source data to use
  21669. @param numSamples the number of samples to process
  21670. @param startGain the gain to apply to the first sample (this is multiplied with
  21671. the source samples before they are added to this buffer)
  21672. @param endGain the gain to apply to the final sample. The gain is linearly
  21673. interpolated between the first and last samples.
  21674. */
  21675. void addFromWithRamp (int destChannel,
  21676. int destStartSample,
  21677. const float* source,
  21678. int numSamples,
  21679. float startGain,
  21680. float endGain) throw();
  21681. /** Copies samples from another buffer to this one.
  21682. @param destChannel the channel within this buffer to copy the samples to
  21683. @param destStartSample the start sample within this buffer's channel
  21684. @param source the source buffer to read from
  21685. @param sourceChannel the channel within the source buffer to read from
  21686. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  21687. @param numSamples the number of samples to process
  21688. @see addFrom
  21689. */
  21690. void copyFrom (int destChannel,
  21691. int destStartSample,
  21692. const AudioSampleBuffer& source,
  21693. int sourceChannel,
  21694. int sourceStartSample,
  21695. int numSamples) throw();
  21696. /** Copies samples from an array of floats into one of the channels.
  21697. @param destChannel the channel within this buffer to copy the samples to
  21698. @param destStartSample the start sample within this buffer's channel
  21699. @param source the source buffer to read from
  21700. @param numSamples the number of samples to process
  21701. @see addFrom
  21702. */
  21703. void copyFrom (int destChannel,
  21704. int destStartSample,
  21705. const float* source,
  21706. int numSamples) throw();
  21707. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  21708. @param destChannel the channel within this buffer to copy the samples to
  21709. @param destStartSample the start sample within this buffer's channel
  21710. @param source the source buffer to read from
  21711. @param numSamples the number of samples to process
  21712. @param gain the gain to apply
  21713. @see addFrom
  21714. */
  21715. void copyFrom (int destChannel,
  21716. int destStartSample,
  21717. const float* source,
  21718. int numSamples,
  21719. float gain) throw();
  21720. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  21721. @param destChannel the channel within this buffer to copy the samples to
  21722. @param destStartSample the start sample within this buffer's channel
  21723. @param source the source buffer to read from
  21724. @param numSamples the number of samples to process
  21725. @param startGain the gain to apply to the first sample (this is multiplied with
  21726. the source samples before they are copied to this buffer)
  21727. @param endGain the gain to apply to the final sample. The gain is linearly
  21728. interpolated between the first and last samples.
  21729. @see addFrom
  21730. */
  21731. void copyFromWithRamp (int destChannel,
  21732. int destStartSample,
  21733. const float* source,
  21734. int numSamples,
  21735. float startGain,
  21736. float endGain) throw();
  21737. /** Finds the highest and lowest sample values in a given range.
  21738. @param channel the channel to read from
  21739. @param startSample the start sample within the channel
  21740. @param numSamples the number of samples to check
  21741. @param minVal on return, the lowest value that was found
  21742. @param maxVal on return, the highest value that was found
  21743. */
  21744. void findMinMax (int channel,
  21745. int startSample,
  21746. int numSamples,
  21747. float& minVal,
  21748. float& maxVal) const throw();
  21749. /** Finds the highest absolute sample value within a region of a channel.
  21750. */
  21751. float getMagnitude (int channel,
  21752. int startSample,
  21753. int numSamples) const throw();
  21754. /** Finds the highest absolute sample value within a region on all channels.
  21755. */
  21756. float getMagnitude (int startSample,
  21757. int numSamples) const throw();
  21758. /** Returns the root mean squared level for a region of a channel.
  21759. */
  21760. float getRMSLevel (int channel,
  21761. int startSample,
  21762. int numSamples) const throw();
  21763. /** Fills a section of the buffer using an AudioReader as its source.
  21764. This will convert the reader's fixed- or floating-point data to
  21765. the buffer's floating-point format, and will try to intelligently
  21766. cope with mismatches between the number of channels in the reader
  21767. and the buffer.
  21768. @see writeToAudioWriter
  21769. */
  21770. void readFromAudioReader (AudioFormatReader* reader,
  21771. int startSample,
  21772. int numSamples,
  21773. int readerStartSample,
  21774. bool useReaderLeftChan,
  21775. bool useReaderRightChan) throw();
  21776. /** Writes a section of this buffer to an audio writer.
  21777. This saves you having to mess about with channels or floating/fixed
  21778. point conversion.
  21779. @see readFromAudioReader
  21780. */
  21781. void writeToAudioWriter (AudioFormatWriter* writer,
  21782. int startSample,
  21783. int numSamples) const throw();
  21784. juce_UseDebuggingNewOperator
  21785. private:
  21786. int numChannels, size;
  21787. size_t allocatedBytes;
  21788. float** channels;
  21789. HeapBlock <char> allocatedData;
  21790. float* preallocatedChannelSpace [32];
  21791. void allocateData();
  21792. void allocateChannels (float** dataToReferTo);
  21793. };
  21794. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  21795. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  21796. /**
  21797. Used by AudioSource::getNextAudioBlock().
  21798. */
  21799. struct JUCE_API AudioSourceChannelInfo
  21800. {
  21801. /** The destination buffer to fill with audio data.
  21802. When the AudioSource::getNextAudioBlock() method is called, the active section
  21803. of this buffer should be filled with whatever output the source produces.
  21804. Only the samples specified by the startSample and numSamples members of this structure
  21805. should be affected by the call.
  21806. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  21807. method can be treated as the input if the source is performing some kind of filter operation,
  21808. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  21809. a handy way of doing this.
  21810. The number of channels in the buffer could be anything, so the AudioSource
  21811. must cope with this in whatever way is appropriate for its function.
  21812. */
  21813. AudioSampleBuffer* buffer;
  21814. /** The first sample in the buffer from which the callback is expected
  21815. to write data. */
  21816. int startSample;
  21817. /** The number of samples in the buffer which the callback is expected to
  21818. fill with data. */
  21819. int numSamples;
  21820. /** Convenient method to clear the buffer if the source is not producing any data. */
  21821. void clearActiveBufferRegion() const
  21822. {
  21823. if (buffer != 0)
  21824. buffer->clear (startSample, numSamples);
  21825. }
  21826. };
  21827. /**
  21828. Base class for objects that can produce a continuous stream of audio.
  21829. @see AudioFormatReaderSource, ResamplingAudioSource
  21830. */
  21831. class JUCE_API AudioSource
  21832. {
  21833. protected:
  21834. /** Creates an AudioSource. */
  21835. AudioSource() throw() {}
  21836. public:
  21837. /** Destructor. */
  21838. virtual ~AudioSource() {}
  21839. /** Tells the source to prepare for playing.
  21840. The source can use this opportunity to initialise anything it needs to.
  21841. Note that this method could be called more than once in succession without
  21842. a matching call to releaseResources(), so make sure your code is robust and
  21843. can handle that kind of situation.
  21844. @param samplesPerBlockExpected the number of samples that the source
  21845. will be expected to supply each time its
  21846. getNextAudioBlock() method is called. This
  21847. number may vary slightly, because it will be dependent
  21848. on audio hardware callbacks, and these aren't
  21849. guaranteed to always use a constant block size, so
  21850. the source should be able to cope with small variations.
  21851. @param sampleRate the sample rate that the output will be used at - this
  21852. is needed by sources such as tone generators.
  21853. @see releaseResources, getNextAudioBlock
  21854. */
  21855. virtual void prepareToPlay (int samplesPerBlockExpected,
  21856. double sampleRate) = 0;
  21857. /** Allows the source to release anything it no longer needs after playback has stopped.
  21858. This will be called when the source is no longer going to have its getNextAudioBlock()
  21859. method called, so it should release any spare memory, etc. that it might have
  21860. allocated during the prepareToPlay() call.
  21861. Note that there's no guarantee that prepareToPlay() will actually have been called before
  21862. releaseResources(), and it may be called more than once in succession, so make sure your
  21863. code is robust and doesn't make any assumptions about when it will be called.
  21864. @see prepareToPlay, getNextAudioBlock
  21865. */
  21866. virtual void releaseResources() = 0;
  21867. /** Called repeatedly to fetch subsequent blocks of audio data.
  21868. After calling the prepareToPlay() method, this callback will be made each
  21869. time the audio playback hardware (or whatever other destination the audio
  21870. data is going to) needs another block of data.
  21871. It will generally be called on a high-priority system thread, or possibly even
  21872. an interrupt, so be careful not to do too much work here, as that will cause
  21873. audio glitches!
  21874. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  21875. */
  21876. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  21877. };
  21878. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  21879. /*** End of inlined file: juce_AudioSource.h ***/
  21880. /**
  21881. Writes samples to an audio file stream.
  21882. A subclass that writes a specific type of audio format will be created by
  21883. an AudioFormat object.
  21884. After creating one of these with the AudioFormat::createWriterFor() method
  21885. you can call its write() method to store the samples, and then delete it.
  21886. @see AudioFormat, AudioFormatReader
  21887. */
  21888. class JUCE_API AudioFormatWriter
  21889. {
  21890. protected:
  21891. /** Creates an AudioFormatWriter object.
  21892. @param destStream the stream to write to - this will be deleted
  21893. by this object when it is no longer needed
  21894. @param formatName the description that will be returned by the getFormatName()
  21895. method
  21896. @param sampleRate the sample rate to use - the base class just stores
  21897. this value, it doesn't do anything with it
  21898. @param numberOfChannels the number of channels to write - the base class just stores
  21899. this value, it doesn't do anything with it
  21900. @param bitsPerSample the bit depth of the stream - the base class just stores
  21901. this value, it doesn't do anything with it
  21902. */
  21903. AudioFormatWriter (OutputStream* destStream,
  21904. const String& formatName,
  21905. double sampleRate,
  21906. unsigned int numberOfChannels,
  21907. unsigned int bitsPerSample);
  21908. public:
  21909. /** Destructor. */
  21910. virtual ~AudioFormatWriter();
  21911. /** Returns a description of what type of format this is.
  21912. E.g. "AIFF file"
  21913. */
  21914. const String getFormatName() const throw() { return formatName; }
  21915. /** Writes a set of samples to the audio stream.
  21916. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  21917. can use AudioSampleBuffer::writeToAudioWriter().
  21918. @param samplesToWrite an array of arrays containing the sample data for
  21919. each channel to write. This is a zero-terminated
  21920. array of arrays, and can contain a different number
  21921. of channels than the actual stream uses, and the
  21922. writer should do its best to cope with this.
  21923. If the format is fixed-point, each channel will be formatted
  21924. as an array of signed integers using the full 32-bit
  21925. range -0x80000000 to 0x7fffffff, regardless of the source's
  21926. bit-depth. If it is a floating-point format, you should treat
  21927. the arrays as arrays of floats, and just cast it to an (int**)
  21928. to pass it into the method.
  21929. @param numSamples the number of samples to write
  21930. */
  21931. virtual bool write (const int** samplesToWrite,
  21932. int numSamples) = 0;
  21933. /** Reads a section of samples from an AudioFormatReader, and writes these to
  21934. the output.
  21935. This will take care of any floating-point conversion that's required to convert
  21936. between the two formats. It won't deal with sample-rate conversion, though.
  21937. If numSamplesToRead < 0, it will write the entire length of the reader.
  21938. @returns false if it can't read or write properly during the operation
  21939. */
  21940. bool writeFromAudioReader (AudioFormatReader& reader,
  21941. int64 startSample,
  21942. int64 numSamplesToRead);
  21943. /** Reads some samples from an AudioSource, and writes these to the output.
  21944. The source must already have been initialised with the AudioSource::prepareToPlay() method
  21945. @param source the source to read from
  21946. @param numSamplesToRead total number of samples to read and write
  21947. @param samplesPerBlock the maximum number of samples to fetch from the source
  21948. @returns false if it can't read or write properly during the operation
  21949. */
  21950. bool writeFromAudioSource (AudioSource& source,
  21951. int numSamplesToRead,
  21952. int samplesPerBlock = 2048);
  21953. /** Returns the sample rate being used. */
  21954. double getSampleRate() const throw() { return sampleRate; }
  21955. /** Returns the number of channels being written. */
  21956. int getNumChannels() const throw() { return numChannels; }
  21957. /** Returns the bit-depth of the data being written. */
  21958. int getBitsPerSample() const throw() { return bitsPerSample; }
  21959. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  21960. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  21961. juce_UseDebuggingNewOperator
  21962. protected:
  21963. /** The sample rate of the stream. */
  21964. double sampleRate;
  21965. /** The number of channels being written to the stream. */
  21966. unsigned int numChannels;
  21967. /** The bit depth of the file. */
  21968. unsigned int bitsPerSample;
  21969. /** True if it's a floating-point format, false if it's fixed-point. */
  21970. bool usesFloatingPointData;
  21971. /** The output stream for Use by subclasses. */
  21972. OutputStream* output;
  21973. private:
  21974. String formatName;
  21975. AudioFormatWriter (const AudioFormatWriter&);
  21976. AudioFormatWriter& operator= (const AudioFormatWriter&);
  21977. };
  21978. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  21979. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  21980. /**
  21981. Subclasses of AudioFormat are used to read and write different audio
  21982. file formats.
  21983. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  21984. */
  21985. class JUCE_API AudioFormat
  21986. {
  21987. public:
  21988. /** Destructor. */
  21989. virtual ~AudioFormat();
  21990. /** Returns the name of this format.
  21991. e.g. "WAV file" or "AIFF file"
  21992. */
  21993. const String& getFormatName() const;
  21994. /** Returns all the file extensions that might apply to a file of this format.
  21995. The first item will be the one that's preferred when creating a new file.
  21996. So for a wav file this might just return ".wav"; for an AIFF file it might
  21997. return two items, ".aif" and ".aiff"
  21998. */
  21999. const StringArray& getFileExtensions() const;
  22000. /** Returns true if this the given file can be read by this format.
  22001. Subclasses shouldn't do too much work here, just check the extension or
  22002. file type. The base class implementation just checks the file's extension
  22003. against one of the ones that was registered in the constructor.
  22004. */
  22005. virtual bool canHandleFile (const File& fileToTest);
  22006. /** Returns a set of sample rates that the format can read and write. */
  22007. virtual const Array <int> getPossibleSampleRates() = 0;
  22008. /** Returns a set of bit depths that the format can read and write. */
  22009. virtual const Array <int> getPossibleBitDepths() = 0;
  22010. /** Returns true if the format can do 2-channel audio. */
  22011. virtual bool canDoStereo() = 0;
  22012. /** Returns true if the format can do 1-channel audio. */
  22013. virtual bool canDoMono() = 0;
  22014. /** Returns true if the format uses compressed data. */
  22015. virtual bool isCompressed();
  22016. /** Returns a list of different qualities that can be used when writing.
  22017. Non-compressed formats will just return an empty array, but for something
  22018. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  22019. When calling createWriterFor(), an index from this array is passed in to
  22020. tell the format which option is required.
  22021. */
  22022. virtual const StringArray getQualityOptions();
  22023. /** Tries to create an object that can read from a stream containing audio
  22024. data in this format.
  22025. The reader object that is returned can be used to read from the stream, and
  22026. should then be deleted by the caller.
  22027. @param sourceStream the stream to read from - the AudioFormatReader object
  22028. that is returned will delete this stream when it no longer
  22029. needs it.
  22030. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  22031. should delete the stream object that was passed-in. (If a valid
  22032. reader is returned, it will always be in charge of deleting the
  22033. stream, so this parameter is ignored)
  22034. @see AudioFormatReader
  22035. */
  22036. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22037. const bool deleteStreamIfOpeningFails) = 0;
  22038. /** Tries to create an object that can write to a stream with this audio format.
  22039. The writer object that is returned can be used to write to the stream, and
  22040. should then be deleted by the caller.
  22041. If the stream can't be created for some reason (e.g. the parameters passed in
  22042. here aren't suitable), this will return 0.
  22043. @param streamToWriteTo the stream that the data will go to - this will be
  22044. deleted by the AudioFormatWriter object when it's no longer
  22045. needed. If no AudioFormatWriter can be created by this method,
  22046. the stream will NOT be deleted, so that the caller can re-use it
  22047. to try to open a different format, etc
  22048. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  22049. returned by getPossibleSampleRates()
  22050. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  22051. the choice will depend on the results of canDoMono() and
  22052. canDoStereo()
  22053. @param bitsPerSample the bits per sample to use - this must be one of the values
  22054. returned by getPossibleBitDepths()
  22055. @param metadataValues a set of metadata values that the writer should try to write
  22056. to the stream. Exactly what these are depends on the format,
  22057. and the subclass doesn't actually have to do anything with
  22058. them if it doesn't want to. Have a look at the specific format
  22059. implementation classes to see possible values that can be
  22060. used
  22061. @param qualityOptionIndex the index of one of compression qualities returned by the
  22062. getQualityOptions() method. If there aren't any quality options
  22063. for this format, just pass 0 in this parameter, as it'll be
  22064. ignored
  22065. @see AudioFormatWriter
  22066. */
  22067. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22068. double sampleRateToUse,
  22069. unsigned int numberOfChannels,
  22070. int bitsPerSample,
  22071. const StringPairArray& metadataValues,
  22072. int qualityOptionIndex) = 0;
  22073. protected:
  22074. /** Creates an AudioFormat object.
  22075. @param formatName this sets the value that will be returned by getFormatName()
  22076. @param fileExtensions a zero-terminated list of file extensions - this is what will
  22077. be returned by getFileExtension()
  22078. */
  22079. AudioFormat (const String& formatName,
  22080. const StringArray& fileExtensions);
  22081. private:
  22082. String formatName;
  22083. StringArray fileExtensions;
  22084. };
  22085. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  22086. /*** End of inlined file: juce_AudioFormat.h ***/
  22087. /**
  22088. Reads and Writes AIFF format audio files.
  22089. @see AudioFormat
  22090. */
  22091. class JUCE_API AiffAudioFormat : public AudioFormat
  22092. {
  22093. public:
  22094. /** Creates an format object. */
  22095. AiffAudioFormat();
  22096. /** Destructor. */
  22097. ~AiffAudioFormat();
  22098. const Array <int> getPossibleSampleRates();
  22099. const Array <int> getPossibleBitDepths();
  22100. bool canDoStereo();
  22101. bool canDoMono();
  22102. #if JUCE_MAC
  22103. bool canHandleFile (const File& fileToTest);
  22104. #endif
  22105. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22106. const bool deleteStreamIfOpeningFails);
  22107. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22108. double sampleRateToUse,
  22109. unsigned int numberOfChannels,
  22110. int bitsPerSample,
  22111. const StringPairArray& metadataValues,
  22112. int qualityOptionIndex);
  22113. juce_UseDebuggingNewOperator
  22114. };
  22115. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22116. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  22117. #endif
  22118. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22119. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  22120. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22121. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22122. #if JUCE_USE_CDBURNER
  22123. /**
  22124. */
  22125. class AudioCDBurner : public ChangeBroadcaster
  22126. {
  22127. public:
  22128. /** Returns a list of available optical drives.
  22129. Use openDevice() to open one of the items from this list.
  22130. */
  22131. static const StringArray findAvailableDevices();
  22132. /** Tries to open one of the optical drives.
  22133. The deviceIndex is an index into the array returned by findAvailableDevices().
  22134. */
  22135. static AudioCDBurner* openDevice (const int deviceIndex);
  22136. /** Destructor. */
  22137. ~AudioCDBurner();
  22138. enum DiskState
  22139. {
  22140. unknown, /**< An error condition, if the device isn't responding. */
  22141. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  22142. may seem to be permanently open. */
  22143. noDisc, /**< The drive has no disk in it. */
  22144. writableDiskPresent, /**< The drive contains a writeable disk. */
  22145. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  22146. };
  22147. /** Returns the current status of the device.
  22148. To get informed when the drive's status changes, attach a ChangeListener to
  22149. the AudioCDBurner.
  22150. */
  22151. DiskState getDiskState() const;
  22152. /** Returns true if there's a writable disk in the drive. */
  22153. bool isDiskPresent() const;
  22154. /** Sends an eject signal to the drive.
  22155. The eject will happen asynchronously, so you can use getDiskState() and
  22156. waitUntilStateChange() to monitor its progress.
  22157. */
  22158. bool openTray();
  22159. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  22160. @returns the device's new state
  22161. */
  22162. DiskState waitUntilStateChange (int timeOutMilliseconds);
  22163. /** Returns the set of possible write speeds that the device can handle.
  22164. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  22165. Note that if there's no media present in the drive, this value may be unavailable!
  22166. @see setWriteSpeed, getWriteSpeed
  22167. */
  22168. const Array<int> getAvailableWriteSpeeds() const;
  22169. /** Tries to enable or disable buffer underrun safety on devices that support it.
  22170. @returns true if it's now enabled. If the device doesn't support it, this
  22171. will always return false.
  22172. */
  22173. bool setBufferUnderrunProtection (const bool shouldBeEnabled);
  22174. /** Returns the number of free blocks on the disk.
  22175. There are 75 blocks per second, at 44100Hz.
  22176. */
  22177. int getNumAvailableAudioBlocks() const;
  22178. /** Adds a track to be written.
  22179. The source passed-in here will be kept by this object, and it will
  22180. be used and deleted at some point in the future, either during the
  22181. burn() method or when this AudioCDBurner object is deleted. Your caller
  22182. method shouldn't keep a reference to it or use it again after passing
  22183. it in here.
  22184. */
  22185. bool addAudioTrack (AudioSource* source, int numSamples);
  22186. /** Receives progress callbacks during a cd-burn operation.
  22187. @see AudioCDBurner::burn()
  22188. */
  22189. class BurnProgressListener
  22190. {
  22191. public:
  22192. BurnProgressListener() throw() {}
  22193. virtual ~BurnProgressListener() {}
  22194. /** Called at intervals to report on the progress of the AudioCDBurner.
  22195. To cancel the burn, return true from this method.
  22196. */
  22197. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  22198. };
  22199. /** Runs the burn process.
  22200. This method will block until the operation is complete.
  22201. @param listener the object to receive callbacks about progress
  22202. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  22203. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  22204. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  22205. 0 or less to mean the fastest speed.
  22206. */
  22207. const String burn (BurnProgressListener* listener,
  22208. bool ejectDiscAfterwards,
  22209. bool performFakeBurnForTesting,
  22210. int writeSpeed);
  22211. /** If a burn operation is currently in progress, this tells it to stop
  22212. as soon as possible.
  22213. It's also possible to stop the burn process by returning true from
  22214. BurnProgressListener::audioCDBurnProgress()
  22215. */
  22216. void abortBurn();
  22217. juce_UseDebuggingNewOperator
  22218. private:
  22219. AudioCDBurner (const int deviceIndex);
  22220. class Pimpl;
  22221. friend class ScopedPointer<Pimpl>;
  22222. ScopedPointer<Pimpl> pimpl;
  22223. };
  22224. #endif
  22225. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22226. /*** End of inlined file: juce_AudioCDBurner.h ***/
  22227. #endif
  22228. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22229. /*** Start of inlined file: juce_AudioCDReader.h ***/
  22230. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22231. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  22232. #if JUCE_USE_CDREADER
  22233. #if JUCE_MAC
  22234. #endif
  22235. /**
  22236. A type of AudioFormatReader that reads from an audio CD.
  22237. One of these can be used to read a CD as if it's one big audio stream. Use the
  22238. getPositionOfTrackStart() method to find where the individual tracks are
  22239. within the stream.
  22240. @see AudioFormatReader
  22241. */
  22242. class JUCE_API AudioCDReader : public AudioFormatReader
  22243. {
  22244. public:
  22245. /** Returns a list of names of Audio CDs currently available for reading.
  22246. If there's a CD drive but no CD in it, this might return an empty list, or
  22247. possibly a device that can be opened but which has no tracks, depending
  22248. on the platform.
  22249. @see createReaderForCD
  22250. */
  22251. static const StringArray getAvailableCDNames();
  22252. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  22253. @param index the index of one of the available CDs - use getAvailableCDNames()
  22254. to find out how many there are.
  22255. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  22256. caller will be responsible for deleting the object returned.
  22257. */
  22258. static AudioCDReader* createReaderForCD (const int index);
  22259. /** Destructor. */
  22260. ~AudioCDReader();
  22261. /** Implementation of the AudioFormatReader method. */
  22262. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  22263. int64 startSampleInFile, int numSamples);
  22264. /** Checks whether the CD has been removed from the drive.
  22265. */
  22266. bool isCDStillPresent() const;
  22267. /** Returns the total number of tracks (audio + data).
  22268. */
  22269. int getNumTracks() const;
  22270. /** Finds the sample offset of the start of a track.
  22271. @param trackNum the track number, where 0 is the first track.
  22272. */
  22273. int getPositionOfTrackStart (int trackNum) const;
  22274. /** Returns true if a given track is an audio track.
  22275. @param trackNum the track number, where 0 is the first track.
  22276. */
  22277. bool isTrackAudio (int trackNum) const;
  22278. /** Refreshes the object's table of contents.
  22279. If the disc has been ejected and a different one put in since this
  22280. object was created, this will cause it to update its idea of how many tracks
  22281. there are, etc.
  22282. */
  22283. void refreshTrackLengths();
  22284. /** Enables scanning for indexes within tracks.
  22285. @see getLastIndex
  22286. */
  22287. void enableIndexScanning (bool enabled);
  22288. /** Returns the index number found during the last read() call.
  22289. Index scanning is turned off by default - turn it on with enableIndexScanning().
  22290. Then when the read() method is called, if it comes across an index within that
  22291. block, the index number is stored and returned by this method.
  22292. Some devices might not support indexes, of course.
  22293. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  22294. @see enableIndexScanning
  22295. */
  22296. int getLastIndex() const;
  22297. /** Scans a track to find the position of any indexes within it.
  22298. @param trackNumber the track to look in, where 0 is the first track on the disc
  22299. @returns an array of sample positions of any index points found (not including
  22300. the index that marks the start of the track)
  22301. */
  22302. const Array <int> findIndexesInTrack (const int trackNumber);
  22303. /** Returns the CDDB id number for the CD.
  22304. It's not a great way of identifying a disc, but it's traditional.
  22305. */
  22306. int getCDDBId();
  22307. /** Tries to eject the disk.
  22308. Of course this might not be possible, if some other process is using it.
  22309. */
  22310. void ejectDisk();
  22311. juce_UseDebuggingNewOperator
  22312. private:
  22313. #if JUCE_MAC
  22314. File volumeDir;
  22315. Array<File> tracks;
  22316. Array<int> trackStartSamples;
  22317. int currentReaderTrack;
  22318. ScopedPointer <AudioFormatReader> reader;
  22319. AudioCDReader (const File& volume);
  22320. public:
  22321. static int compareElements (const File&, const File&);
  22322. private:
  22323. #elif JUCE_WINDOWS
  22324. int numTracks;
  22325. int trackStarts[100];
  22326. bool audioTracks [100];
  22327. void* handle;
  22328. bool indexingEnabled;
  22329. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  22330. MemoryBlock buffer;
  22331. AudioCDReader (void* handle);
  22332. int getIndexAt (int samplePos);
  22333. #elif JUCE_LINUX
  22334. AudioCDReader();
  22335. #endif
  22336. AudioCDReader (const AudioCDReader&);
  22337. AudioCDReader& operator= (const AudioCDReader&);
  22338. };
  22339. #endif
  22340. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  22341. /*** End of inlined file: juce_AudioCDReader.h ***/
  22342. #endif
  22343. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  22344. #endif
  22345. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22346. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  22347. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22348. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22349. /**
  22350. A class for keeping a list of available audio formats, and for deciding which
  22351. one to use to open a given file.
  22352. You can either use this class as a singleton object, or create instances of it
  22353. yourself. Once created, use its registerFormat() method to tell it which
  22354. formats it should use.
  22355. @see AudioFormat
  22356. */
  22357. class JUCE_API AudioFormatManager
  22358. {
  22359. public:
  22360. /** Creates an empty format manager.
  22361. Before it'll be any use, you'll need to call registerFormat() with all the
  22362. formats you want it to be able to recognise.
  22363. */
  22364. AudioFormatManager();
  22365. /** Destructor. */
  22366. ~AudioFormatManager();
  22367. juce_DeclareSingleton (AudioFormatManager, false);
  22368. /** Adds a format to the manager's list of available file types.
  22369. The object passed-in will be deleted by this object, so don't keep a pointer
  22370. to it!
  22371. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  22372. return this one when called.
  22373. */
  22374. void registerFormat (AudioFormat* newFormat,
  22375. bool makeThisTheDefaultFormat);
  22376. /** Handy method to make it easy to register the formats that come with Juce.
  22377. Currently, this will add WAV and AIFF to the list.
  22378. */
  22379. void registerBasicFormats();
  22380. /** Clears the list of known formats. */
  22381. void clearFormats();
  22382. /** Returns the number of currently registered file formats. */
  22383. int getNumKnownFormats() const;
  22384. /** Returns one of the registered file formats. */
  22385. AudioFormat* getKnownFormat (int index) const;
  22386. /** Looks for which of the known formats is listed as being for a given file
  22387. extension.
  22388. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  22389. */
  22390. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  22391. /** Returns the format which has been set as the default one.
  22392. You can set a format as being the default when it is registered. It's useful
  22393. when you want to write to a file, because the best format may change between
  22394. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  22395. If none has been set as the default, this method will just return the first
  22396. one in the list.
  22397. */
  22398. AudioFormat* getDefaultFormat() const;
  22399. /** Returns a set of wildcards for file-matching that contains the extensions for
  22400. all known formats.
  22401. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  22402. */
  22403. const String getWildcardForAllFormats() const;
  22404. /** Searches through the known formats to try to create a suitable reader for
  22405. this file.
  22406. If none of the registered formats can open the file, it'll return 0. If it
  22407. returns a reader, it's the caller's responsibility to delete the reader.
  22408. */
  22409. AudioFormatReader* createReaderFor (const File& audioFile);
  22410. /** Searches through the known formats to try to create a suitable reader for
  22411. this stream.
  22412. The stream object that is passed-in will be deleted by this method or by the
  22413. reader that is returned, so the caller should not keep any references to it.
  22414. The stream that is passed-in must be capable of being repositioned so
  22415. that all the formats can have a go at opening it.
  22416. If none of the registered formats can open the stream, it'll return 0. If it
  22417. returns a reader, it's the caller's responsibility to delete the reader.
  22418. */
  22419. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  22420. juce_UseDebuggingNewOperator
  22421. private:
  22422. OwnedArray<AudioFormat> knownFormats;
  22423. int defaultFormatIndex;
  22424. };
  22425. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  22426. /*** End of inlined file: juce_AudioFormatManager.h ***/
  22427. #endif
  22428. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22429. #endif
  22430. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22431. #endif
  22432. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22433. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  22434. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22435. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22436. /**
  22437. This class is used to wrap an AudioFormatReader and only read from a
  22438. subsection of the file.
  22439. So if you have a reader which can read a 1000 sample file, you could wrap it
  22440. in one of these to only access, e.g. samples 100 to 200, and any samples
  22441. outside that will come back as 0. Accessing sample 0 from this reader will
  22442. actually read the first sample from the other's subsection, which might
  22443. be at a non-zero position.
  22444. @see AudioFormatReader
  22445. */
  22446. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  22447. {
  22448. public:
  22449. /** Creates a AudioSubsectionReader for a given data source.
  22450. @param sourceReader the source reader from which we'll be taking data
  22451. @param subsectionStartSample the sample within the source reader which will be
  22452. mapped onto sample 0 for this reader.
  22453. @param subsectionLength the number of samples from the source that will
  22454. make up the subsection. If this reader is asked for
  22455. any samples beyond this region, it will return zero.
  22456. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  22457. this object is deleted.
  22458. */
  22459. AudioSubsectionReader (AudioFormatReader* sourceReader,
  22460. int64 subsectionStartSample,
  22461. int64 subsectionLength,
  22462. bool deleteSourceWhenDeleted);
  22463. /** Destructor. */
  22464. ~AudioSubsectionReader();
  22465. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  22466. int64 startSampleInFile, int numSamples);
  22467. void readMaxLevels (int64 startSample,
  22468. int64 numSamples,
  22469. float& lowestLeft,
  22470. float& highestLeft,
  22471. float& lowestRight,
  22472. float& highestRight);
  22473. juce_UseDebuggingNewOperator
  22474. private:
  22475. AudioFormatReader* const source;
  22476. int64 startSample, length;
  22477. const bool deleteSourceWhenDeleted;
  22478. AudioSubsectionReader (const AudioSubsectionReader&);
  22479. AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  22480. };
  22481. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  22482. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  22483. #endif
  22484. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22485. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  22486. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22487. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22488. class AudioThumbnailCache;
  22489. /**
  22490. Makes it easy to quickly draw scaled views of the waveform shape of an
  22491. audio file.
  22492. To use this class, just create an AudioThumbNail class for the file you want
  22493. to draw, call setSource to tell it which file or resource to use, then call
  22494. drawChannel() to draw it.
  22495. The class will asynchronously scan the wavefile to create its scaled-down view,
  22496. so you should make your UI repaint itself as this data comes in. To do this, the
  22497. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  22498. listeners should repaint themselves.
  22499. The thumbnail stores an internal low-res version of the wave data, and this can
  22500. be loaded and saved to avoid having to scan the file again.
  22501. @see AudioThumbnailCache
  22502. */
  22503. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  22504. public TimeSliceClient,
  22505. private Timer
  22506. {
  22507. public:
  22508. /** Creates an audio thumbnail.
  22509. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  22510. of the audio data, this is the scale at which it should be done. (This
  22511. number is the number of original samples that will be averaged for each
  22512. low-res sample)
  22513. @param formatManagerToUse the audio format manager that is used to open the file
  22514. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  22515. thread and storage that is used to by the thumbnail, and the cache
  22516. object can be shared between multiple thumbnails
  22517. */
  22518. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  22519. AudioFormatManager& formatManagerToUse,
  22520. AudioThumbnailCache& cacheToUse);
  22521. /** Destructor. */
  22522. ~AudioThumbnail();
  22523. /** Specifies the file or stream that contains the audio file.
  22524. For a file, just call
  22525. @code
  22526. setSource (new FileInputSource (file))
  22527. @endcode
  22528. You can pass a zero in here to clear the thumbnail.
  22529. The source that is passed in will be deleted by this object when it is no
  22530. longer needed
  22531. */
  22532. void setSource (InputSource* newSource);
  22533. /** Reloads the low res thumbnail data from an input stream.
  22534. The thumb will automatically attempt to reload itself from its
  22535. AudioThumbnailCache.
  22536. */
  22537. void loadFrom (InputStream& input);
  22538. /** Saves the low res thumbnail data to an output stream.
  22539. The thumb will automatically attempt to save itself to its
  22540. AudioThumbnailCache after it finishes scanning the wave file.
  22541. */
  22542. void saveTo (OutputStream& output) const;
  22543. /** Returns the number of channels in the file.
  22544. */
  22545. int getNumChannels() const throw();
  22546. /** Returns the length of the audio file, in seconds.
  22547. */
  22548. double getTotalLength() const throw();
  22549. /** Renders the waveform shape for a channel.
  22550. The waveform will be drawn within the specified rectangle, where startTime
  22551. and endTime specify the times within the audio file that should be positioned
  22552. at the left and right edges of the rectangle.
  22553. The waveform will be scaled vertically so that a full-volume sample will fill
  22554. the rectangle vertically, but you can also specify an extra vertical scale factor
  22555. with the verticalZoomFactor parameter.
  22556. */
  22557. void drawChannel (Graphics& g,
  22558. int x, int y, int w, int h,
  22559. double startTimeSeconds,
  22560. double endTimeSeconds,
  22561. int channelNum,
  22562. float verticalZoomFactor);
  22563. /** Returns true if the low res preview is fully generated.
  22564. */
  22565. bool isFullyLoaded() const throw();
  22566. /** @internal */
  22567. bool useTimeSlice();
  22568. /** @internal */
  22569. void timerCallback();
  22570. juce_UseDebuggingNewOperator
  22571. private:
  22572. AudioFormatManager& formatManagerToUse;
  22573. AudioThumbnailCache& cache;
  22574. ScopedPointer <InputSource> source;
  22575. CriticalSection readerLock;
  22576. ScopedPointer <AudioFormatReader> reader;
  22577. MemoryBlock data, cachedLevels;
  22578. int orginalSamplesPerThumbnailSample;
  22579. int numChannelsCached, numSamplesCached;
  22580. double cachedStart, cachedTimePerPixel;
  22581. bool cacheNeedsRefilling;
  22582. void clear();
  22583. AudioFormatReader* createReader() const;
  22584. void generateSection (AudioFormatReader& reader, int64 startSample, int numSamples);
  22585. char* getChannelData (int channel) const;
  22586. void refillCache (int numSamples, double startTime, double timePerPixel);
  22587. friend class AudioThumbnailCache;
  22588. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  22589. bool initialiseFromAudioFile (AudioFormatReader& reader);
  22590. // returns true if more needs to be read
  22591. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  22592. };
  22593. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  22594. /*** End of inlined file: juce_AudioThumbnail.h ***/
  22595. #endif
  22596. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22597. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  22598. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22599. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22600. struct ThumbnailCacheEntry;
  22601. /**
  22602. An instance of this class is used to manage multiple AudioThumbnail objects.
  22603. The cache runs a single background thread that is shared by all the thumbnails
  22604. that need it, and it maintains a set of low-res previews in memory, to avoid
  22605. having to re-scan audio files too often.
  22606. @see AudioThumbnail
  22607. */
  22608. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  22609. {
  22610. public:
  22611. /** Creates a cache object.
  22612. The maxNumThumbsToStore parameter lets you specify how many previews should
  22613. be kept in memory at once.
  22614. */
  22615. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  22616. /** Destructor. */
  22617. ~AudioThumbnailCache();
  22618. /** Clears out any stored thumbnails.
  22619. */
  22620. void clear();
  22621. /** Reloads the specified thumb if this cache contains the appropriate stored
  22622. data.
  22623. This is called automatically by the AudioThumbnail class, so you shouldn't
  22624. normally need to call it directly.
  22625. */
  22626. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  22627. /** Stores the cachable data from the specified thumb in this cache.
  22628. This is called automatically by the AudioThumbnail class, so you shouldn't
  22629. normally need to call it directly.
  22630. */
  22631. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  22632. juce_UseDebuggingNewOperator
  22633. private:
  22634. OwnedArray <ThumbnailCacheEntry> thumbs;
  22635. int maxNumThumbsToStore;
  22636. friend class AudioThumbnail;
  22637. void addThumbnail (AudioThumbnail* thumb);
  22638. void removeThumbnail (AudioThumbnail* thumb);
  22639. };
  22640. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  22641. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  22642. #endif
  22643. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  22644. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  22645. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  22646. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  22647. #if JUCE_USE_FLAC || defined (DOXYGEN)
  22648. /**
  22649. Reads and writes the lossless-compression FLAC audio format.
  22650. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  22651. and make sure your include search path and library search path are set up to find
  22652. the FLAC header files and static libraries.
  22653. @see AudioFormat
  22654. */
  22655. class JUCE_API FlacAudioFormat : public AudioFormat
  22656. {
  22657. public:
  22658. FlacAudioFormat();
  22659. ~FlacAudioFormat();
  22660. const Array <int> getPossibleSampleRates();
  22661. const Array <int> getPossibleBitDepths();
  22662. bool canDoStereo();
  22663. bool canDoMono();
  22664. bool isCompressed();
  22665. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22666. const bool deleteStreamIfOpeningFails);
  22667. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22668. double sampleRateToUse,
  22669. unsigned int numberOfChannels,
  22670. int bitsPerSample,
  22671. const StringPairArray& metadataValues,
  22672. int qualityOptionIndex);
  22673. juce_UseDebuggingNewOperator
  22674. };
  22675. #endif
  22676. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  22677. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  22678. #endif
  22679. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  22680. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  22681. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  22682. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  22683. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  22684. /**
  22685. Reads and writes the Ogg-Vorbis audio format.
  22686. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  22687. and make sure your include search path and library search path are set up to find
  22688. the Vorbis and Ogg header files and static libraries.
  22689. @see AudioFormat,
  22690. */
  22691. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  22692. {
  22693. public:
  22694. OggVorbisAudioFormat();
  22695. ~OggVorbisAudioFormat();
  22696. const Array <int> getPossibleSampleRates();
  22697. const Array <int> getPossibleBitDepths();
  22698. bool canDoStereo();
  22699. bool canDoMono();
  22700. bool isCompressed();
  22701. const StringArray getQualityOptions();
  22702. /** Tries to estimate the quality level of an ogg file based on its size.
  22703. If it can't read the file for some reason, this will just return 1 (medium quality),
  22704. otherwise it will return the approximate quality setting that would have been used
  22705. to create the file.
  22706. @see getQualityOptions
  22707. */
  22708. int estimateOggFileQuality (const File& source);
  22709. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22710. const bool deleteStreamIfOpeningFails);
  22711. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22712. double sampleRateToUse,
  22713. unsigned int numberOfChannels,
  22714. int bitsPerSample,
  22715. const StringPairArray& metadataValues,
  22716. int qualityOptionIndex);
  22717. juce_UseDebuggingNewOperator
  22718. };
  22719. #endif
  22720. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  22721. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  22722. #endif
  22723. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  22724. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  22725. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  22726. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  22727. #if JUCE_QUICKTIME
  22728. /**
  22729. Uses QuickTime to read the audio track a movie or media file.
  22730. As well as QuickTime movies, this should also manage to open other audio
  22731. files that quicktime can understand, like mp3, m4a, etc.
  22732. @see AudioFormat
  22733. */
  22734. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  22735. {
  22736. public:
  22737. /** Creates a format object. */
  22738. QuickTimeAudioFormat();
  22739. /** Destructor. */
  22740. ~QuickTimeAudioFormat();
  22741. const Array <int> getPossibleSampleRates();
  22742. const Array <int> getPossibleBitDepths();
  22743. bool canDoStereo();
  22744. bool canDoMono();
  22745. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22746. const bool deleteStreamIfOpeningFails);
  22747. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22748. double sampleRateToUse,
  22749. unsigned int numberOfChannels,
  22750. int bitsPerSample,
  22751. const StringPairArray& metadataValues,
  22752. int qualityOptionIndex);
  22753. juce_UseDebuggingNewOperator
  22754. };
  22755. #endif
  22756. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  22757. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  22758. #endif
  22759. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  22760. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  22761. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  22762. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  22763. /**
  22764. Reads and Writes WAV format audio files.
  22765. @see AudioFormat
  22766. */
  22767. class JUCE_API WavAudioFormat : public AudioFormat
  22768. {
  22769. public:
  22770. /** Creates a format object. */
  22771. WavAudioFormat();
  22772. /** Destructor. */
  22773. ~WavAudioFormat();
  22774. /** Metadata property name used by wav readers and writers for adding
  22775. a BWAV chunk to the file.
  22776. @see AudioFormatReader::metadataValues, createWriterFor
  22777. */
  22778. static const char* const bwavDescription;
  22779. /** Metadata property name used by wav readers and writers for adding
  22780. a BWAV chunk to the file.
  22781. @see AudioFormatReader::metadataValues, createWriterFor
  22782. */
  22783. static const char* const bwavOriginator;
  22784. /** Metadata property name used by wav readers and writers for adding
  22785. a BWAV chunk to the file.
  22786. @see AudioFormatReader::metadataValues, createWriterFor
  22787. */
  22788. static const char* const bwavOriginatorRef;
  22789. /** Metadata property name used by wav readers and writers for adding
  22790. a BWAV chunk to the file.
  22791. Date format is: yyyy-mm-dd
  22792. @see AudioFormatReader::metadataValues, createWriterFor
  22793. */
  22794. static const char* const bwavOriginationDate;
  22795. /** Metadata property name used by wav readers and writers for adding
  22796. a BWAV chunk to the file.
  22797. Time format is: hh-mm-ss
  22798. @see AudioFormatReader::metadataValues, createWriterFor
  22799. */
  22800. static const char* const bwavOriginationTime;
  22801. /** Metadata property name used by wav readers and writers for adding
  22802. a BWAV chunk to the file.
  22803. This is the number of samples from the start of an edit that the
  22804. file is supposed to begin at. Seems like an obvious mistake to
  22805. only allow a file to occur in an edit once, but that's the way
  22806. it is..
  22807. @see AudioFormatReader::metadataValues, createWriterFor
  22808. */
  22809. static const char* const bwavTimeReference;
  22810. /** Metadata property name used by wav readers and writers for adding
  22811. a BWAV chunk to the file.
  22812. This is a
  22813. @see AudioFormatReader::metadataValues, createWriterFor
  22814. */
  22815. static const char* const bwavCodingHistory;
  22816. /** Utility function to fill out the appropriate metadata for a BWAV file.
  22817. This just makes it easier than using the property names directly, and it
  22818. fills out the time and date in the right format.
  22819. */
  22820. static const StringPairArray createBWAVMetadata (const String& description,
  22821. const String& originator,
  22822. const String& originatorRef,
  22823. const Time& dateAndTime,
  22824. const int64 timeReferenceSamples,
  22825. const String& codingHistory);
  22826. const Array <int> getPossibleSampleRates();
  22827. const Array <int> getPossibleBitDepths();
  22828. bool canDoStereo();
  22829. bool canDoMono();
  22830. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22831. const bool deleteStreamIfOpeningFails);
  22832. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22833. double sampleRateToUse,
  22834. unsigned int numberOfChannels,
  22835. int bitsPerSample,
  22836. const StringPairArray& metadataValues,
  22837. int qualityOptionIndex);
  22838. /** Utility function to replace the metadata in a wav file with a new set of values.
  22839. If possible, this cheats by overwriting just the metadata region of the file, rather
  22840. than by copying the whole file again.
  22841. */
  22842. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  22843. juce_UseDebuggingNewOperator
  22844. };
  22845. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  22846. /*** End of inlined file: juce_WavAudioFormat.h ***/
  22847. #endif
  22848. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22849. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  22850. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22851. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22852. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  22853. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22854. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22855. /**
  22856. A type of AudioSource which can be repositioned.
  22857. The basic AudioSource just streams continuously with no idea of a current
  22858. time or length, so the PositionableAudioSource is used for a finite stream
  22859. that has a current read position.
  22860. @see AudioSource, AudioTransportSource
  22861. */
  22862. class JUCE_API PositionableAudioSource : public AudioSource
  22863. {
  22864. protected:
  22865. /** Creates the PositionableAudioSource. */
  22866. PositionableAudioSource() throw() {}
  22867. public:
  22868. /** Destructor */
  22869. ~PositionableAudioSource() {}
  22870. /** Tells the stream to move to a new position.
  22871. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  22872. should return samples from this position.
  22873. Note that this may be called on a different thread to getNextAudioBlock(),
  22874. so the subclass should make sure it's synchronised.
  22875. */
  22876. virtual void setNextReadPosition (int newPosition) = 0;
  22877. /** Returns the position from which the next block will be returned.
  22878. @see setNextReadPosition
  22879. */
  22880. virtual int getNextReadPosition() const = 0;
  22881. /** Returns the total length of the stream (in samples). */
  22882. virtual int getTotalLength() const = 0;
  22883. /** Returns true if this source is actually playing in a loop. */
  22884. virtual bool isLooping() const = 0;
  22885. };
  22886. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  22887. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  22888. /**
  22889. A type of AudioSource that will read from an AudioFormatReader.
  22890. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  22891. */
  22892. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  22893. {
  22894. public:
  22895. /** Creates an AudioFormatReaderSource for a given reader.
  22896. @param sourceReader the reader to use as the data source
  22897. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  22898. when this object is deleted; if false it will be
  22899. left up to the caller to manage its lifetime
  22900. */
  22901. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  22902. const bool deleteReaderWhenThisIsDeleted);
  22903. /** Destructor. */
  22904. ~AudioFormatReaderSource();
  22905. /** Toggles loop-mode.
  22906. If set to true, it will continuously loop the input source. If false,
  22907. it will just emit silence after the source has finished.
  22908. @see isLooping
  22909. */
  22910. void setLooping (const bool shouldLoop) throw();
  22911. /** Returns whether loop-mode is turned on or not. */
  22912. bool isLooping() const { return looping; }
  22913. /** Returns the reader that's being used. */
  22914. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  22915. /** Implementation of the AudioSource method. */
  22916. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  22917. /** Implementation of the AudioSource method. */
  22918. void releaseResources();
  22919. /** Implementation of the AudioSource method. */
  22920. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  22921. /** Implements the PositionableAudioSource method. */
  22922. void setNextReadPosition (int newPosition);
  22923. /** Implements the PositionableAudioSource method. */
  22924. int getNextReadPosition() const;
  22925. /** Implements the PositionableAudioSource method. */
  22926. int getTotalLength() const;
  22927. juce_UseDebuggingNewOperator
  22928. private:
  22929. AudioFormatReader* reader;
  22930. bool deleteReader;
  22931. int volatile nextPlayPos;
  22932. bool volatile looping;
  22933. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  22934. AudioFormatReaderSource (const AudioFormatReaderSource&);
  22935. AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  22936. };
  22937. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  22938. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  22939. #endif
  22940. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  22941. #endif
  22942. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  22943. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  22944. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  22945. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  22946. /*** Start of inlined file: juce_AudioIODevice.h ***/
  22947. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22948. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  22949. class AudioIODevice;
  22950. /**
  22951. One of these is passed to an AudioIODevice object to stream the audio data
  22952. in and out.
  22953. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  22954. method on its own high-priority audio thread, when it needs to send or receive
  22955. the next block of data.
  22956. @see AudioIODevice, AudioDeviceManager
  22957. */
  22958. class JUCE_API AudioIODeviceCallback
  22959. {
  22960. public:
  22961. /** Destructor. */
  22962. virtual ~AudioIODeviceCallback() {}
  22963. /** Processes a block of incoming and outgoing audio data.
  22964. The subclass's implementation should use the incoming audio for whatever
  22965. purposes it needs to, and must fill all the output channels with the next
  22966. block of output data before returning.
  22967. The channel data is arranged with the same array indices as the channel name
  22968. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  22969. that aren't specified in AudioIODevice::open() will have a null pointer for their
  22970. associated channel, so remember to check for this.
  22971. @param inputChannelData a set of arrays containing the audio data for each
  22972. incoming channel - this data is valid until the function
  22973. returns. There will be one channel of data for each input
  22974. channel that was enabled when the audio device was opened
  22975. (see AudioIODevice::open())
  22976. @param numInputChannels the number of pointers to channel data in the
  22977. inputChannelData array.
  22978. @param outputChannelData a set of arrays which need to be filled with the data
  22979. that should be sent to each outgoing channel of the device.
  22980. There will be one channel of data for each output channel
  22981. that was enabled when the audio device was opened (see
  22982. AudioIODevice::open())
  22983. The initial contents of the array is undefined, so the
  22984. callback function must fill all the channels with zeros if
  22985. its output is silence. Failing to do this could cause quite
  22986. an unpleasant noise!
  22987. @param numOutputChannels the number of pointers to channel data in the
  22988. outputChannelData array.
  22989. @param numSamples the number of samples in each channel of the input and
  22990. output arrays. The number of samples will depend on the
  22991. audio device's buffer size and will usually remain constant,
  22992. although this isn't guaranteed, so make sure your code can
  22993. cope with reasonable changes in the buffer size from one
  22994. callback to the next.
  22995. */
  22996. virtual void audioDeviceIOCallback (const float** inputChannelData,
  22997. int numInputChannels,
  22998. float** outputChannelData,
  22999. int numOutputChannels,
  23000. int numSamples) = 0;
  23001. /** Called to indicate that the device is about to start calling back.
  23002. This will be called just before the audio callbacks begin, either when this
  23003. callback has just been added to an audio device, or after the device has been
  23004. restarted because of a sample-rate or block-size change.
  23005. You can use this opportunity to find out the sample rate and block size
  23006. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  23007. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  23008. @param device the audio IO device that will be used to drive the callback.
  23009. Note that if you're going to store this this pointer, it is
  23010. only valid until the next time that audioDeviceStopped is called.
  23011. */
  23012. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  23013. /** Called to indicate that the device has stopped.
  23014. */
  23015. virtual void audioDeviceStopped() = 0;
  23016. };
  23017. /**
  23018. Base class for an audio device with synchronised input and output channels.
  23019. Subclasses of this are used to implement different protocols such as DirectSound,
  23020. ASIO, CoreAudio, etc.
  23021. To create one of these, you'll need to use the AudioIODeviceType class - see the
  23022. documentation for that class for more info.
  23023. For an easier way of managing audio devices and their settings, have a look at the
  23024. AudioDeviceManager class.
  23025. @see AudioIODeviceType, AudioDeviceManager
  23026. */
  23027. class JUCE_API AudioIODevice
  23028. {
  23029. public:
  23030. /** Destructor. */
  23031. virtual ~AudioIODevice();
  23032. /** Returns the device's name, (as set in the constructor). */
  23033. const String& getName() const throw() { return name; }
  23034. /** Returns the type of the device.
  23035. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  23036. */
  23037. const String& getTypeName() const throw() { return typeName; }
  23038. /** Returns the names of all the available output channels on this device.
  23039. To find out which of these are currently in use, call getActiveOutputChannels().
  23040. */
  23041. virtual const StringArray getOutputChannelNames() = 0;
  23042. /** Returns the names of all the available input channels on this device.
  23043. To find out which of these are currently in use, call getActiveInputChannels().
  23044. */
  23045. virtual const StringArray getInputChannelNames() = 0;
  23046. /** Returns the number of sample-rates this device supports.
  23047. To find out which rates are available on this device, use this method to
  23048. find out how many there are, and getSampleRate() to get the rates.
  23049. @see getSampleRate
  23050. */
  23051. virtual int getNumSampleRates() = 0;
  23052. /** Returns one of the sample-rates this device supports.
  23053. To find out which rates are available on this device, use getNumSampleRates() to
  23054. find out how many there are, and getSampleRate() to get the individual rates.
  23055. The sample rate is set by the open() method.
  23056. (Note that for DirectSound some rates might not work, depending on combinations
  23057. of i/o channels that are being opened).
  23058. @see getNumSampleRates
  23059. */
  23060. virtual double getSampleRate (int index) = 0;
  23061. /** Returns the number of sizes of buffer that are available.
  23062. @see getBufferSizeSamples, getDefaultBufferSize
  23063. */
  23064. virtual int getNumBufferSizesAvailable() = 0;
  23065. /** Returns one of the possible buffer-sizes.
  23066. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  23067. @returns a number of samples
  23068. @see getNumBufferSizesAvailable, getDefaultBufferSize
  23069. */
  23070. virtual int getBufferSizeSamples (int index) = 0;
  23071. /** Returns the default buffer-size to use.
  23072. @returns a number of samples
  23073. @see getNumBufferSizesAvailable, getBufferSizeSamples
  23074. */
  23075. virtual int getDefaultBufferSize() = 0;
  23076. /** Tries to open the device ready to play.
  23077. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  23078. input channel should be enabled
  23079. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  23080. output channel should be enabled
  23081. @param sampleRate the sample rate to try to use - to find out which rates are
  23082. available, see getNumSampleRates() and getSampleRate()
  23083. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  23084. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  23085. @returns an error description if there's a problem, or an empty string if it succeeds in
  23086. opening the device
  23087. @see close
  23088. */
  23089. virtual const String open (const BigInteger& inputChannels,
  23090. const BigInteger& outputChannels,
  23091. double sampleRate,
  23092. int bufferSizeSamples) = 0;
  23093. /** Closes and releases the device if it's open. */
  23094. virtual void close() = 0;
  23095. /** Returns true if the device is still open.
  23096. A device might spontaneously close itself if something goes wrong, so this checks if
  23097. it's still open.
  23098. */
  23099. virtual bool isOpen() = 0;
  23100. /** Starts the device actually playing.
  23101. This must be called after the device has been opened.
  23102. @param callback the callback to use for streaming the data.
  23103. @see AudioIODeviceCallback, open
  23104. */
  23105. virtual void start (AudioIODeviceCallback* callback) = 0;
  23106. /** Stops the device playing.
  23107. Once a device has been started, this will stop it. Any pending calls to the
  23108. callback class will be flushed before this method returns.
  23109. */
  23110. virtual void stop() = 0;
  23111. /** Returns true if the device is still calling back.
  23112. The device might mysteriously stop, so this checks whether it's
  23113. still playing.
  23114. */
  23115. virtual bool isPlaying() = 0;
  23116. /** Returns the last error that happened if anything went wrong. */
  23117. virtual const String getLastError() = 0;
  23118. /** Returns the buffer size that the device is currently using.
  23119. If the device isn't actually open, this value doesn't really mean much.
  23120. */
  23121. virtual int getCurrentBufferSizeSamples() = 0;
  23122. /** Returns the sample rate that the device is currently using.
  23123. If the device isn't actually open, this value doesn't really mean much.
  23124. */
  23125. virtual double getCurrentSampleRate() = 0;
  23126. /** Returns the device's current physical bit-depth.
  23127. If the device isn't actually open, this value doesn't really mean much.
  23128. */
  23129. virtual int getCurrentBitDepth() = 0;
  23130. /** Returns a mask showing which of the available output channels are currently
  23131. enabled.
  23132. @see getOutputChannelNames
  23133. */
  23134. virtual const BigInteger getActiveOutputChannels() const = 0;
  23135. /** Returns a mask showing which of the available input channels are currently
  23136. enabled.
  23137. @see getInputChannelNames
  23138. */
  23139. virtual const BigInteger getActiveInputChannels() const = 0;
  23140. /** Returns the device's output latency.
  23141. This is the delay in samples between a callback getting a block of data, and
  23142. that data actually getting played.
  23143. */
  23144. virtual int getOutputLatencyInSamples() = 0;
  23145. /** Returns the device's input latency.
  23146. This is the delay in samples between some audio actually arriving at the soundcard,
  23147. and the callback getting passed this block of data.
  23148. */
  23149. virtual int getInputLatencyInSamples() = 0;
  23150. /** True if this device can show a pop-up control panel for editing its settings.
  23151. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  23152. to display it.
  23153. */
  23154. virtual bool hasControlPanel() const;
  23155. /** Shows a device-specific control panel if there is one.
  23156. This should only be called for devices which return true from hasControlPanel().
  23157. */
  23158. virtual bool showControlPanel();
  23159. protected:
  23160. /** Creates a device, setting its name and type member variables. */
  23161. AudioIODevice (const String& deviceName,
  23162. const String& typeName);
  23163. /** @internal */
  23164. String name, typeName;
  23165. };
  23166. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23167. /*** End of inlined file: juce_AudioIODevice.h ***/
  23168. /**
  23169. Wrapper class to continuously stream audio from an audio source to an
  23170. AudioIODevice.
  23171. This object acts as an AudioIODeviceCallback, so can be attached to an
  23172. output device, and will stream audio from an AudioSource.
  23173. */
  23174. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23175. {
  23176. public:
  23177. /** Creates an empty AudioSourcePlayer. */
  23178. AudioSourcePlayer();
  23179. /** Destructor.
  23180. Make sure this object isn't still being used by an AudioIODevice before
  23181. deleting it!
  23182. */
  23183. virtual ~AudioSourcePlayer();
  23184. /** Changes the current audio source to play from.
  23185. If the source passed in is already being used, this method will do nothing.
  23186. If the source is not null, its prepareToPlay() method will be called
  23187. before it starts being used for playback.
  23188. If there's another source currently playing, its releaseResources() method
  23189. will be called after it has been swapped for the new one.
  23190. @param newSource the new source to use - this will NOT be deleted
  23191. by this object when no longer needed, so it's the
  23192. caller's responsibility to manage it.
  23193. */
  23194. void setSource (AudioSource* newSource);
  23195. /** Returns the source that's playing.
  23196. May return 0 if there's no source.
  23197. */
  23198. AudioSource* getCurrentSource() const throw() { return source; }
  23199. /** Sets a gain to apply to the audio data. */
  23200. void setGain (const float newGain) throw();
  23201. /** Implementation of the AudioIODeviceCallback method. */
  23202. void audioDeviceIOCallback (const float** inputChannelData,
  23203. int totalNumInputChannels,
  23204. float** outputChannelData,
  23205. int totalNumOutputChannels,
  23206. int numSamples);
  23207. /** Implementation of the AudioIODeviceCallback method. */
  23208. void audioDeviceAboutToStart (AudioIODevice* device);
  23209. /** Implementation of the AudioIODeviceCallback method. */
  23210. void audioDeviceStopped();
  23211. juce_UseDebuggingNewOperator
  23212. private:
  23213. CriticalSection readLock;
  23214. AudioSource* source;
  23215. double sampleRate;
  23216. int bufferSize;
  23217. float* channels [128];
  23218. float* outputChans [128];
  23219. const float* inputChans [128];
  23220. AudioSampleBuffer tempBuffer;
  23221. float lastGain, gain;
  23222. AudioSourcePlayer (const AudioSourcePlayer&);
  23223. AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23224. };
  23225. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23226. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  23227. #endif
  23228. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23229. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  23230. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23231. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23232. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  23233. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23234. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23235. /**
  23236. An AudioSource which takes another source as input, and buffers it using a thread.
  23237. Create this as a wrapper around another thread, and it will read-ahead with
  23238. a background thread to smooth out playback. You can either create one of these
  23239. directly, or use it indirectly using an AudioTransportSource.
  23240. @see PositionableAudioSource, AudioTransportSource
  23241. */
  23242. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23243. {
  23244. public:
  23245. /** Creates a BufferingAudioSource.
  23246. @param source the input source to read from
  23247. @param deleteSourceWhenDeleted if true, then the input source object will
  23248. be deleted when this object is deleted
  23249. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23250. */
  23251. BufferingAudioSource (PositionableAudioSource* source,
  23252. const bool deleteSourceWhenDeleted,
  23253. int numberOfSamplesToBuffer);
  23254. /** Destructor.
  23255. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23256. flag was set in the constructor.
  23257. */
  23258. ~BufferingAudioSource();
  23259. /** Implementation of the AudioSource method. */
  23260. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23261. /** Implementation of the AudioSource method. */
  23262. void releaseResources();
  23263. /** Implementation of the AudioSource method. */
  23264. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23265. /** Implements the PositionableAudioSource method. */
  23266. void setNextReadPosition (int newPosition);
  23267. /** Implements the PositionableAudioSource method. */
  23268. int getNextReadPosition() const;
  23269. /** Implements the PositionableAudioSource method. */
  23270. int getTotalLength() const { return source->getTotalLength(); }
  23271. /** Implements the PositionableAudioSource method. */
  23272. bool isLooping() const { return source->isLooping(); }
  23273. juce_UseDebuggingNewOperator
  23274. private:
  23275. PositionableAudioSource* source;
  23276. bool deleteSourceWhenDeleted;
  23277. int numberOfSamplesToBuffer;
  23278. AudioSampleBuffer buffer;
  23279. CriticalSection bufferStartPosLock;
  23280. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23281. bool wasSourceLooping;
  23282. double volatile sampleRate;
  23283. friend class SharedBufferingAudioSourceThread;
  23284. bool readNextBufferChunk();
  23285. void readBufferSection (int start, int length, int bufferOffset);
  23286. BufferingAudioSource (const BufferingAudioSource&);
  23287. BufferingAudioSource& operator= (const BufferingAudioSource&);
  23288. };
  23289. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23290. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  23291. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  23292. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23293. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23294. /**
  23295. A type of AudioSource that takes an input source and changes its sample rate.
  23296. @see AudioSource
  23297. */
  23298. class JUCE_API ResamplingAudioSource : public AudioSource
  23299. {
  23300. public:
  23301. /** Creates a ResamplingAudioSource for a given input source.
  23302. @param inputSource the input source to read from
  23303. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23304. this object is deleted
  23305. */
  23306. ResamplingAudioSource (AudioSource* const inputSource,
  23307. const bool deleteInputWhenDeleted);
  23308. /** Destructor. */
  23309. ~ResamplingAudioSource();
  23310. /** Changes the resampling ratio.
  23311. (This value can be changed at any time, even while the source is running).
  23312. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  23313. values will speed it up; lower values will slow it
  23314. down. The ratio must be greater than 0
  23315. */
  23316. void setResamplingRatio (const double samplesInPerOutputSample);
  23317. /** Returns the current resampling ratio.
  23318. This is the value that was set by setResamplingRatio().
  23319. */
  23320. double getResamplingRatio() const throw() { return ratio; }
  23321. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23322. void releaseResources();
  23323. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23324. juce_UseDebuggingNewOperator
  23325. private:
  23326. AudioSource* const input;
  23327. const bool deleteInputWhenDeleted;
  23328. double ratio, lastRatio;
  23329. AudioSampleBuffer buffer;
  23330. int bufferPos, sampsInBuffer;
  23331. double subSampleOffset;
  23332. double coefficients[6];
  23333. CriticalSection ratioLock;
  23334. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  23335. void createLowPass (const double proportionalRate);
  23336. struct FilterState
  23337. {
  23338. double x1, x2, y1, y2;
  23339. };
  23340. FilterState filterStates[2];
  23341. void resetFilters();
  23342. void applyFilter (float* samples, int num, FilterState& fs);
  23343. ResamplingAudioSource (const ResamplingAudioSource&);
  23344. ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  23345. };
  23346. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23347. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  23348. /**
  23349. An AudioSource that takes a PositionableAudioSource and allows it to be
  23350. played, stopped, started, etc.
  23351. This can also be told use a buffer and background thread to read ahead, and
  23352. if can correct for different sample-rates.
  23353. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  23354. to control playback of an audio file.
  23355. @see AudioSource, AudioSourcePlayer
  23356. */
  23357. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  23358. public ChangeBroadcaster
  23359. {
  23360. public:
  23361. /** Creates an AudioTransportSource.
  23362. After creating one of these, use the setSource() method to select an input source.
  23363. */
  23364. AudioTransportSource();
  23365. /** Destructor. */
  23366. ~AudioTransportSource();
  23367. /** Sets the reader that is being used as the input source.
  23368. This will stop playback, reset the position to 0 and change to the new reader.
  23369. The source passed in will not be deleted by this object, so must be managed by
  23370. the caller.
  23371. @param newSource the new input source to use. This may be zero
  23372. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  23373. is zero, no reading ahead will be done; if it's
  23374. greater than zero, a BufferingAudioSource will be used
  23375. to do the reading-ahead
  23376. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  23377. rate of the source, and playback will be sample-rate
  23378. adjusted to maintain playback at the correct pitch. If
  23379. this is 0, no sample-rate adjustment will be performed
  23380. */
  23381. void setSource (PositionableAudioSource* const newSource,
  23382. int readAheadBufferSize = 0,
  23383. double sourceSampleRateToCorrectFor = 0.0);
  23384. /** Changes the current playback position in the source stream.
  23385. The next time the getNextAudioBlock() method is called, this
  23386. is the time from which it'll read data.
  23387. @see getPosition
  23388. */
  23389. void setPosition (double newPosition);
  23390. /** Returns the position that the next data block will be read from
  23391. This is a time in seconds.
  23392. */
  23393. double getCurrentPosition() const;
  23394. /** Returns true if the player has stopped because its input stream ran out of data.
  23395. */
  23396. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  23397. /** Starts playing (if a source has been selected).
  23398. If it starts playing, this will send a message to any ChangeListeners
  23399. that are registered with this object.
  23400. */
  23401. void start();
  23402. /** Stops playing.
  23403. If it's actually playing, this will send a message to any ChangeListeners
  23404. that are registered with this object.
  23405. */
  23406. void stop();
  23407. /** Returns true if it's currently playing. */
  23408. bool isPlaying() const throw() { return playing; }
  23409. /** Changes the gain to apply to the output.
  23410. @param newGain a factor by which to multiply the outgoing samples,
  23411. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  23412. */
  23413. void setGain (const float newGain) throw();
  23414. /** Returns the current gain setting.
  23415. @see setGain
  23416. */
  23417. float getGain() const throw() { return gain; }
  23418. /** Implementation of the AudioSource method. */
  23419. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23420. /** Implementation of the AudioSource method. */
  23421. void releaseResources();
  23422. /** Implementation of the AudioSource method. */
  23423. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23424. /** Implements the PositionableAudioSource method. */
  23425. void setNextReadPosition (int newPosition);
  23426. /** Implements the PositionableAudioSource method. */
  23427. int getNextReadPosition() const;
  23428. /** Implements the PositionableAudioSource method. */
  23429. int getTotalLength() const;
  23430. /** Implements the PositionableAudioSource method. */
  23431. bool isLooping() const;
  23432. juce_UseDebuggingNewOperator
  23433. private:
  23434. PositionableAudioSource* source;
  23435. ResamplingAudioSource* resamplerSource;
  23436. BufferingAudioSource* bufferingSource;
  23437. PositionableAudioSource* positionableSource;
  23438. AudioSource* masterSource;
  23439. CriticalSection callbackLock;
  23440. float volatile gain, lastGain;
  23441. bool volatile playing, stopped;
  23442. double sampleRate, sourceSampleRate;
  23443. int blockSize, readAheadBufferSize;
  23444. bool isPrepared, inputStreamEOF;
  23445. AudioTransportSource (const AudioTransportSource&);
  23446. AudioTransportSource& operator= (const AudioTransportSource&);
  23447. };
  23448. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23449. /*** End of inlined file: juce_AudioTransportSource.h ***/
  23450. #endif
  23451. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23452. #endif
  23453. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23454. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  23455. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23456. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23457. /**
  23458. An AudioSource that takes the audio from another source, and re-maps its
  23459. input and output channels to a different arrangement.
  23460. You can use this to increase or decrease the number of channels that an
  23461. audio source uses, or to re-order those channels.
  23462. Call the reset() method before using it to set up a default mapping, and then
  23463. the setInputChannelMapping() and setOutputChannelMapping() methods to
  23464. create an appropriate mapping, otherwise no channels will be connected and
  23465. it'll produce silence.
  23466. @see AudioSource
  23467. */
  23468. class ChannelRemappingAudioSource : public AudioSource
  23469. {
  23470. public:
  23471. /** Creates a remapping source that will pass on audio from the given input.
  23472. @param source the input source to use. Make sure that this doesn't
  23473. get deleted before the ChannelRemappingAudioSource object
  23474. @param deleteSourceWhenDeleted if true, the input source will be deleted
  23475. when this object is deleted, if false, the caller is
  23476. responsible for its deletion
  23477. */
  23478. ChannelRemappingAudioSource (AudioSource* const source,
  23479. const bool deleteSourceWhenDeleted);
  23480. /** Destructor. */
  23481. ~ChannelRemappingAudioSource();
  23482. /** Specifies a number of channels that this audio source must produce from its
  23483. getNextAudioBlock() callback.
  23484. */
  23485. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  23486. /** Clears any mapped channels.
  23487. After this, no channels are mapped, so this object will produce silence. Create
  23488. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  23489. */
  23490. void clearAllMappings() throw();
  23491. /** Creates an input channel mapping.
  23492. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  23493. data will be sent to destChannelIndex of our input source.
  23494. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  23495. source specified when this object was created).
  23496. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  23497. during our getNextAudioBlock() callback
  23498. */
  23499. void setInputChannelMapping (const int destChannelIndex,
  23500. const int sourceChannelIndex) throw();
  23501. /** Creates an output channel mapping.
  23502. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  23503. our input audio source will be copied to channel destChannelIndex of the final buffer.
  23504. @param sourceChannelIndex the index of an output channel coming from our input audio source
  23505. (i.e. the source specified when this object was created).
  23506. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  23507. during our getNextAudioBlock() callback
  23508. */
  23509. void setOutputChannelMapping (const int sourceChannelIndex,
  23510. const int destChannelIndex) throw();
  23511. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  23512. our input audio source.
  23513. */
  23514. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  23515. /** Returns the output channel to which channel outputChannelIndex of our input audio
  23516. source will be sent to.
  23517. */
  23518. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  23519. /** Returns an XML object to encapsulate the state of the mappings.
  23520. @see restoreFromXml
  23521. */
  23522. XmlElement* createXml() const throw();
  23523. /** Restores the mappings from an XML object created by createXML().
  23524. @see createXml
  23525. */
  23526. void restoreFromXml (const XmlElement& e) throw();
  23527. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23528. void releaseResources();
  23529. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23530. juce_UseDebuggingNewOperator
  23531. private:
  23532. int requiredNumberOfChannels;
  23533. Array <int> remappedInputs, remappedOutputs;
  23534. AudioSource* const source;
  23535. const bool deleteSourceWhenDeleted;
  23536. AudioSampleBuffer buffer;
  23537. AudioSourceChannelInfo remappedInfo;
  23538. CriticalSection lock;
  23539. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  23540. ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  23541. };
  23542. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  23543. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  23544. #endif
  23545. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23546. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  23547. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23548. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23549. /*** Start of inlined file: juce_IIRFilter.h ***/
  23550. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  23551. #define __JUCE_IIRFILTER_JUCEHEADER__
  23552. /**
  23553. An IIR filter that can perform low, high, or band-pass filtering on an
  23554. audio signal.
  23555. @see IIRFilterAudioSource
  23556. */
  23557. class JUCE_API IIRFilter
  23558. {
  23559. public:
  23560. /** Creates a filter.
  23561. Initially the filter is inactive, so will have no effect on samples that
  23562. you process with it. Use the appropriate method to turn it into the type
  23563. of filter needed.
  23564. */
  23565. IIRFilter();
  23566. /** Creates a copy of another filter. */
  23567. IIRFilter (const IIRFilter& other);
  23568. /** Destructor. */
  23569. ~IIRFilter();
  23570. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  23571. Note that this clears the processing state, but the type of filter and
  23572. its coefficients aren't changed. To put a filter into an inactive state, use
  23573. the makeInactive() method.
  23574. */
  23575. void reset() throw();
  23576. /** Performs the filter operation on the given set of samples.
  23577. */
  23578. void processSamples (float* samples,
  23579. int numSamples) throw();
  23580. /** Processes a single sample, without any locking or checking.
  23581. Use this if you need fast processing of a single value, but be aware that
  23582. this isn't thread-safe in the way that processSamples() is.
  23583. */
  23584. float processSingleSampleRaw (float sample) throw();
  23585. /** Sets the filter up to act as a low-pass filter.
  23586. */
  23587. void makeLowPass (double sampleRate,
  23588. double frequency) throw();
  23589. /** Sets the filter up to act as a high-pass filter.
  23590. */
  23591. void makeHighPass (double sampleRate,
  23592. double frequency) throw();
  23593. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  23594. The gain is a scale factor that the low frequencies are multiplied by, so values
  23595. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  23596. attenuate them.
  23597. */
  23598. void makeLowShelf (double sampleRate,
  23599. double cutOffFrequency,
  23600. double Q,
  23601. float gainFactor) throw();
  23602. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  23603. The gain is a scale factor that the high frequencies are multiplied by, so values
  23604. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  23605. attenuate them.
  23606. */
  23607. void makeHighShelf (double sampleRate,
  23608. double cutOffFrequency,
  23609. double Q,
  23610. float gainFactor) throw();
  23611. /** Sets the filter up to act as a band pass filter centred around a
  23612. frequency, with a variable Q and gain.
  23613. The gain is a scale factor that the centre frequencies are multiplied by, so
  23614. values greater than 1.0 will boost the centre frequencies, values less than
  23615. 1.0 will attenuate them.
  23616. */
  23617. void makeBandPass (double sampleRate,
  23618. double centreFrequency,
  23619. double Q,
  23620. float gainFactor) throw();
  23621. /** Clears the filter's coefficients so that it becomes inactive.
  23622. */
  23623. void makeInactive() throw();
  23624. /** Makes this filter duplicate the set-up of another one.
  23625. */
  23626. void copyCoefficientsFrom (const IIRFilter& other) throw();
  23627. juce_UseDebuggingNewOperator
  23628. protected:
  23629. CriticalSection processLock;
  23630. void setCoefficients (double c1, double c2, double c3,
  23631. double c4, double c5, double c6) throw();
  23632. bool active;
  23633. float coefficients[6];
  23634. float x1, x2, y1, y2;
  23635. // (use the copyCoefficientsFrom() method instead of this operator)
  23636. IIRFilter& operator= (const IIRFilter&);
  23637. };
  23638. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  23639. /*** End of inlined file: juce_IIRFilter.h ***/
  23640. /**
  23641. An AudioSource that performs an IIR filter on another source.
  23642. */
  23643. class JUCE_API IIRFilterAudioSource : public AudioSource
  23644. {
  23645. public:
  23646. /** Creates a IIRFilterAudioSource for a given input source.
  23647. @param inputSource the input source to read from
  23648. @param deleteInputWhenDeleted if true, the input source will be deleted when
  23649. this object is deleted
  23650. */
  23651. IIRFilterAudioSource (AudioSource* const inputSource,
  23652. const bool deleteInputWhenDeleted);
  23653. /** Destructor. */
  23654. ~IIRFilterAudioSource();
  23655. /** Changes the filter to use the same parameters as the one being passed in.
  23656. */
  23657. void setFilterParameters (const IIRFilter& newSettings);
  23658. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23659. void releaseResources();
  23660. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23661. juce_UseDebuggingNewOperator
  23662. private:
  23663. AudioSource* const input;
  23664. const bool deleteInputWhenDeleted;
  23665. OwnedArray <IIRFilter> iirFilters;
  23666. IIRFilterAudioSource (const IIRFilterAudioSource&);
  23667. IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  23668. };
  23669. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  23670. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  23671. #endif
  23672. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23673. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  23674. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23675. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23676. /**
  23677. An AudioSource that mixes together the output of a set of other AudioSources.
  23678. Input sources can be added and removed while the mixer is running as long as their
  23679. prepareToPlay() and releaseResources() methods are called before and after adding
  23680. them to the mixer.
  23681. */
  23682. class JUCE_API MixerAudioSource : public AudioSource
  23683. {
  23684. public:
  23685. /** Creates a MixerAudioSource.
  23686. */
  23687. MixerAudioSource();
  23688. /** Destructor. */
  23689. ~MixerAudioSource();
  23690. /** Adds an input source to the mixer.
  23691. If the mixer is running you'll need to make sure that the input source
  23692. is ready to play by calling its prepareToPlay() method before adding it.
  23693. If the mixer is stopped, then its input sources will be automatically
  23694. prepared when the mixer's prepareToPlay() method is called.
  23695. @param newInput the source to add to the mixer
  23696. @param deleteWhenRemoved if true, then this source will be deleted when
  23697. the mixer is deleted or when removeAllInputs() is
  23698. called (unless the source is previously removed
  23699. with the removeInputSource method)
  23700. */
  23701. void addInputSource (AudioSource* newInput,
  23702. const bool deleteWhenRemoved);
  23703. /** Removes an input source.
  23704. If the mixer is running, this will remove the source but not call its
  23705. releaseResources() method, so the caller might want to do this manually.
  23706. @param input the source to remove
  23707. @param deleteSource whether to delete this source after it's been removed
  23708. */
  23709. void removeInputSource (AudioSource* input,
  23710. const bool deleteSource);
  23711. /** Removes all the input sources.
  23712. If the mixer is running, this will remove the sources but not call their
  23713. releaseResources() method, so the caller might want to do this manually.
  23714. Any sources which were added with the deleteWhenRemoved flag set will be
  23715. deleted by this method.
  23716. */
  23717. void removeAllInputs();
  23718. /** Implementation of the AudioSource method.
  23719. This will call prepareToPlay() on all its input sources.
  23720. */
  23721. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23722. /** Implementation of the AudioSource method.
  23723. This will call releaseResources() on all its input sources.
  23724. */
  23725. void releaseResources();
  23726. /** Implementation of the AudioSource method. */
  23727. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23728. juce_UseDebuggingNewOperator
  23729. private:
  23730. Array <AudioSource*> inputs;
  23731. BigInteger inputsToDelete;
  23732. CriticalSection lock;
  23733. AudioSampleBuffer tempBuffer;
  23734. double currentSampleRate;
  23735. int bufferSizeExpected;
  23736. MixerAudioSource (const MixerAudioSource&);
  23737. MixerAudioSource& operator= (const MixerAudioSource&);
  23738. };
  23739. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  23740. /*** End of inlined file: juce_MixerAudioSource.h ***/
  23741. #endif
  23742. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23743. #endif
  23744. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23745. #endif
  23746. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23747. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  23748. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23749. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23750. /**
  23751. A simple AudioSource that generates a sine wave.
  23752. */
  23753. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  23754. {
  23755. public:
  23756. /** Creates a ToneGeneratorAudioSource. */
  23757. ToneGeneratorAudioSource();
  23758. /** Destructor. */
  23759. ~ToneGeneratorAudioSource();
  23760. /** Sets the signal's amplitude. */
  23761. void setAmplitude (const float newAmplitude);
  23762. /** Sets the signal's frequency. */
  23763. void setFrequency (const double newFrequencyHz);
  23764. /** Implementation of the AudioSource method. */
  23765. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23766. /** Implementation of the AudioSource method. */
  23767. void releaseResources();
  23768. /** Implementation of the AudioSource method. */
  23769. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23770. juce_UseDebuggingNewOperator
  23771. private:
  23772. double frequency, sampleRate;
  23773. double currentPhase, phasePerSample;
  23774. float amplitude;
  23775. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  23776. ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  23777. };
  23778. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  23779. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  23780. #endif
  23781. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23782. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  23783. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23784. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  23785. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  23786. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23787. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23788. class AudioDeviceManager;
  23789. class Component;
  23790. /**
  23791. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  23792. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  23793. method. Each of the objects returned can then be used to list the available
  23794. devices of that type. E.g.
  23795. @code
  23796. OwnedArray <AudioIODeviceType> types;
  23797. myAudioDeviceManager.createAudioDeviceTypes (types);
  23798. for (int i = 0; i < types.size(); ++i)
  23799. {
  23800. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  23801. types[i]->scanForDevices(); // This must be called before getting the list of devices
  23802. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  23803. for (int j = 0; j < deviceNames.size(); ++j)
  23804. {
  23805. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  23806. ...
  23807. }
  23808. }
  23809. @endcode
  23810. For an easier way of managing audio devices and their settings, have a look at the
  23811. AudioDeviceManager class.
  23812. @see AudioIODevice, AudioDeviceManager
  23813. */
  23814. class JUCE_API AudioIODeviceType
  23815. {
  23816. public:
  23817. /** Returns the name of this type of driver that this object manages.
  23818. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  23819. */
  23820. const String& getTypeName() const throw() { return typeName; }
  23821. /** Refreshes the object's cached list of known devices.
  23822. This must be called at least once before calling getDeviceNames() or any of
  23823. the other device creation methods.
  23824. */
  23825. virtual void scanForDevices() = 0;
  23826. /** Returns the list of available devices of this type.
  23827. The scanForDevices() method must have been called to create this list.
  23828. @param wantInputNames only really used by DirectSound where devices are split up
  23829. into inputs and outputs, this indicates whether to use
  23830. the input or output name to refer to a pair of devices.
  23831. */
  23832. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  23833. /** Returns the name of the default device.
  23834. This will be one of the names from the getDeviceNames() list.
  23835. @param forInput if true, this means that a default input device should be
  23836. returned; if false, it should return the default output
  23837. */
  23838. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  23839. /** Returns the index of a given device in the list of device names.
  23840. If asInput is true, it shows the index in the inputs list, otherwise it
  23841. looks for it in the outputs list.
  23842. */
  23843. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  23844. /** Returns true if two different devices can be used for the input and output.
  23845. */
  23846. virtual bool hasSeparateInputsAndOutputs() const = 0;
  23847. /** Creates one of the devices of this type.
  23848. The deviceName must be one of the strings returned by getDeviceNames(), and
  23849. scanForDevices() must have been called before this method is used.
  23850. */
  23851. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  23852. const String& inputDeviceName) = 0;
  23853. struct DeviceSetupDetails
  23854. {
  23855. AudioDeviceManager* manager;
  23856. int minNumInputChannels, maxNumInputChannels;
  23857. int minNumOutputChannels, maxNumOutputChannels;
  23858. bool useStereoPairs;
  23859. };
  23860. /** Destructor. */
  23861. virtual ~AudioIODeviceType();
  23862. protected:
  23863. explicit AudioIODeviceType (const String& typeName);
  23864. private:
  23865. String typeName;
  23866. AudioIODeviceType (const AudioIODeviceType&);
  23867. AudioIODeviceType& operator= (const AudioIODeviceType&);
  23868. };
  23869. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  23870. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  23871. /*** Start of inlined file: juce_MidiInput.h ***/
  23872. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  23873. #define __JUCE_MIDIINPUT_JUCEHEADER__
  23874. /*** Start of inlined file: juce_MidiMessage.h ***/
  23875. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  23876. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  23877. /**
  23878. Encapsulates a MIDI message.
  23879. @see MidiMessageSequence, MidiOutput, MidiInput
  23880. */
  23881. class JUCE_API MidiMessage
  23882. {
  23883. public:
  23884. /** Creates a 3-byte short midi message.
  23885. @param byte1 message byte 1
  23886. @param byte2 message byte 2
  23887. @param byte3 message byte 3
  23888. @param timeStamp the time to give the midi message - this value doesn't
  23889. use any particular units, so will be application-specific
  23890. */
  23891. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  23892. /** Creates a 2-byte short midi message.
  23893. @param byte1 message byte 1
  23894. @param byte2 message byte 2
  23895. @param timeStamp the time to give the midi message - this value doesn't
  23896. use any particular units, so will be application-specific
  23897. */
  23898. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  23899. /** Creates a 1-byte short midi message.
  23900. @param byte1 message byte 1
  23901. @param timeStamp the time to give the midi message - this value doesn't
  23902. use any particular units, so will be application-specific
  23903. */
  23904. MidiMessage (int byte1, double timeStamp = 0) throw();
  23905. /** Creates a midi message from a block of data. */
  23906. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  23907. /** Reads the next midi message from some data.
  23908. This will read as many bytes from a data stream as it needs to make a
  23909. complete message, and will return the number of bytes it used. This lets
  23910. you read a sequence of midi messages from a file or stream.
  23911. @param data the data to read from
  23912. @param maxBytesToUse the maximum number of bytes it's allowed to read
  23913. @param numBytesUsed returns the number of bytes that were actually needed
  23914. @param lastStatusByte in a sequence of midi messages, the initial byte
  23915. can be dropped from a message if it's the same as the
  23916. first byte of the previous message, so this lets you
  23917. supply the byte to use if the first byte of the message
  23918. has in fact been dropped.
  23919. @param timeStamp the time to give the midi message - this value doesn't
  23920. use any particular units, so will be application-specific
  23921. */
  23922. MidiMessage (const void* data, int maxBytesToUse,
  23923. int& numBytesUsed, uint8 lastStatusByte,
  23924. double timeStamp = 0);
  23925. /** Creates a copy of another midi message. */
  23926. MidiMessage (const MidiMessage& other);
  23927. /** Creates a copy of another midi message, with a different timestamp. */
  23928. MidiMessage (const MidiMessage& other, double newTimeStamp);
  23929. /** Destructor. */
  23930. ~MidiMessage();
  23931. /** Copies this message from another one. */
  23932. MidiMessage& operator= (const MidiMessage& other);
  23933. /** Returns a pointer to the raw midi data.
  23934. @see getRawDataSize
  23935. */
  23936. uint8* getRawData() const throw() { return data; }
  23937. /** Returns the number of bytes of data in the message.
  23938. @see getRawData
  23939. */
  23940. int getRawDataSize() const throw() { return size; }
  23941. /** Returns the timestamp associated with this message.
  23942. The exact meaning of this time and its units will vary, as messages are used in
  23943. a variety of different contexts.
  23944. If you're getting the message from a midi file, this could be a time in seconds, or
  23945. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  23946. If the message is being used in a MidiBuffer, it might indicate the number of
  23947. audio samples from the start of the buffer.
  23948. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  23949. for details of the way that it initialises this value.
  23950. @see setTimeStamp, addToTimeStamp
  23951. */
  23952. double getTimeStamp() const throw() { return timeStamp; }
  23953. /** Changes the message's associated timestamp.
  23954. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  23955. @see addToTimeStamp, getTimeStamp
  23956. */
  23957. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  23958. /** Adds a value to the message's timestamp.
  23959. The units for the timestamp will be application-specific.
  23960. */
  23961. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  23962. /** Returns the midi channel associated with the message.
  23963. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  23964. if it's a sysex)
  23965. @see isForChannel, setChannel
  23966. */
  23967. int getChannel() const throw();
  23968. /** Returns true if the message applies to the given midi channel.
  23969. @param channelNumber the channel number to look for, in the range 1 to 16
  23970. @see getChannel, setChannel
  23971. */
  23972. bool isForChannel (int channelNumber) const throw();
  23973. /** Changes the message's midi channel.
  23974. This won't do anything for non-channel messages like sysexes.
  23975. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  23976. */
  23977. void setChannel (int newChannelNumber) throw();
  23978. /** Returns true if this is a system-exclusive message.
  23979. */
  23980. bool isSysEx() const throw();
  23981. /** Returns a pointer to the sysex data inside the message.
  23982. If this event isn't a sysex event, it'll return 0.
  23983. @see getSysExDataSize
  23984. */
  23985. const uint8* getSysExData() const throw();
  23986. /** Returns the size of the sysex data.
  23987. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  23988. @see getSysExData
  23989. */
  23990. int getSysExDataSize() const throw();
  23991. /** Returns true if this message is a 'key-down' event.
  23992. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  23993. velocity 0, it will still be considered to be a note-on and the
  23994. method will return true. If returnTrueForVelocity0 is false, then
  23995. if this is a note-on event with velocity 0, it'll be regarded as
  23996. a note-off, and the method will return false
  23997. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  23998. */
  23999. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  24000. /** Creates a key-down message (using a floating-point velocity).
  24001. @param channel the midi channel, in the range 1 to 16
  24002. @param noteNumber the key number, 0 to 127
  24003. @param velocity in the range 0 to 1.0
  24004. @see isNoteOn
  24005. */
  24006. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  24007. /** Creates a key-down message (using an integer velocity).
  24008. @param channel the midi channel, in the range 1 to 16
  24009. @param noteNumber the key number, 0 to 127
  24010. @param velocity in the range 0 to 127
  24011. @see isNoteOn
  24012. */
  24013. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  24014. /** Returns true if this message is a 'key-up' event.
  24015. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  24016. for a note-on event with a velocity of 0.
  24017. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  24018. */
  24019. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  24020. /** Creates a key-up message.
  24021. @param channel the midi channel, in the range 1 to 16
  24022. @param noteNumber the key number, 0 to 127
  24023. @see isNoteOff
  24024. */
  24025. static const MidiMessage noteOff (int channel, int noteNumber) throw();
  24026. /** Returns true if this message is a 'key-down' or 'key-up' event.
  24027. @see isNoteOn, isNoteOff
  24028. */
  24029. bool isNoteOnOrOff() const throw();
  24030. /** Returns the midi note number for note-on and note-off messages.
  24031. If the message isn't a note-on or off, the value returned will be
  24032. meaningless.
  24033. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  24034. */
  24035. int getNoteNumber() const throw();
  24036. /** Changes the midi note number of a note-on or note-off message.
  24037. If the message isn't a note on or off, this will do nothing.
  24038. */
  24039. void setNoteNumber (int newNoteNumber) throw();
  24040. /** Returns the velocity of a note-on or note-off message.
  24041. The value returned will be in the range 0 to 127.
  24042. If the message isn't a note-on or off event, it will return 0.
  24043. @see getFloatVelocity
  24044. */
  24045. uint8 getVelocity() const throw();
  24046. /** Returns the velocity of a note-on or note-off message.
  24047. The value returned will be in the range 0 to 1.0
  24048. If the message isn't a note-on or off event, it will return 0.
  24049. @see getVelocity, setVelocity
  24050. */
  24051. float getFloatVelocity() const throw();
  24052. /** Changes the velocity of a note-on or note-off message.
  24053. If the message isn't a note on or off, this will do nothing.
  24054. @param newVelocity the new velocity, in the range 0 to 1.0
  24055. @see getFloatVelocity, multiplyVelocity
  24056. */
  24057. void setVelocity (float newVelocity) throw();
  24058. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  24059. If the message isn't a note on or off, this will do nothing.
  24060. @param scaleFactor the value by which to multiply the velocity
  24061. @see setVelocity
  24062. */
  24063. void multiplyVelocity (float scaleFactor) throw();
  24064. /** Returns true if the message is a program (patch) change message.
  24065. @see getProgramChangeNumber, getGMInstrumentName
  24066. */
  24067. bool isProgramChange() const throw();
  24068. /** Returns the new program number of a program change message.
  24069. If the message isn't a program change, the value returned will be
  24070. nonsense.
  24071. @see isProgramChange, getGMInstrumentName
  24072. */
  24073. int getProgramChangeNumber() const throw();
  24074. /** Creates a program-change message.
  24075. @param channel the midi channel, in the range 1 to 16
  24076. @param programNumber the midi program number, 0 to 127
  24077. @see isProgramChange, getGMInstrumentName
  24078. */
  24079. static const MidiMessage programChange (int channel, int programNumber) throw();
  24080. /** Returns true if the message is a pitch-wheel move.
  24081. @see getPitchWheelValue, pitchWheel
  24082. */
  24083. bool isPitchWheel() const throw();
  24084. /** Returns the pitch wheel position from a pitch-wheel move message.
  24085. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  24086. If called for messages which aren't pitch wheel events, the number returned will be
  24087. nonsense.
  24088. @see isPitchWheel
  24089. */
  24090. int getPitchWheelValue() const throw();
  24091. /** Creates a pitch-wheel move message.
  24092. @param channel the midi channel, in the range 1 to 16
  24093. @param position the wheel position, in the range 0 to 16383
  24094. @see isPitchWheel
  24095. */
  24096. static const MidiMessage pitchWheel (int channel, int position) throw();
  24097. /** Returns true if the message is an aftertouch event.
  24098. For aftertouch events, use the getNoteNumber() method to find out the key
  24099. that it applies to, and getAftertouchValue() to find out the amount. Use
  24100. getChannel() to find out the channel.
  24101. @see getAftertouchValue, getNoteNumber
  24102. */
  24103. bool isAftertouch() const throw();
  24104. /** Returns the amount of aftertouch from an aftertouch messages.
  24105. The value returned is in the range 0 to 127, and will be nonsense for messages
  24106. other than aftertouch messages.
  24107. @see isAftertouch
  24108. */
  24109. int getAfterTouchValue() const throw();
  24110. /** Creates an aftertouch message.
  24111. @param channel the midi channel, in the range 1 to 16
  24112. @param noteNumber the key number, 0 to 127
  24113. @param aftertouchAmount the amount of aftertouch, 0 to 127
  24114. @see isAftertouch
  24115. */
  24116. static const MidiMessage aftertouchChange (int channel,
  24117. int noteNumber,
  24118. int aftertouchAmount) throw();
  24119. /** Returns true if the message is a channel-pressure change event.
  24120. This is like aftertouch, but common to the whole channel rather than a specific
  24121. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  24122. to find out the channel.
  24123. @see channelPressureChange
  24124. */
  24125. bool isChannelPressure() const throw();
  24126. /** Returns the pressure from a channel pressure change message.
  24127. @returns the pressure, in the range 0 to 127
  24128. @see isChannelPressure, channelPressureChange
  24129. */
  24130. int getChannelPressureValue() const throw();
  24131. /** Creates a channel-pressure change event.
  24132. @param channel the midi channel: 1 to 16
  24133. @param pressure the pressure, 0 to 127
  24134. @see isChannelPressure
  24135. */
  24136. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  24137. /** Returns true if this is a midi controller message.
  24138. @see getControllerNumber, getControllerValue, controllerEvent
  24139. */
  24140. bool isController() const throw();
  24141. /** Returns the controller number of a controller message.
  24142. The name of the controller can be looked up using the getControllerName() method.
  24143. Note that the value returned is invalid for messages that aren't controller changes.
  24144. @see isController, getControllerName, getControllerValue
  24145. */
  24146. int getControllerNumber() const throw();
  24147. /** Returns the controller value from a controller message.
  24148. A value 0 to 127 is returned to indicate the new controller position.
  24149. Note that the value returned is invalid for messages that aren't controller changes.
  24150. @see isController, getControllerNumber
  24151. */
  24152. int getControllerValue() const throw();
  24153. /** Creates a controller message.
  24154. @param channel the midi channel, in the range 1 to 16
  24155. @param controllerType the type of controller
  24156. @param value the controller value
  24157. @see isController
  24158. */
  24159. static const MidiMessage controllerEvent (int channel,
  24160. int controllerType,
  24161. int value) throw();
  24162. /** Checks whether this message is an all-notes-off message.
  24163. @see allNotesOff
  24164. */
  24165. bool isAllNotesOff() const throw();
  24166. /** Checks whether this message is an all-sound-off message.
  24167. @see allSoundOff
  24168. */
  24169. bool isAllSoundOff() const throw();
  24170. /** Creates an all-notes-off message.
  24171. @param channel the midi channel, in the range 1 to 16
  24172. @see isAllNotesOff
  24173. */
  24174. static const MidiMessage allNotesOff (int channel) throw();
  24175. /** Creates an all-sound-off message.
  24176. @param channel the midi channel, in the range 1 to 16
  24177. @see isAllSoundOff
  24178. */
  24179. static const MidiMessage allSoundOff (int channel) throw();
  24180. /** Creates an all-controllers-off message.
  24181. @param channel the midi channel, in the range 1 to 16
  24182. */
  24183. static const MidiMessage allControllersOff (int channel) throw();
  24184. /** Returns true if this event is a meta-event.
  24185. Meta-events are things like tempo changes, track names, etc.
  24186. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24187. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24188. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24189. */
  24190. bool isMetaEvent() const throw();
  24191. /** Returns a meta-event's type number.
  24192. If the message isn't a meta-event, this will return -1.
  24193. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24194. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24195. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24196. */
  24197. int getMetaEventType() const throw();
  24198. /** Returns a pointer to the data in a meta-event.
  24199. @see isMetaEvent, getMetaEventLength
  24200. */
  24201. const uint8* getMetaEventData() const throw();
  24202. /** Returns the length of the data for a meta-event.
  24203. @see isMetaEvent, getMetaEventData
  24204. */
  24205. int getMetaEventLength() const throw();
  24206. /** Returns true if this is a 'track' meta-event. */
  24207. bool isTrackMetaEvent() const throw();
  24208. /** Returns true if this is an 'end-of-track' meta-event. */
  24209. bool isEndOfTrackMetaEvent() const throw();
  24210. /** Creates an end-of-track meta-event.
  24211. @see isEndOfTrackMetaEvent
  24212. */
  24213. static const MidiMessage endOfTrack() throw();
  24214. /** Returns true if this is an 'track name' meta-event.
  24215. You can use the getTextFromTextMetaEvent() method to get the track's name.
  24216. */
  24217. bool isTrackNameEvent() const throw();
  24218. /** Returns true if this is a 'text' meta-event.
  24219. @see getTextFromTextMetaEvent
  24220. */
  24221. bool isTextMetaEvent() const throw();
  24222. /** Returns the text from a text meta-event.
  24223. @see isTextMetaEvent
  24224. */
  24225. const String getTextFromTextMetaEvent() const;
  24226. /** Returns true if this is a 'tempo' meta-event.
  24227. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  24228. */
  24229. bool isTempoMetaEvent() const throw();
  24230. /** Returns the tick length from a tempo meta-event.
  24231. @param timeFormat the 16-bit time format value from the midi file's header.
  24232. @returns the tick length (in seconds).
  24233. @see isTempoMetaEvent
  24234. */
  24235. double getTempoMetaEventTickLength (short timeFormat) const throw();
  24236. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  24237. @see isTempoMetaEvent, getTempoMetaEventTickLength
  24238. */
  24239. double getTempoSecondsPerQuarterNote() const throw();
  24240. /** Creates a tempo meta-event.
  24241. @see isTempoMetaEvent
  24242. */
  24243. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  24244. /** Returns true if this is a 'time-signature' meta-event.
  24245. @see getTimeSignatureInfo
  24246. */
  24247. bool isTimeSignatureMetaEvent() const throw();
  24248. /** Returns the time-signature values from a time-signature meta-event.
  24249. @see isTimeSignatureMetaEvent
  24250. */
  24251. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  24252. /** Creates a time-signature meta-event.
  24253. @see isTimeSignatureMetaEvent
  24254. */
  24255. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  24256. /** Returns true if this is a 'key-signature' meta-event.
  24257. @see getKeySignatureNumberOfSharpsOrFlats
  24258. */
  24259. bool isKeySignatureMetaEvent() const throw();
  24260. /** Returns the key from a key-signature meta-event.
  24261. @see isKeySignatureMetaEvent
  24262. */
  24263. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  24264. /** Returns true if this is a 'channel' meta-event.
  24265. A channel meta-event specifies the midi channel that should be used
  24266. for subsequent meta-events.
  24267. @see getMidiChannelMetaEventChannel
  24268. */
  24269. bool isMidiChannelMetaEvent() const throw();
  24270. /** Returns the channel number from a channel meta-event.
  24271. @returns the channel, in the range 1 to 16.
  24272. @see isMidiChannelMetaEvent
  24273. */
  24274. int getMidiChannelMetaEventChannel() const throw();
  24275. /** Creates a midi channel meta-event.
  24276. @param channel the midi channel, in the range 1 to 16
  24277. @see isMidiChannelMetaEvent
  24278. */
  24279. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  24280. /** Returns true if this is an active-sense message. */
  24281. bool isActiveSense() const throw();
  24282. /** Returns true if this is a midi start event.
  24283. @see midiStart
  24284. */
  24285. bool isMidiStart() const throw();
  24286. /** Creates a midi start event. */
  24287. static const MidiMessage midiStart() throw();
  24288. /** Returns true if this is a midi continue event.
  24289. @see midiContinue
  24290. */
  24291. bool isMidiContinue() const throw();
  24292. /** Creates a midi continue event. */
  24293. static const MidiMessage midiContinue() throw();
  24294. /** Returns true if this is a midi stop event.
  24295. @see midiStop
  24296. */
  24297. bool isMidiStop() const throw();
  24298. /** Creates a midi stop event. */
  24299. static const MidiMessage midiStop() throw();
  24300. /** Returns true if this is a midi clock event.
  24301. @see midiClock, songPositionPointer
  24302. */
  24303. bool isMidiClock() const throw();
  24304. /** Creates a midi clock event. */
  24305. static const MidiMessage midiClock() throw();
  24306. /** Returns true if this is a song-position-pointer message.
  24307. @see getSongPositionPointerMidiBeat, songPositionPointer
  24308. */
  24309. bool isSongPositionPointer() const throw();
  24310. /** Returns the midi beat-number of a song-position-pointer message.
  24311. @see isSongPositionPointer, songPositionPointer
  24312. */
  24313. int getSongPositionPointerMidiBeat() const throw();
  24314. /** Creates a song-position-pointer message.
  24315. The position is a number of midi beats from the start of the song, where 1 midi
  24316. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  24317. are 4 midi beats in a quarter-note.
  24318. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  24319. */
  24320. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  24321. /** Returns true if this is a quarter-frame midi timecode message.
  24322. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  24323. */
  24324. bool isQuarterFrame() const throw();
  24325. /** Returns the sequence number of a quarter-frame midi timecode message.
  24326. This will be a value between 0 and 7.
  24327. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  24328. */
  24329. int getQuarterFrameSequenceNumber() const throw();
  24330. /** Returns the value from a quarter-frame message.
  24331. This will be the lower nybble of the message's data-byte, a value
  24332. between 0 and 15
  24333. */
  24334. int getQuarterFrameValue() const throw();
  24335. /** Creates a quarter-frame MTC message.
  24336. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  24337. @param value a value 0 to 15 for the lower nybble of the message's data byte
  24338. */
  24339. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  24340. /** SMPTE timecode types.
  24341. Used by the getFullFrameParameters() and fullFrame() methods.
  24342. */
  24343. enum SmpteTimecodeType
  24344. {
  24345. fps24 = 0,
  24346. fps25 = 1,
  24347. fps30drop = 2,
  24348. fps30 = 3
  24349. };
  24350. /** Returns true if this is a full-frame midi timecode message.
  24351. */
  24352. bool isFullFrame() const throw();
  24353. /** Extracts the timecode information from a full-frame midi timecode message.
  24354. You should only call this on messages where you've used isFullFrame() to
  24355. check that they're the right kind.
  24356. */
  24357. void getFullFrameParameters (int& hours,
  24358. int& minutes,
  24359. int& seconds,
  24360. int& frames,
  24361. SmpteTimecodeType& timecodeType) const throw();
  24362. /** Creates a full-frame MTC message.
  24363. */
  24364. static const MidiMessage fullFrame (int hours,
  24365. int minutes,
  24366. int seconds,
  24367. int frames,
  24368. SmpteTimecodeType timecodeType);
  24369. /** Types of MMC command.
  24370. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  24371. */
  24372. enum MidiMachineControlCommand
  24373. {
  24374. mmc_stop = 1,
  24375. mmc_play = 2,
  24376. mmc_deferredplay = 3,
  24377. mmc_fastforward = 4,
  24378. mmc_rewind = 5,
  24379. mmc_recordStart = 6,
  24380. mmc_recordStop = 7,
  24381. mmc_pause = 9
  24382. };
  24383. /** Checks whether this is an MMC message.
  24384. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  24385. */
  24386. bool isMidiMachineControlMessage() const throw();
  24387. /** For an MMC message, this returns its type.
  24388. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  24389. calling this method.
  24390. */
  24391. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  24392. /** Creates an MMC message.
  24393. */
  24394. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  24395. /** Checks whether this is an MMC "goto" message.
  24396. If it is, the parameters passed-in are set to the time that the message contains.
  24397. @see midiMachineControlGoto
  24398. */
  24399. bool isMidiMachineControlGoto (int& hours,
  24400. int& minutes,
  24401. int& seconds,
  24402. int& frames) const throw();
  24403. /** Creates an MMC "goto" message.
  24404. This messages tells the device to go to a specific frame.
  24405. @see isMidiMachineControlGoto
  24406. */
  24407. static const MidiMessage midiMachineControlGoto (int hours,
  24408. int minutes,
  24409. int seconds,
  24410. int frames);
  24411. /** Creates a master-volume change message.
  24412. @param volume the volume, 0 to 1.0
  24413. */
  24414. static const MidiMessage masterVolume (float volume);
  24415. /** Creates a system-exclusive message.
  24416. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  24417. */
  24418. static const MidiMessage createSysExMessage (const uint8* sysexData,
  24419. int dataSize);
  24420. /** Reads a midi variable-length integer.
  24421. @param data the data to read the number from
  24422. @param numBytesUsed on return, this will be set to the number of bytes that were read
  24423. */
  24424. static int readVariableLengthVal (const uint8* data,
  24425. int& numBytesUsed) throw();
  24426. /** Based on the first byte of a short midi message, this uses a lookup table
  24427. to return the message length (either 1, 2, or 3 bytes).
  24428. The value passed in must be 0x80 or higher.
  24429. */
  24430. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  24431. /** Returns the name of a midi note number.
  24432. E.g "C", "D#", etc.
  24433. @param noteNumber the midi note number, 0 to 127
  24434. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  24435. they'll be flattened, e.g. "Db"
  24436. @param includeOctaveNumber if true, the octave number will be appended to the string,
  24437. e.g. "C#4"
  24438. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  24439. number that will be used for middle C's octave
  24440. @see getMidiNoteInHertz
  24441. */
  24442. static const String getMidiNoteName (int noteNumber,
  24443. bool useSharps,
  24444. bool includeOctaveNumber,
  24445. int octaveNumForMiddleC) throw();
  24446. /** Returns the frequency of a midi note number.
  24447. @see getMidiNoteName
  24448. */
  24449. static const double getMidiNoteInHertz (int noteNumber) throw();
  24450. /** Returns the standard name of a GM instrument.
  24451. @param midiInstrumentNumber the program number 0 to 127
  24452. @see getProgramChangeNumber
  24453. */
  24454. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  24455. /** Returns the name of a bank of GM instruments.
  24456. @param midiBankNumber the bank, 0 to 15
  24457. */
  24458. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  24459. /** Returns the standard name of a channel 10 percussion sound.
  24460. @param midiNoteNumber the key number, 35 to 81
  24461. */
  24462. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  24463. /** Returns the name of a controller type number.
  24464. @see getControllerNumber
  24465. */
  24466. static const String getControllerName (int controllerNumber) throw();
  24467. juce_UseDebuggingNewOperator
  24468. private:
  24469. double timeStamp;
  24470. uint8* data;
  24471. int size;
  24472. union
  24473. {
  24474. uint8 asBytes[4];
  24475. uint32 asInt32;
  24476. } preallocatedData;
  24477. };
  24478. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  24479. /*** End of inlined file: juce_MidiMessage.h ***/
  24480. class MidiInput;
  24481. /**
  24482. Receives midi messages from a midi input device.
  24483. This class is overridden to handle incoming midi messages. See the MidiInput
  24484. class for more details.
  24485. @see MidiInput
  24486. */
  24487. class JUCE_API MidiInputCallback
  24488. {
  24489. public:
  24490. /** Destructor. */
  24491. virtual ~MidiInputCallback() {}
  24492. /** Receives an incoming message.
  24493. A MidiInput object will call this method when a midi event arrives. It'll be
  24494. called on a high-priority system thread, so avoid doing anything time-consuming
  24495. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  24496. for queueing incoming messages for use later.
  24497. @param source the MidiInput object that generated the message
  24498. @param message the incoming message. The message's timestamp is set to a value
  24499. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  24500. time when the message arrived.
  24501. */
  24502. virtual void handleIncomingMidiMessage (MidiInput* source,
  24503. const MidiMessage& message) = 0;
  24504. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  24505. If a long sysex message is broken up into multiple packets, this callback is made
  24506. for each packet that arrives until the message is finished, at which point
  24507. the normal handleIncomingMidiMessage() callback will be made with the entire
  24508. message.
  24509. The message passed in will contain the start of a sysex, but won't be finished
  24510. with the terminating 0xf7 byte.
  24511. */
  24512. virtual void handlePartialSysexMessage (MidiInput* source,
  24513. const uint8* messageData,
  24514. const int numBytesSoFar,
  24515. const double timestamp)
  24516. {
  24517. // (this bit is just to avoid compiler warnings about unused variables)
  24518. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  24519. }
  24520. };
  24521. /**
  24522. Represents a midi input device.
  24523. To create one of these, use the static getDevices() method to find out what inputs are
  24524. available, and then use the openDevice() method to try to open one.
  24525. @see MidiOutput
  24526. */
  24527. class JUCE_API MidiInput
  24528. {
  24529. public:
  24530. /** Returns a list of the available midi input devices.
  24531. You can open one of the devices by passing its index into the
  24532. openDevice() method.
  24533. @see getDefaultDeviceIndex, openDevice
  24534. */
  24535. static const StringArray getDevices();
  24536. /** Returns the index of the default midi input device to use.
  24537. This refers to the index in the list returned by getDevices().
  24538. */
  24539. static int getDefaultDeviceIndex();
  24540. /** Tries to open one of the midi input devices.
  24541. This will return a MidiInput object if it manages to open it. You can then
  24542. call start() and stop() on this device, and delete it when no longer needed.
  24543. If the device can't be opened, this will return a null pointer.
  24544. @param deviceIndex the index of a device from the list returned by getDevices()
  24545. @param callback the object that will receive the midi messages from this device.
  24546. @see MidiInputCallback, getDevices
  24547. */
  24548. static MidiInput* openDevice (int deviceIndex,
  24549. MidiInputCallback* callback);
  24550. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  24551. /** This will try to create a new midi input device (Not available on Windows).
  24552. This will attempt to create a new midi input device with the specified name,
  24553. for other apps to connect to.
  24554. Returns 0 if a device can't be created.
  24555. @param deviceName the name to use for the new device
  24556. @param callback the object that will receive the midi messages from this device.
  24557. */
  24558. static MidiInput* createNewDevice (const String& deviceName,
  24559. MidiInputCallback* callback);
  24560. #endif
  24561. /** Destructor. */
  24562. virtual ~MidiInput();
  24563. /** Returns the name of this device.
  24564. */
  24565. virtual const String getName() const throw() { return name; }
  24566. /** Allows you to set a custom name for the device, in case you don't like the name
  24567. it was given when created.
  24568. */
  24569. virtual void setName (const String& newName) throw() { name = newName; }
  24570. /** Starts the device running.
  24571. After calling this, the device will start sending midi messages to the
  24572. MidiInputCallback object that was specified when the openDevice() method
  24573. was called.
  24574. @see stop
  24575. */
  24576. virtual void start();
  24577. /** Stops the device running.
  24578. @see start
  24579. */
  24580. virtual void stop();
  24581. juce_UseDebuggingNewOperator
  24582. protected:
  24583. String name;
  24584. void* internal;
  24585. explicit MidiInput (const String& name);
  24586. private:
  24587. MidiInput (const MidiInput&);
  24588. MidiInput& operator= (const MidiInput&);
  24589. };
  24590. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  24591. /*** End of inlined file: juce_MidiInput.h ***/
  24592. /*** Start of inlined file: juce_MidiOutput.h ***/
  24593. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  24594. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  24595. /*** Start of inlined file: juce_MidiBuffer.h ***/
  24596. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  24597. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  24598. /**
  24599. Holds a sequence of time-stamped midi events.
  24600. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  24601. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  24602. @see MidiMessage
  24603. */
  24604. class JUCE_API MidiBuffer
  24605. {
  24606. public:
  24607. /** Creates an empty MidiBuffer. */
  24608. MidiBuffer() throw();
  24609. /** Creates a MidiBuffer containing a single midi message. */
  24610. explicit MidiBuffer (const MidiMessage& message) throw();
  24611. /** Creates a copy of another MidiBuffer. */
  24612. MidiBuffer (const MidiBuffer& other) throw();
  24613. /** Makes a copy of another MidiBuffer. */
  24614. MidiBuffer& operator= (const MidiBuffer& other) throw();
  24615. /** Destructor */
  24616. ~MidiBuffer() throw();
  24617. /** Removes all events from the buffer. */
  24618. void clear() throw();
  24619. /** Removes all events between two times from the buffer.
  24620. All events for which (start <= event position < start + numSamples) will
  24621. be removed.
  24622. */
  24623. void clear (const int start,
  24624. const int numSamples) throw();
  24625. /** Returns true if the buffer is empty.
  24626. To actually retrieve the events, use a MidiBuffer::Iterator object
  24627. */
  24628. bool isEmpty() const throw();
  24629. /** Counts the number of events in the buffer.
  24630. This is actually quite a slow operation, as it has to iterate through all
  24631. the events, so you might prefer to call isEmpty() if that's all you need
  24632. to know.
  24633. */
  24634. int getNumEvents() const throw();
  24635. /** Adds an event to the buffer.
  24636. The sample number will be used to determine the position of the event in
  24637. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  24638. ignored.
  24639. If an event is added whose sample position is the same as one or more events
  24640. already in the buffer, the new event will be placed after the existing ones.
  24641. To retrieve events, use a MidiBuffer::Iterator object
  24642. */
  24643. void addEvent (const MidiMessage& midiMessage,
  24644. const int sampleNumber) throw();
  24645. /** Adds an event to the buffer from raw midi data.
  24646. The sample number will be used to determine the position of the event in
  24647. the buffer, which is always kept sorted.
  24648. If an event is added whose sample position is the same as one or more events
  24649. already in the buffer, the new event will be placed after the existing ones.
  24650. The event data will be inspected to calculate the number of bytes in length that
  24651. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  24652. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  24653. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  24654. add an event at all.
  24655. To retrieve events, use a MidiBuffer::Iterator object
  24656. */
  24657. void addEvent (const uint8* const rawMidiData,
  24658. const int maxBytesOfMidiData,
  24659. const int sampleNumber) throw();
  24660. /** Adds some events from another buffer to this one.
  24661. @param otherBuffer the buffer containing the events you want to add
  24662. @param startSample the lowest sample number in the source buffer for which
  24663. events should be added. Any source events whose timestamp is
  24664. less than this will be ignored
  24665. @param numSamples the valid range of samples from the source buffer for which
  24666. events should be added - i.e. events in the source buffer whose
  24667. timestamp is greater than or equal to (startSample + numSamples)
  24668. will be ignored. If this value is less than 0, all events after
  24669. startSample will be taken.
  24670. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  24671. that are added to this buffer
  24672. */
  24673. void addEvents (const MidiBuffer& otherBuffer,
  24674. const int startSample,
  24675. const int numSamples,
  24676. const int sampleDeltaToAdd) throw();
  24677. /** Returns the sample number of the first event in the buffer.
  24678. If the buffer's empty, this will just return 0.
  24679. */
  24680. int getFirstEventTime() const throw();
  24681. /** Returns the sample number of the last event in the buffer.
  24682. If the buffer's empty, this will just return 0.
  24683. */
  24684. int getLastEventTime() const throw();
  24685. /** Exchanges the contents of this buffer with another one.
  24686. This is a quick operation, because no memory allocating or copying is done, it
  24687. just swaps the internal state of the two buffers.
  24688. */
  24689. void swapWith (MidiBuffer& other);
  24690. /** Preallocates some memory for the buffer to use.
  24691. This helps to avoid needing to reallocate space when the buffer has messages
  24692. added to it.
  24693. */
  24694. void ensureSize (size_t minimumNumBytes);
  24695. /**
  24696. Used to iterate through the events in a MidiBuffer.
  24697. Note that altering the buffer while an iterator is using it isn't a
  24698. safe operation.
  24699. @see MidiBuffer
  24700. */
  24701. class Iterator
  24702. {
  24703. public:
  24704. /** Creates an Iterator for this MidiBuffer. */
  24705. Iterator (const MidiBuffer& buffer) throw();
  24706. /** Destructor. */
  24707. ~Iterator() throw();
  24708. /** Repositions the iterator so that the next event retrieved will be the first
  24709. one whose sample position is at greater than or equal to the given position.
  24710. */
  24711. void setNextSamplePosition (const int samplePosition) throw();
  24712. /** Retrieves a copy of the next event from the buffer.
  24713. @param result on return, this will be the message (the MidiMessage's timestamp
  24714. is not set)
  24715. @param samplePosition on return, this will be the position of the event
  24716. @returns true if an event was found, or false if the iterator has reached
  24717. the end of the buffer
  24718. */
  24719. bool getNextEvent (MidiMessage& result,
  24720. int& samplePosition) throw();
  24721. /** Retrieves the next event from the buffer.
  24722. @param midiData on return, this pointer will be set to a block of data containing
  24723. the midi message. Note that to make it fast, this is a pointer
  24724. directly into the MidiBuffer's internal data, so is only valid
  24725. temporarily until the MidiBuffer is altered.
  24726. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  24727. midi message
  24728. @param samplePosition on return, this will be the position of the event
  24729. @returns true if an event was found, or false if the iterator has reached
  24730. the end of the buffer
  24731. */
  24732. bool getNextEvent (const uint8* &midiData,
  24733. int& numBytesOfMidiData,
  24734. int& samplePosition) throw();
  24735. juce_UseDebuggingNewOperator
  24736. private:
  24737. const MidiBuffer& buffer;
  24738. const uint8* data;
  24739. Iterator (const Iterator&);
  24740. Iterator& operator= (const Iterator&);
  24741. };
  24742. juce_UseDebuggingNewOperator
  24743. private:
  24744. friend class MidiBuffer::Iterator;
  24745. MemoryBlock data;
  24746. int bytesUsed;
  24747. uint8* getData() const throw();
  24748. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  24749. static int getEventTime (const void* d) throw();
  24750. static uint16 getEventDataSize (const void* d) throw();
  24751. static uint16 getEventTotalSize (const void* d) throw();
  24752. };
  24753. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  24754. /*** End of inlined file: juce_MidiBuffer.h ***/
  24755. /**
  24756. Represents a midi output device.
  24757. To create one of these, use the static getDevices() method to find out what
  24758. outputs are available, then use the openDevice() method to try to open one.
  24759. @see MidiInput
  24760. */
  24761. class JUCE_API MidiOutput : private Thread
  24762. {
  24763. public:
  24764. /** Returns a list of the available midi output devices.
  24765. You can open one of the devices by passing its index into the
  24766. openDevice() method.
  24767. @see getDefaultDeviceIndex, openDevice
  24768. */
  24769. static const StringArray getDevices();
  24770. /** Returns the index of the default midi output device to use.
  24771. This refers to the index in the list returned by getDevices().
  24772. */
  24773. static int getDefaultDeviceIndex();
  24774. /** Tries to open one of the midi output devices.
  24775. This will return a MidiOutput object if it manages to open it. You can then
  24776. send messages to this device, and delete it when no longer needed.
  24777. If the device can't be opened, this will return a null pointer.
  24778. @param deviceIndex the index of a device from the list returned by getDevices()
  24779. @see getDevices
  24780. */
  24781. static MidiOutput* openDevice (int deviceIndex);
  24782. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  24783. /** This will try to create a new midi output device (Not available on Windows).
  24784. This will attempt to create a new midi output device that other apps can connect
  24785. to and use as their midi input.
  24786. Returns 0 if a device can't be created.
  24787. @param deviceName the name to use for the new device
  24788. */
  24789. static MidiOutput* createNewDevice (const String& deviceName);
  24790. #endif
  24791. /** Destructor. */
  24792. virtual ~MidiOutput();
  24793. /** Makes this device output a midi message.
  24794. @see MidiMessage
  24795. */
  24796. virtual void sendMessageNow (const MidiMessage& message);
  24797. /** Sends a midi reset to the device. */
  24798. virtual void reset();
  24799. /** Returns the current volume setting for this device. */
  24800. virtual bool getVolume (float& leftVol,
  24801. float& rightVol);
  24802. /** Changes the overall volume for this device. */
  24803. virtual void setVolume (float leftVol,
  24804. float rightVol);
  24805. /** This lets you supply a block of messages that will be sent out at some point
  24806. in the future.
  24807. The MidiOutput class has an internal thread that can send out timestamped
  24808. messages - this appends a set of messages to its internal buffer, ready for
  24809. sending.
  24810. This will only work if you've already started the thread with startBackgroundThread().
  24811. A time is supplied, at which the block of messages should be sent. This time uses
  24812. the same time base as Time::getMillisecondCounter(), and must be in the future.
  24813. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  24814. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  24815. samplesPerSecondForBuffer value is needed to convert this sample position to a
  24816. real time.
  24817. */
  24818. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  24819. double millisecondCounterToStartAt,
  24820. double samplesPerSecondForBuffer);
  24821. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  24822. */
  24823. virtual void clearAllPendingMessages();
  24824. /** Starts up a background thread so that the device can send blocks of data.
  24825. Call this to get the device ready, before using sendBlockOfMessages().
  24826. */
  24827. virtual void startBackgroundThread();
  24828. /** Stops the background thread, and clears any pending midi events.
  24829. @see startBackgroundThread
  24830. */
  24831. virtual void stopBackgroundThread();
  24832. juce_UseDebuggingNewOperator
  24833. protected:
  24834. void* internal;
  24835. struct PendingMessage
  24836. {
  24837. PendingMessage (const uint8* data, int len, double sampleNumber);
  24838. MidiMessage message;
  24839. PendingMessage* next;
  24840. juce_UseDebuggingNewOperator
  24841. };
  24842. CriticalSection lock;
  24843. PendingMessage* firstMessage;
  24844. MidiOutput();
  24845. void run();
  24846. private:
  24847. MidiOutput (const MidiOutput&);
  24848. MidiOutput& operator= (const MidiOutput&);
  24849. };
  24850. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  24851. /*** End of inlined file: juce_MidiOutput.h ***/
  24852. /*** Start of inlined file: juce_ComboBox.h ***/
  24853. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  24854. #define __JUCE_COMBOBOX_JUCEHEADER__
  24855. /*** Start of inlined file: juce_Label.h ***/
  24856. #ifndef __JUCE_LABEL_JUCEHEADER__
  24857. #define __JUCE_LABEL_JUCEHEADER__
  24858. /*** Start of inlined file: juce_TextEditor.h ***/
  24859. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  24860. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  24861. /*** Start of inlined file: juce_Viewport.h ***/
  24862. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  24863. #define __JUCE_VIEWPORT_JUCEHEADER__
  24864. /*** Start of inlined file: juce_ScrollBar.h ***/
  24865. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  24866. #define __JUCE_SCROLLBAR_JUCEHEADER__
  24867. /*** Start of inlined file: juce_Button.h ***/
  24868. #ifndef __JUCE_BUTTON_JUCEHEADER__
  24869. #define __JUCE_BUTTON_JUCEHEADER__
  24870. /*** Start of inlined file: juce_TooltipWindow.h ***/
  24871. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  24872. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  24873. /*** Start of inlined file: juce_TooltipClient.h ***/
  24874. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  24875. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  24876. /**
  24877. Components that want to use pop-up tooltips should implement this interface.
  24878. A TooltipWindow will wait for the mouse to hover over a component that
  24879. implements the TooltipClient interface, and when it finds one, it will display
  24880. the tooltip returned by its getTooltip() method.
  24881. @see TooltipWindow, SettableTooltipClient
  24882. */
  24883. class JUCE_API TooltipClient
  24884. {
  24885. public:
  24886. /** Destructor. */
  24887. virtual ~TooltipClient() {}
  24888. /** Returns the string that this object wants to show as its tooltip. */
  24889. virtual const String getTooltip() = 0;
  24890. };
  24891. /**
  24892. An implementation of TooltipClient that stores the tooltip string and a method
  24893. for changing it.
  24894. This makes it easy to add a tooltip to a custom component, by simply adding this
  24895. as a base class and calling setTooltip().
  24896. Many of the Juce widgets already use this as a base class to implement their
  24897. tooltips.
  24898. @see TooltipClient, TooltipWindow
  24899. */
  24900. class JUCE_API SettableTooltipClient : public TooltipClient
  24901. {
  24902. public:
  24903. /** Destructor. */
  24904. virtual ~SettableTooltipClient() {}
  24905. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  24906. virtual const String getTooltip() { return tooltipString; }
  24907. juce_UseDebuggingNewOperator
  24908. protected:
  24909. String tooltipString;
  24910. };
  24911. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  24912. /*** End of inlined file: juce_TooltipClient.h ***/
  24913. /**
  24914. A window that displays a pop-up tooltip when the mouse hovers over another component.
  24915. To enable tooltips in your app, just create a single instance of a TooltipWindow
  24916. object.
  24917. The TooltipWindow object will then stay invisible, waiting until the mouse
  24918. hovers for the specified length of time - it will then see if it's currently
  24919. over a component which implements the TooltipClient interface, and if so,
  24920. it will make itself visible to show the tooltip in the appropriate place.
  24921. @see TooltipClient, SettableTooltipClient
  24922. */
  24923. class JUCE_API TooltipWindow : public Component,
  24924. private Timer
  24925. {
  24926. public:
  24927. /** Creates a tooltip window.
  24928. Make sure your app only creates one instance of this class, otherwise you'll
  24929. get multiple overlaid tooltips appearing. The window will initially be invisible
  24930. and will make itself visible when it needs to display a tip.
  24931. To change the style of tooltips, see the LookAndFeel class for its tooltip
  24932. methods.
  24933. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  24934. otherwise the tooltip will be added to the given parent
  24935. component.
  24936. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  24937. before a tooltip will be shown
  24938. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  24939. */
  24940. explicit TooltipWindow (Component* parentComponent = 0,
  24941. int millisecondsBeforeTipAppears = 700);
  24942. /** Destructor. */
  24943. ~TooltipWindow();
  24944. /** Changes the time before the tip appears.
  24945. This lets you change the value that was set in the constructor.
  24946. */
  24947. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  24948. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  24949. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  24950. methods.
  24951. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  24952. */
  24953. enum ColourIds
  24954. {
  24955. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  24956. textColourId = 0x1001c00, /**< The colour to use for the text. */
  24957. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  24958. };
  24959. juce_UseDebuggingNewOperator
  24960. private:
  24961. int millisecondsBeforeTipAppears;
  24962. Point<int> lastMousePos;
  24963. int mouseClicks;
  24964. unsigned int lastCompChangeTime, lastHideTime;
  24965. Component* lastComponentUnderMouse;
  24966. bool changedCompsSinceShown;
  24967. String tipShowing, lastTipUnderMouse;
  24968. void paint (Graphics& g);
  24969. void mouseEnter (const MouseEvent& e);
  24970. void timerCallback();
  24971. static const String getTipFor (Component* c);
  24972. void showFor (const String& tip);
  24973. void hide();
  24974. TooltipWindow (const TooltipWindow&);
  24975. TooltipWindow& operator= (const TooltipWindow&);
  24976. };
  24977. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  24978. /*** End of inlined file: juce_TooltipWindow.h ***/
  24979. class Button;
  24980. /**
  24981. Used to receive callbacks when a button is clicked.
  24982. @see Button::addButtonListener, Button::removeButtonListener
  24983. */
  24984. class JUCE_API ButtonListener
  24985. {
  24986. public:
  24987. /** Destructor. */
  24988. virtual ~ButtonListener() {}
  24989. /** Called when the button is clicked. */
  24990. virtual void buttonClicked (Button* button) = 0;
  24991. /** Called when the button's state changes. */
  24992. virtual void buttonStateChanged (Button*) {}
  24993. };
  24994. /**
  24995. A base class for buttons.
  24996. This contains all the logic for button behaviours such as enabling/disabling,
  24997. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  24998. and radio groups, etc.
  24999. @see TextButton, DrawableButton, ToggleButton
  25000. */
  25001. class JUCE_API Button : public Component,
  25002. public SettableTooltipClient,
  25003. public ApplicationCommandManagerListener,
  25004. public Value::Listener,
  25005. private KeyListener
  25006. {
  25007. protected:
  25008. /** Creates a button.
  25009. @param buttonName the text to put in the button (the component's name is also
  25010. initially set to this string, but these can be changed later
  25011. using the setName() and setButtonText() methods)
  25012. */
  25013. explicit Button (const String& buttonName);
  25014. public:
  25015. /** Destructor. */
  25016. virtual ~Button();
  25017. /** Changes the button's text.
  25018. @see getButtonText
  25019. */
  25020. void setButtonText (const String& newText);
  25021. /** Returns the text displayed in the button.
  25022. @see setButtonText
  25023. */
  25024. const String getButtonText() const { return text; }
  25025. /** Returns true if the button is currently being held down by the mouse.
  25026. @see isOver
  25027. */
  25028. bool isDown() const throw();
  25029. /** Returns true if the mouse is currently over the button.
  25030. This will be also be true if the mouse is being held down.
  25031. @see isDown
  25032. */
  25033. bool isOver() const throw();
  25034. /** A button has an on/off state associated with it, and this changes that.
  25035. By default buttons are 'off' and for simple buttons that you click to perform
  25036. an action you won't change this. Toggle buttons, however will want to
  25037. change their state when turned on or off.
  25038. @param shouldBeOn whether to set the button's toggle state to be on or
  25039. off. If it's a member of a button group, this will
  25040. always try to turn it on, and to turn off any other
  25041. buttons in the group
  25042. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  25043. the button will be repainted but no notification will
  25044. be sent
  25045. @see getToggleState, setRadioGroupId
  25046. */
  25047. void setToggleState (bool shouldBeOn,
  25048. bool sendChangeNotification);
  25049. /** Returns true if the button in 'on'.
  25050. By default buttons are 'off' and for simple buttons that you click to perform
  25051. an action you won't change this. Toggle buttons, however will want to
  25052. change their state when turned on or off.
  25053. @see setToggleState
  25054. */
  25055. bool getToggleState() const throw() { return isOn.getValue(); }
  25056. /** Returns the Value object that represents the botton's toggle state.
  25057. You can use this Value object to connect the button's state to external values or setters,
  25058. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  25059. your own Value object.
  25060. @see getToggleState, Value
  25061. */
  25062. Value& getToggleStateValue() { return isOn; }
  25063. /** This tells the button to automatically flip the toggle state when
  25064. the button is clicked.
  25065. If set to true, then before the clicked() callback occurs, the toggle-state
  25066. of the button is flipped.
  25067. */
  25068. void setClickingTogglesState (bool shouldToggle) throw();
  25069. /** Returns true if this button is set to be an automatic toggle-button.
  25070. This returns the last value that was passed to setClickingTogglesState().
  25071. */
  25072. bool getClickingTogglesState() const throw();
  25073. /** Enables the button to act as a member of a mutually-exclusive group
  25074. of 'radio buttons'.
  25075. If the group ID is set to a non-zero number, then this button will
  25076. act as part of a group of buttons with the same ID, only one of
  25077. which can be 'on' at the same time. Note that when it's part of
  25078. a group, clicking a toggle-button that's 'on' won't turn it off.
  25079. To find other buttons with the same ID, this button will search through
  25080. its sibling components for ToggleButtons, so all the buttons for a
  25081. particular group must be placed inside the same parent component.
  25082. Set the group ID back to zero if you want it to act as a normal toggle
  25083. button again.
  25084. @see getRadioGroupId
  25085. */
  25086. void setRadioGroupId (int newGroupId);
  25087. /** Returns the ID of the group to which this button belongs.
  25088. (See setRadioGroupId() for an explanation of this).
  25089. */
  25090. int getRadioGroupId() const throw() { return radioGroupId; }
  25091. /** Registers a listener to receive events when this button's state changes.
  25092. If the listener is already registered, this will not register it again.
  25093. @see removeButtonListener
  25094. */
  25095. void addButtonListener (ButtonListener* newListener);
  25096. /** Removes a previously-registered button listener
  25097. @see addButtonListener
  25098. */
  25099. void removeButtonListener (ButtonListener* listener);
  25100. /** Causes the button to act as if it's been clicked.
  25101. This will asynchronously make the button draw itself going down and up, and
  25102. will then call back the clicked() method as if mouse was clicked on it.
  25103. @see clicked
  25104. */
  25105. virtual void triggerClick();
  25106. /** Sets a command ID for this button to automatically invoke when it's clicked.
  25107. When the button is pressed, it will use the given manager to trigger the
  25108. command ID.
  25109. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  25110. before this button is. To disable the command triggering, call this method and
  25111. pass 0 for the parameters.
  25112. If generateTooltip is true, then the button's tooltip will be automatically
  25113. generated based on the name of this command and its current shortcut key.
  25114. @see addShortcut, getCommandID
  25115. */
  25116. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  25117. int commandID,
  25118. bool generateTooltip);
  25119. /** Returns the command ID that was set by setCommandToTrigger().
  25120. */
  25121. int getCommandID() const throw() { return commandID; }
  25122. /** Assigns a shortcut key to trigger the button.
  25123. The button registers itself with its top-level parent component for keypresses.
  25124. Note that a different way of linking buttons to keypresses is by using the
  25125. setCommandToTrigger() method to invoke a command.
  25126. @see clearShortcuts
  25127. */
  25128. void addShortcut (const KeyPress& key);
  25129. /** Removes all key shortcuts that had been set for this button.
  25130. @see addShortcut
  25131. */
  25132. void clearShortcuts();
  25133. /** Returns true if the given keypress is a shortcut for this button.
  25134. @see addShortcut
  25135. */
  25136. bool isRegisteredForShortcut (const KeyPress& key) const;
  25137. /** Sets an auto-repeat speed for the button when it is held down.
  25138. (Auto-repeat is disabled by default).
  25139. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  25140. triggering the next click. If this is zero, auto-repeat
  25141. is disabled
  25142. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  25143. triggered
  25144. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  25145. get faster, the longer the button is held down, up to the
  25146. minimum interval specified here
  25147. */
  25148. void setRepeatSpeed (int initialDelayInMillisecs,
  25149. int repeatDelayInMillisecs,
  25150. int minimumDelayInMillisecs = -1) throw();
  25151. /** Sets whether the button click should happen when the mouse is pressed or released.
  25152. By default the button is only considered to have been clicked when the mouse is
  25153. released, but setting this to true will make it call the clicked() method as soon
  25154. as the button is pressed.
  25155. This is useful if the button is being used to show a pop-up menu, as it allows
  25156. the click to be used as a drag onto the menu.
  25157. */
  25158. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  25159. /** Returns the number of milliseconds since the last time the button
  25160. went into the 'down' state.
  25161. */
  25162. uint32 getMillisecondsSinceButtonDown() const throw();
  25163. /** (overridden from Component to do special stuff). */
  25164. void setVisible (bool shouldBeVisible);
  25165. /** Sets the tooltip for this button.
  25166. @see TooltipClient, TooltipWindow
  25167. */
  25168. void setTooltip (const String& newTooltip);
  25169. // (implementation of the TooltipClient method)
  25170. const String getTooltip();
  25171. /** A combination of these flags are used by setConnectedEdges().
  25172. */
  25173. enum ConnectedEdgeFlags
  25174. {
  25175. ConnectedOnLeft = 1,
  25176. ConnectedOnRight = 2,
  25177. ConnectedOnTop = 4,
  25178. ConnectedOnBottom = 8
  25179. };
  25180. /** Hints about which edges of the button might be connected to adjoining buttons.
  25181. The value passed in is a bitwise combination of any of the values in the
  25182. ConnectedEdgeFlags enum.
  25183. E.g. if you are placing two buttons adjacent to each other, you could use this to
  25184. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  25185. without rounded corners on the edges that connect. It's only a hint, so the
  25186. LookAndFeel can choose to ignore it if it's not relevent for this type of
  25187. button.
  25188. */
  25189. void setConnectedEdges (int connectedEdgeFlags);
  25190. /** Returns the set of flags passed into setConnectedEdges(). */
  25191. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  25192. /** Indicates whether the button adjoins another one on its left edge.
  25193. @see setConnectedEdges
  25194. */
  25195. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  25196. /** Indicates whether the button adjoins another one on its right edge.
  25197. @see setConnectedEdges
  25198. */
  25199. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  25200. /** Indicates whether the button adjoins another one on its top edge.
  25201. @see setConnectedEdges
  25202. */
  25203. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  25204. /** Indicates whether the button adjoins another one on its bottom edge.
  25205. @see setConnectedEdges
  25206. */
  25207. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  25208. /** Used by setState(). */
  25209. enum ButtonState
  25210. {
  25211. buttonNormal,
  25212. buttonOver,
  25213. buttonDown
  25214. };
  25215. /** Can be used to force the button into a particular state.
  25216. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  25217. from happening.
  25218. The state that you set here will only last until it is automatically changed when the mouse
  25219. enters or exits the button, or the mouse-button is pressed or released.
  25220. */
  25221. void setState (const ButtonState newState);
  25222. juce_UseDebuggingNewOperator
  25223. protected:
  25224. /** This method is called when the button has been clicked.
  25225. Subclasses can override this to perform whatever they actions they need
  25226. to do.
  25227. Alternatively, a ButtonListener can be added to the button, and these listeners
  25228. will be called when the click occurs.
  25229. @see triggerClick
  25230. */
  25231. virtual void clicked();
  25232. /** This method is called when the button has been clicked.
  25233. By default it just calls clicked(), but you might want to override it to handle
  25234. things like clicking when a modifier key is pressed, etc.
  25235. @see ModifierKeys
  25236. */
  25237. virtual void clicked (const ModifierKeys& modifiers);
  25238. /** Subclasses should override this to actually paint the button's contents.
  25239. It's better to use this than the paint method, because it gives you information
  25240. about the over/down state of the button.
  25241. @param g the graphics context to use
  25242. @param isMouseOverButton true if the button is either in the 'over' or
  25243. 'down' state
  25244. @param isButtonDown true if the button should be drawn in the 'down' position
  25245. */
  25246. virtual void paintButton (Graphics& g,
  25247. bool isMouseOverButton,
  25248. bool isButtonDown) = 0;
  25249. /** Called when the button's up/down/over state changes.
  25250. Subclasses can override this if they need to do something special when the button
  25251. goes up or down.
  25252. @see isDown, isOver
  25253. */
  25254. virtual void buttonStateChanged();
  25255. /** @internal */
  25256. virtual void internalClickCallback (const ModifierKeys& modifiers);
  25257. /** @internal */
  25258. void handleCommandMessage (int commandId);
  25259. /** @internal */
  25260. void mouseEnter (const MouseEvent& e);
  25261. /** @internal */
  25262. void mouseExit (const MouseEvent& e);
  25263. /** @internal */
  25264. void mouseDown (const MouseEvent& e);
  25265. /** @internal */
  25266. void mouseDrag (const MouseEvent& e);
  25267. /** @internal */
  25268. void mouseUp (const MouseEvent& e);
  25269. /** @internal */
  25270. bool keyPressed (const KeyPress& key);
  25271. /** @internal */
  25272. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  25273. /** @internal */
  25274. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  25275. /** @internal */
  25276. void paint (Graphics& g);
  25277. /** @internal */
  25278. void parentHierarchyChanged();
  25279. /** @internal */
  25280. void focusGained (FocusChangeType cause);
  25281. /** @internal */
  25282. void focusLost (FocusChangeType cause);
  25283. /** @internal */
  25284. void enablementChanged();
  25285. /** @internal */
  25286. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  25287. /** @internal */
  25288. void applicationCommandListChanged();
  25289. /** @internal */
  25290. void valueChanged (Value& value);
  25291. private:
  25292. Array <KeyPress> shortcuts;
  25293. Component::SafePointer<Component> keySource;
  25294. String text;
  25295. ListenerList <ButtonListener> buttonListeners;
  25296. class RepeatTimer;
  25297. friend class RepeatTimer;
  25298. friend class ScopedPointer <RepeatTimer>;
  25299. ScopedPointer <RepeatTimer> repeatTimer;
  25300. uint32 buttonPressTime, lastTimeCallbackTime;
  25301. ApplicationCommandManager* commandManagerToUse;
  25302. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  25303. int radioGroupId, commandID, connectedEdgeFlags;
  25304. ButtonState buttonState;
  25305. Value isOn;
  25306. bool lastToggleState : 1;
  25307. bool clickTogglesState : 1;
  25308. bool needsToRelease : 1;
  25309. bool needsRepainting : 1;
  25310. bool isKeyDown : 1;
  25311. bool triggerOnMouseDown : 1;
  25312. bool generateTooltip : 1;
  25313. void repeatTimerCallback();
  25314. RepeatTimer& getRepeatTimer();
  25315. ButtonState updateState (const MouseEvent* const e);
  25316. bool isShortcutPressed() const;
  25317. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  25318. void flashButtonState();
  25319. void sendClickMessage (const ModifierKeys& modifiers);
  25320. void sendStateMessage();
  25321. Button (const Button&);
  25322. Button& operator= (const Button&);
  25323. };
  25324. #endif // __JUCE_BUTTON_JUCEHEADER__
  25325. /*** End of inlined file: juce_Button.h ***/
  25326. class ScrollBar;
  25327. /**
  25328. A class for receiving events from a ScrollBar.
  25329. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  25330. method, and it will be called when the bar's position changes.
  25331. @see ScrollBar::addListener, ScrollBar::removeListener
  25332. */
  25333. class JUCE_API ScrollBarListener
  25334. {
  25335. public:
  25336. /** Destructor. */
  25337. virtual ~ScrollBarListener() {}
  25338. /** Called when a ScrollBar is moved.
  25339. @param scrollBarThatHasMoved the bar that has moved
  25340. @param newRangeStart the new range start of this bar
  25341. */
  25342. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  25343. double newRangeStart) = 0;
  25344. };
  25345. /**
  25346. A scrollbar component.
  25347. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  25348. sets the range of values it can represent. Then you can use setCurrentRange() to
  25349. change the position and size of the scrollbar's 'thumb'.
  25350. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  25351. the user moves it, and you can use the getCurrentRangeStart() to find out where
  25352. they moved it to.
  25353. The scrollbar will adjust its own visibility according to whether its thumb size
  25354. allows it to actually be scrolled.
  25355. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  25356. instead of handling a scrollbar directly.
  25357. @see ScrollBarListener
  25358. */
  25359. class JUCE_API ScrollBar : public Component,
  25360. public AsyncUpdater,
  25361. private Timer
  25362. {
  25363. public:
  25364. /** Creates a Scrollbar.
  25365. @param isVertical whether it should be a vertical or horizontal bar
  25366. @param buttonsAreVisible whether to show the up/down or left/right buttons
  25367. */
  25368. ScrollBar (bool isVertical,
  25369. bool buttonsAreVisible = true);
  25370. /** Destructor. */
  25371. ~ScrollBar();
  25372. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  25373. bool isVertical() const throw() { return vertical; }
  25374. /** Changes the scrollbar's direction.
  25375. You'll also need to resize the bar appropriately - this just changes its internal
  25376. layout.
  25377. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  25378. */
  25379. void setOrientation (bool shouldBeVertical);
  25380. /** Shows or hides the scrollbar's buttons. */
  25381. void setButtonVisibility (bool buttonsAreVisible);
  25382. /** Tells the scrollbar whether to make itself invisible when not needed.
  25383. The default behaviour is for a scrollbar to become invisible when the thumb
  25384. fills the whole of its range (i.e. when it can't be moved). Setting this
  25385. value to false forces the bar to always be visible.
  25386. @see autoHides()
  25387. */
  25388. void setAutoHide (bool shouldHideWhenFullRange);
  25389. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  25390. as its maximum range.
  25391. @see setAutoHide
  25392. */
  25393. bool autoHides() const throw();
  25394. /** Sets the minimum and maximum values that the bar will move between.
  25395. The bar's thumb will always be constrained so that the entire thumb lies
  25396. within this range.
  25397. @see setCurrentRange
  25398. */
  25399. void setRangeLimits (const Range<double>& newRangeLimit);
  25400. /** Sets the minimum and maximum values that the bar will move between.
  25401. The bar's thumb will always be constrained so that the entire thumb lies
  25402. within this range.
  25403. @see setCurrentRange
  25404. */
  25405. void setRangeLimits (double minimum, double maximum);
  25406. /** Returns the current limits on the thumb position.
  25407. @see setRangeLimits
  25408. */
  25409. const Range<double> getRangeLimit() const throw() { return totalRange; }
  25410. /** Returns the lower value that the thumb can be set to.
  25411. This is the value set by setRangeLimits().
  25412. */
  25413. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  25414. /** Returns the upper value that the thumb can be set to.
  25415. This is the value set by setRangeLimits().
  25416. */
  25417. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  25418. /** Changes the position of the scrollbar's 'thumb'.
  25419. If this method call actually changes the scrollbar's position, it will trigger an
  25420. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25421. are registered.
  25422. @see getCurrentRange. setCurrentRangeStart
  25423. */
  25424. void setCurrentRange (const Range<double>& newRange);
  25425. /** Changes the position of the scrollbar's 'thumb'.
  25426. This sets both the position and size of the thumb - to just set the position without
  25427. changing the size, you can use setCurrentRangeStart().
  25428. If this method call actually changes the scrollbar's position, it will trigger an
  25429. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25430. are registered.
  25431. @param newStart the top (or left) of the thumb, in the range
  25432. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  25433. value is beyond these limits, it will be clipped.
  25434. @param newSize the size of the thumb, such that
  25435. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  25436. size is beyond these limits, it will be clipped.
  25437. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  25438. */
  25439. void setCurrentRange (double newStart, double newSize);
  25440. /** Moves the bar's thumb position.
  25441. This will move the thumb position without changing the thumb size. Note
  25442. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  25443. If this method call actually changes the scrollbar's position, it will trigger an
  25444. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  25445. are registered.
  25446. @see setCurrentRange
  25447. */
  25448. void setCurrentRangeStart (double newStart);
  25449. /** Returns the current thumb range.
  25450. @see getCurrentRange, setCurrentRange
  25451. */
  25452. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  25453. /** Returns the position of the top of the thumb.
  25454. @see getCurrentRange, setCurrentRangeStart
  25455. */
  25456. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  25457. /** Returns the current size of the thumb.
  25458. @see getCurrentRange, setCurrentRange
  25459. */
  25460. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  25461. /** Sets the amount by which the up and down buttons will move the bar.
  25462. The value here is in terms of the total range, and is added or subtracted
  25463. from the thumb position when the user clicks an up/down (or left/right) button.
  25464. */
  25465. void setSingleStepSize (double newSingleStepSize);
  25466. /** Moves the scrollbar by a number of single-steps.
  25467. This will move the bar by a multiple of its single-step interval (as
  25468. specified using the setSingleStepSize() method).
  25469. A positive value here will move the bar down or to the right, a negative
  25470. value moves it up or to the left.
  25471. */
  25472. void moveScrollbarInSteps (int howManySteps);
  25473. /** Moves the scroll bar up or down in pages.
  25474. This will move the bar by a multiple of its current thumb size, effectively
  25475. doing a page-up or down.
  25476. A positive value here will move the bar down or to the right, a negative
  25477. value moves it up or to the left.
  25478. */
  25479. void moveScrollbarInPages (int howManyPages);
  25480. /** Scrolls to the top (or left).
  25481. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  25482. */
  25483. void scrollToTop();
  25484. /** Scrolls to the bottom (or right).
  25485. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  25486. */
  25487. void scrollToBottom();
  25488. /** Changes the delay before the up and down buttons autorepeat when they are held
  25489. down.
  25490. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  25491. @see Button::setRepeatSpeed
  25492. */
  25493. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  25494. int repeatDelayInMillisecs,
  25495. int minimumDelayInMillisecs = -1);
  25496. /** A set of colour IDs to use to change the colour of various aspects of the component.
  25497. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25498. methods.
  25499. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25500. */
  25501. enum ColourIds
  25502. {
  25503. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  25504. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  25505. 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. */
  25506. };
  25507. /** Registers a listener that will be called when the scrollbar is moved. */
  25508. void addListener (ScrollBarListener* listener);
  25509. /** Deregisters a previously-registered listener. */
  25510. void removeListener (ScrollBarListener* listener);
  25511. /** @internal */
  25512. bool keyPressed (const KeyPress& key);
  25513. /** @internal */
  25514. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25515. /** @internal */
  25516. void lookAndFeelChanged();
  25517. /** @internal */
  25518. void handleAsyncUpdate();
  25519. /** @internal */
  25520. void mouseDown (const MouseEvent& e);
  25521. /** @internal */
  25522. void mouseDrag (const MouseEvent& e);
  25523. /** @internal */
  25524. void mouseUp (const MouseEvent& e);
  25525. /** @internal */
  25526. void paint (Graphics& g);
  25527. /** @internal */
  25528. void resized();
  25529. juce_UseDebuggingNewOperator
  25530. private:
  25531. Range <double> totalRange, visibleRange;
  25532. double singleStepSize, dragStartRange;
  25533. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  25534. int dragStartMousePos, lastMousePos;
  25535. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  25536. bool vertical, isDraggingThumb, autohides;
  25537. class ScrollbarButton;
  25538. ScrollbarButton* upButton;
  25539. ScrollbarButton* downButton;
  25540. ListenerList <ScrollBarListener> listeners;
  25541. void updateThumbPosition();
  25542. void timerCallback();
  25543. ScrollBar (const ScrollBar&);
  25544. ScrollBar& operator= (const ScrollBar&);
  25545. };
  25546. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  25547. /*** End of inlined file: juce_ScrollBar.h ***/
  25548. /**
  25549. A Viewport is used to contain a larger child component, and allows the child
  25550. to be automatically scrolled around.
  25551. To use a Viewport, just create one and set the component that goes inside it
  25552. using the setViewedComponent() method. When the child component changes size,
  25553. the Viewport will adjust its scrollbars accordingly.
  25554. A subclass of the viewport can be created which will receive calls to its
  25555. visibleAreaChanged() method when the subcomponent changes position or size.
  25556. */
  25557. class JUCE_API Viewport : public Component,
  25558. private ComponentListener,
  25559. private ScrollBarListener
  25560. {
  25561. public:
  25562. /** Creates a Viewport.
  25563. The viewport is initially empty - use the setViewedComponent() method to
  25564. add a child component for it to manage.
  25565. */
  25566. explicit Viewport (const String& componentName = String::empty);
  25567. /** Destructor. */
  25568. ~Viewport();
  25569. /** Sets the component that this viewport will contain and scroll around.
  25570. This will add the given component to this Viewport and position it at
  25571. (0, 0).
  25572. (Don't add or remove any child components directly using the normal
  25573. Component::addChildComponent() methods).
  25574. @param newViewedComponent the component to add to this viewport (this pointer
  25575. may be null). The component passed in will be deleted
  25576. by the Viewport when it's no longer needed
  25577. @see getViewedComponent
  25578. */
  25579. void setViewedComponent (Component* newViewedComponent);
  25580. /** Returns the component that's currently being used inside the Viewport.
  25581. @see setViewedComponent
  25582. */
  25583. Component* getViewedComponent() const throw() { return contentComp; }
  25584. /** Changes the position of the viewed component.
  25585. The inner component will be moved so that the pixel at the top left of
  25586. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  25587. within the inner component.
  25588. This will update the scrollbars and might cause a call to visibleAreaChanged().
  25589. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  25590. */
  25591. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  25592. /** Changes the view position as a proportion of the distance it can move.
  25593. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  25594. visible area in the top-left, and (1, 1) would put it as far down and
  25595. to the right as it's possible to go whilst keeping the child component
  25596. on-screen.
  25597. */
  25598. void setViewPositionProportionately (double proportionX, double proportionY);
  25599. /** If the specified position is at the edges of the viewport, this method scrolls
  25600. the viewport to bring that position nearer to the centre.
  25601. Call this if you're dragging an object inside a viewport and want to make it scroll
  25602. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  25603. useful when auto-scrolling.
  25604. @param mouseX the x position, relative to the Viewport's top-left
  25605. @param mouseY the y position, relative to the Viewport's top-left
  25606. @param distanceFromEdge specifies how close to an edge the position needs to be
  25607. before the viewport should scroll in that direction
  25608. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  25609. to scroll by.
  25610. @returns true if the viewport was scrolled
  25611. */
  25612. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  25613. /** Returns the position within the child component of the top-left of its visible area.
  25614. */
  25615. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  25616. /** Returns the position within the child component of the top-left of its visible area.
  25617. @see getViewWidth, setViewPosition
  25618. */
  25619. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  25620. /** Returns the position within the child component of the top-left of its visible area.
  25621. @see getViewHeight, setViewPosition
  25622. */
  25623. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  25624. /** Returns the width of the visible area of the child component.
  25625. This may be less than the width of this Viewport if there's a vertical scrollbar
  25626. or if the child component is itself smaller.
  25627. */
  25628. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  25629. /** Returns the height of the visible area of the child component.
  25630. This may be less than the height of this Viewport if there's a horizontal scrollbar
  25631. or if the child component is itself smaller.
  25632. */
  25633. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  25634. /** Returns the width available within this component for the contents.
  25635. This will be the width of the viewport component minus the width of a
  25636. vertical scrollbar (if visible).
  25637. */
  25638. int getMaximumVisibleWidth() const;
  25639. /** Returns the height available within this component for the contents.
  25640. This will be the height of the viewport component minus the space taken up
  25641. by a horizontal scrollbar (if visible).
  25642. */
  25643. int getMaximumVisibleHeight() const;
  25644. /** Callback method that is called when the visible area changes.
  25645. This will be called when the visible area is moved either be scrolling or
  25646. by calls to setViewPosition(), etc.
  25647. */
  25648. virtual void visibleAreaChanged (int visibleX, int visibleY,
  25649. int visibleW, int visibleH);
  25650. /** Turns scrollbars on or off.
  25651. If set to false, the scrollbars won't ever appear. When true (the default)
  25652. they will appear only when needed.
  25653. */
  25654. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  25655. bool showHorizontalScrollbarIfNeeded);
  25656. /** True if the vertical scrollbar is enabled.
  25657. @see setScrollBarsShown
  25658. */
  25659. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  25660. /** True if the horizontal scrollbar is enabled.
  25661. @see setScrollBarsShown
  25662. */
  25663. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  25664. /** Changes the width of the scrollbars.
  25665. If this isn't specified, the default width from the LookAndFeel class will be used.
  25666. @see LookAndFeel::getDefaultScrollbarWidth
  25667. */
  25668. void setScrollBarThickness (int thickness);
  25669. /** Returns the thickness of the scrollbars.
  25670. @see setScrollBarThickness
  25671. */
  25672. int getScrollBarThickness() const;
  25673. /** Changes the distance that a single-step click on a scrollbar button
  25674. will move the viewport.
  25675. */
  25676. void setSingleStepSizes (int stepX, int stepY);
  25677. /** Shows or hides the buttons on any scrollbars that are used.
  25678. @see ScrollBar::setButtonVisibility
  25679. */
  25680. void setScrollBarButtonVisibility (bool buttonsVisible);
  25681. /** Returns a pointer to the scrollbar component being used.
  25682. Handy if you need to customise the bar somehow.
  25683. */
  25684. ScrollBar* getVerticalScrollBar() const throw() { return verticalScrollBar; }
  25685. /** Returns a pointer to the scrollbar component being used.
  25686. Handy if you need to customise the bar somehow.
  25687. */
  25688. ScrollBar* getHorizontalScrollBar() const throw() { return horizontalScrollBar; }
  25689. juce_UseDebuggingNewOperator
  25690. /** @internal */
  25691. void resized();
  25692. /** @internal */
  25693. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  25694. /** @internal */
  25695. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25696. /** @internal */
  25697. bool keyPressed (const KeyPress& key);
  25698. /** @internal */
  25699. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  25700. /** @internal */
  25701. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  25702. private:
  25703. Component::SafePointer<Component> contentComp;
  25704. Rectangle<int> lastVisibleArea;
  25705. int scrollBarThickness;
  25706. int singleStepX, singleStepY;
  25707. bool showHScrollbar, showVScrollbar;
  25708. Component* contentHolder;
  25709. ScrollBar* verticalScrollBar;
  25710. ScrollBar* horizontalScrollBar;
  25711. void updateVisibleArea();
  25712. Viewport (const Viewport&);
  25713. Viewport& operator= (const Viewport&);
  25714. };
  25715. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  25716. /*** End of inlined file: juce_Viewport.h ***/
  25717. /*** Start of inlined file: juce_PopupMenu.h ***/
  25718. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  25719. #define __JUCE_POPUPMENU_JUCEHEADER__
  25720. class PopupMenuCustomComponent;
  25721. /** Creates and displays a popup-menu.
  25722. To show a popup-menu, you create one of these, add some items to it, then
  25723. call its show() method, which returns the id of the item the user selects.
  25724. E.g. @code
  25725. void MyWidget::mouseDown (const MouseEvent& e)
  25726. {
  25727. PopupMenu m;
  25728. m.addItem (1, "item 1");
  25729. m.addItem (2, "item 2");
  25730. const int result = m.show();
  25731. if (result == 0)
  25732. {
  25733. // user dismissed the menu without picking anything
  25734. }
  25735. else if (result == 1)
  25736. {
  25737. // user picked item 1
  25738. }
  25739. else if (result == 2)
  25740. {
  25741. // user picked item 2
  25742. }
  25743. }
  25744. @endcode
  25745. Submenus are easy too: @code
  25746. void MyWidget::mouseDown (const MouseEvent& e)
  25747. {
  25748. PopupMenu subMenu;
  25749. subMenu.addItem (1, "item 1");
  25750. subMenu.addItem (2, "item 2");
  25751. PopupMenu mainMenu;
  25752. mainMenu.addItem (3, "item 3");
  25753. mainMenu.addSubMenu ("other choices", subMenu);
  25754. const int result = m.show();
  25755. ...etc
  25756. }
  25757. @endcode
  25758. */
  25759. class JUCE_API PopupMenu
  25760. {
  25761. public:
  25762. /** Creates an empty popup menu. */
  25763. PopupMenu();
  25764. /** Creates a copy of another menu. */
  25765. PopupMenu (const PopupMenu& other);
  25766. /** Destructor. */
  25767. ~PopupMenu();
  25768. /** Copies this menu from another one. */
  25769. PopupMenu& operator= (const PopupMenu& other);
  25770. /** Resets the menu, removing all its items. */
  25771. void clear();
  25772. /** Appends a new text item for this menu to show.
  25773. @param itemResultId the number that will be returned from the show() method
  25774. if the user picks this item. The value should never be
  25775. zero, because that's used to indicate that the user didn't
  25776. select anything.
  25777. @param itemText the text to show.
  25778. @param isActive if false, the item will be shown 'greyed-out' and can't be
  25779. picked
  25780. @param isTicked if true, the item will be shown with a tick next to it
  25781. @param iconToUse if this is non-zero, it should be an image that will be
  25782. displayed to the left of the item. This method will take its
  25783. own copy of the image passed-in, so there's no need to keep
  25784. it hanging around.
  25785. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  25786. */
  25787. void addItem (int itemResultId,
  25788. const String& itemText,
  25789. bool isActive = true,
  25790. bool isTicked = false,
  25791. const Image* iconToUse = 0);
  25792. /** Adds an item that represents one of the commands in a command manager object.
  25793. @param commandManager the manager to use to trigger the command and get information
  25794. about it
  25795. @param commandID the ID of the command
  25796. @param displayName if this is non-empty, then this string will be used instead of
  25797. the command's registered name
  25798. */
  25799. void addCommandItem (ApplicationCommandManager* commandManager,
  25800. int commandID,
  25801. const String& displayName = String::empty);
  25802. /** Appends a text item with a special colour.
  25803. This is the same as addItem(), but specifies a colour to use for the
  25804. text, which will override the default colours that are used by the
  25805. current look-and-feel. See addItem() for a description of the parameters.
  25806. */
  25807. void addColouredItem (int itemResultId,
  25808. const String& itemText,
  25809. const Colour& itemTextColour,
  25810. bool isActive = true,
  25811. bool isTicked = false,
  25812. const Image* iconToUse = 0);
  25813. /** Appends a custom menu item.
  25814. This will add a user-defined component to use as a menu item. The component
  25815. passed in will be deleted by this menu when it's no longer needed.
  25816. @see PopupMenuCustomComponent
  25817. */
  25818. void addCustomItem (int itemResultId, PopupMenuCustomComponent* customComponent);
  25819. /** Appends a custom menu item that can't be used to trigger a result.
  25820. This will add a user-defined component to use as a menu item. Unlike the
  25821. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  25822. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  25823. delete the component when it's finished, so it's the caller's responsibility
  25824. to manage the component that is passed-in.
  25825. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  25826. detection of a mouse-click on your component, and use that to trigger the
  25827. menu ID specified in itemResultId. If this is false, the menu item can't
  25828. be triggered, so itemResultId is not used.
  25829. @see PopupMenuCustomComponent
  25830. */
  25831. void addCustomItem (int itemResultId,
  25832. Component* customComponent,
  25833. int idealWidth, int idealHeight,
  25834. bool triggerMenuItemAutomaticallyWhenClicked);
  25835. /** Appends a sub-menu.
  25836. If the menu that's passed in is empty, it will appear as an inactive item.
  25837. */
  25838. void addSubMenu (const String& subMenuName,
  25839. const PopupMenu& subMenu,
  25840. bool isActive = true,
  25841. Image* iconToUse = 0,
  25842. bool isTicked = false);
  25843. /** Appends a separator to the menu, to help break it up into sections.
  25844. The menu class is smart enough not to display separators at the top or bottom
  25845. of the menu, and it will replace mutliple adjacent separators with a single
  25846. one, so your code can be quite free and easy about adding these, and it'll
  25847. always look ok.
  25848. */
  25849. void addSeparator();
  25850. /** Adds a non-clickable text item to the menu.
  25851. This is a bold-font items which can be used as a header to separate the items
  25852. into named groups.
  25853. */
  25854. void addSectionHeader (const String& title);
  25855. /** Returns the number of items that the menu currently contains.
  25856. (This doesn't count separators).
  25857. */
  25858. int getNumItems() const throw();
  25859. /** Returns true if the menu contains a command item that triggers the given command. */
  25860. bool containsCommandItem (int commandID) const;
  25861. /** Returns true if the menu contains any items that can be used. */
  25862. bool containsAnyActiveItems() const throw();
  25863. /** Displays the menu and waits for the user to pick something.
  25864. This will display the menu modally, and return the ID of the item that the
  25865. user picks. If they click somewhere off the menu to get rid of it without
  25866. choosing anything, this will return 0.
  25867. The current location of the mouse will be used as the position to show the
  25868. menu - to explicitly set the menu's position, use showAt() instead. Depending
  25869. on where this point is on the screen, the menu will appear above, below or
  25870. to the side of the point.
  25871. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  25872. then when the menu first appears, it will make sure
  25873. that this item is visible. So if the menu has too many
  25874. items to fit on the screen, it will be scrolled to a
  25875. position where this item is visible.
  25876. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  25877. than this if some items are too long to fit.
  25878. @param maximumNumColumns if there are too many items to fit on-screen in a single
  25879. vertical column, the menu may be laid out as a series of
  25880. columns - this is the maximum number allowed. To use the
  25881. default value for this (probably about 7), you can pass
  25882. in zero.
  25883. @param standardItemHeight if this is non-zero, it will be used as the standard
  25884. height for menu items (apart from custom items)
  25885. @see showAt
  25886. */
  25887. int show (int itemIdThatMustBeVisible = 0,
  25888. int minimumWidth = 0,
  25889. int maximumNumColumns = 0,
  25890. int standardItemHeight = 0);
  25891. /** Displays the menu at a specific location.
  25892. This is the same as show(), but uses a specific location (in global screen
  25893. co-ordinates) rather than the current mouse position.
  25894. Note that the co-ordinates don't specify the top-left of the menu - they
  25895. indicate a point of interest, and the menu will position itself nearby to
  25896. this point, trying to keep it fully on-screen.
  25897. @see show()
  25898. */
  25899. int showAt (int screenX,
  25900. int screenY,
  25901. int itemIdThatMustBeVisible = 0,
  25902. int minimumWidth = 0,
  25903. int maximumNumColumns = 0,
  25904. int standardItemHeight = 0);
  25905. /** Displays the menu as if it's attached to a component such as a button.
  25906. This is similar to showAt(), but will position it next to the given component, e.g.
  25907. so that the menu's edge is aligned with that of the component. This is intended for
  25908. things like buttons that trigger a pop-up menu.
  25909. */
  25910. int showAt (Component* componentToAttachTo,
  25911. int itemIdThatMustBeVisible = 0,
  25912. int minimumWidth = 0,
  25913. int maximumNumColumns = 0,
  25914. int standardItemHeight = 0);
  25915. /** Closes any menus that are currently open.
  25916. This might be useful if you have a situation where your window is being closed
  25917. by some means other than a user action, and you'd like to make sure that menus
  25918. aren't left hanging around.
  25919. */
  25920. static void JUCE_CALLTYPE dismissAllActiveMenus();
  25921. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  25922. This can be called before show() if you need a customised menu. Be careful
  25923. not to delete the LookAndFeel object before the menu has been deleted.
  25924. */
  25925. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  25926. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  25927. These constants can be used either via the LookAndFeel::setColour()
  25928. method for the look and feel that is set for this menu with setLookAndFeel()
  25929. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  25930. */
  25931. enum ColourIds
  25932. {
  25933. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  25934. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  25935. colour is specified when the item is added). */
  25936. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  25937. addSectionHeader() method). */
  25938. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  25939. highlighted menu item. */
  25940. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  25941. highlighted item. */
  25942. };
  25943. /**
  25944. Allows you to iterate through the items in a pop-up menu, and examine
  25945. their properties.
  25946. To use this, just create one and repeatedly call its next() method. When this
  25947. returns true, all the member variables of the iterator are filled-out with
  25948. information describing the menu item. When it returns false, the end of the
  25949. list has been reached.
  25950. */
  25951. class JUCE_API MenuItemIterator
  25952. {
  25953. public:
  25954. /** Creates an iterator that will scan through the items in the specified
  25955. menu.
  25956. Be careful not to add any items to a menu while it is being iterated,
  25957. or things could get out of step.
  25958. */
  25959. MenuItemIterator (const PopupMenu& menu);
  25960. /** Destructor. */
  25961. ~MenuItemIterator();
  25962. /** Returns true if there is another item, and sets up all this object's
  25963. member variables to reflect that item's properties.
  25964. */
  25965. bool next();
  25966. String itemName;
  25967. const PopupMenu* subMenu;
  25968. int itemId;
  25969. bool isSeparator;
  25970. bool isTicked;
  25971. bool isEnabled;
  25972. bool isCustomComponent;
  25973. bool isSectionHeader;
  25974. const Colour* customColour;
  25975. const Image* customImage;
  25976. ApplicationCommandManager* commandManager;
  25977. juce_UseDebuggingNewOperator
  25978. private:
  25979. const PopupMenu& menu;
  25980. int index;
  25981. MenuItemIterator (const MenuItemIterator&);
  25982. MenuItemIterator& operator= (const MenuItemIterator&);
  25983. };
  25984. juce_UseDebuggingNewOperator
  25985. private:
  25986. class Item;
  25987. class ItemComponent;
  25988. class Window;
  25989. friend class MenuItemIterator;
  25990. friend class ItemComponent;
  25991. friend class Window;
  25992. friend class PopupMenuCustomComponent;
  25993. friend class OwnedArray <Item>;
  25994. friend class ScopedPointer <Window>;
  25995. OwnedArray <Item> items;
  25996. LookAndFeel* lookAndFeel;
  25997. bool separatorPending;
  25998. void addSeparatorIfPending();
  25999. int showMenu (int x, int y, int w, int h,
  26000. int itemIdThatMustBeVisible,
  26001. int minimumWidth,
  26002. int maximumNumColumns,
  26003. int standardItemHeight,
  26004. bool alignToRectangle,
  26005. Component* componentAttachedTo);
  26006. friend class MenuBarComponent;
  26007. Component* createMenuComponent (int x, int y, int w, int h,
  26008. int itemIdThatMustBeVisible,
  26009. int minimumWidth,
  26010. int maximumNumColumns,
  26011. int standardItemHeight,
  26012. bool alignToRectangle,
  26013. Component* menuBarComponent,
  26014. ApplicationCommandManager** managerOfChosenCommand,
  26015. Component* componentAttachedTo);
  26016. };
  26017. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  26018. /*** End of inlined file: juce_PopupMenu.h ***/
  26019. /*** Start of inlined file: juce_TextInputTarget.h ***/
  26020. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26021. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26022. /** An abstract base class that is implemented by components that wish to be used
  26023. as text editors.
  26024. This class allows different types of text editor component to provide a uniform
  26025. interface, which can be used by things like OS-specific input methods, on-screen
  26026. keyboards, etc.
  26027. */
  26028. class JUCE_API TextInputTarget
  26029. {
  26030. public:
  26031. /** */
  26032. TextInputTarget() {}
  26033. /** Destructor. */
  26034. virtual ~TextInputTarget() {}
  26035. /** Returns true if this input target is currently accepting input.
  26036. For example, a text editor might return false if it's in read-only mode.
  26037. */
  26038. virtual bool isTextInputActive() const = 0;
  26039. /** Returns the extents of the selected text region, or an empty range if
  26040. nothing is selected,
  26041. */
  26042. virtual const Range<int> getHighlightedRegion() const = 0;
  26043. /** Sets the currently-selected text region.
  26044. */
  26045. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  26046. /** Returns a specified sub-section of the text.
  26047. */
  26048. virtual const String getTextInRange (const Range<int>& range) const = 0;
  26049. /** Inserts some text, overwriting the selected text region, if there is one. */
  26050. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  26051. };
  26052. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26053. /*** End of inlined file: juce_TextInputTarget.h ***/
  26054. class TextEditor;
  26055. /**
  26056. Receives callbacks from a TextEditor component when it changes.
  26057. @see TextEditor::addListener
  26058. */
  26059. class JUCE_API TextEditorListener
  26060. {
  26061. public:
  26062. /** Destructor. */
  26063. virtual ~TextEditorListener() {}
  26064. /** Called when the user changes the text in some way. */
  26065. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  26066. /** Called when the user presses the return key. */
  26067. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  26068. /** Called when the user presses the escape key. */
  26069. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  26070. /** Called when the text editor loses focus. */
  26071. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  26072. };
  26073. /**
  26074. A component containing text that can be edited.
  26075. A TextEditor can either be in single- or multi-line mode, and supports mixed
  26076. fonts and colours.
  26077. @see TextEditorListener, Label
  26078. */
  26079. class JUCE_API TextEditor : public Component,
  26080. public TextInputTarget,
  26081. public SettableTooltipClient
  26082. {
  26083. public:
  26084. /** Creates a new, empty text editor.
  26085. @param componentName the name to pass to the component for it to use as its name
  26086. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26087. for all characters that are drawn on screen - e.g. to create
  26088. a password-style textbox containing circular blobs instead of text,
  26089. you could set this value to 0x25cf, which is the unicode character
  26090. for a black splodge (not all fonts include this, though), or 0x2022,
  26091. which is a bullet (probably the best choice for linux).
  26092. */
  26093. explicit TextEditor (const String& componentName = String::empty,
  26094. juce_wchar passwordCharacter = 0);
  26095. /** Destructor. */
  26096. virtual ~TextEditor();
  26097. /** Puts the editor into either multi- or single-line mode.
  26098. By default, the editor will be in single-line mode, so use this if you need a multi-line
  26099. editor.
  26100. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  26101. on if you want a multi-line editor with line-breaks.
  26102. @see isMultiLine, setReturnKeyStartsNewLine
  26103. */
  26104. void setMultiLine (bool shouldBeMultiLine,
  26105. bool shouldWordWrap = true);
  26106. /** Returns true if the editor is in multi-line mode.
  26107. */
  26108. bool isMultiLine() const;
  26109. /** Changes the behaviour of the return key.
  26110. If set to true, the return key will insert a new-line into the text; if false
  26111. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  26112. method. By default this is set to false, and when true it will only insert
  26113. new-lines when in multi-line mode (see setMultiLine()).
  26114. */
  26115. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  26116. /** Returns the value set by setReturnKeyStartsNewLine().
  26117. See setReturnKeyStartsNewLine() for more info.
  26118. */
  26119. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  26120. /** Indicates whether the tab key should be accepted and used to input a tab character,
  26121. or whether it gets ignored.
  26122. By default the tab key is ignored, so that it can be used to switch keyboard focus
  26123. between components.
  26124. */
  26125. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  26126. /** Returns true if the tab key is being used for input.
  26127. @see setTabKeyUsedAsCharacter
  26128. */
  26129. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  26130. /** Changes the editor to read-only mode.
  26131. By default, the text editor is not read-only. If you're making it read-only, you
  26132. might also want to call setCaretVisible (false) to get rid of the caret.
  26133. The text can still be highlighted and copied when in read-only mode.
  26134. @see isReadOnly, setCaretVisible
  26135. */
  26136. void setReadOnly (bool shouldBeReadOnly);
  26137. /** Returns true if the editor is in read-only mode.
  26138. */
  26139. bool isReadOnly() const;
  26140. /** Makes the caret visible or invisible.
  26141. By default the caret is visible.
  26142. @see setCaretColour, setCaretPosition
  26143. */
  26144. void setCaretVisible (bool shouldBeVisible);
  26145. /** Returns true if the caret is enabled.
  26146. @see setCaretVisible
  26147. */
  26148. bool isCaretVisible() const { return caretVisible; }
  26149. /** Enables/disables a vertical scrollbar.
  26150. (This only applies when in multi-line mode). When the text gets too long to fit
  26151. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  26152. this is enabled, the scrollbar will be hidden unless it's needed.
  26153. By default the scrollbar is enabled.
  26154. */
  26155. void setScrollbarsShown (bool shouldBeEnabled);
  26156. /** Returns true if scrollbars are enabled.
  26157. @see setScrollbarsShown
  26158. */
  26159. bool areScrollbarsShown() const { return scrollbarVisible; }
  26160. /** Changes the password character used to disguise the text.
  26161. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26162. for all characters that are drawn on screen - e.g. to create
  26163. a password-style textbox containing circular blobs instead of text,
  26164. you could set this value to 0x25cf, which is the unicode character
  26165. for a black splodge (not all fonts include this, though), or 0x2022,
  26166. which is a bullet (probably the best choice for linux).
  26167. */
  26168. void setPasswordCharacter (juce_wchar passwordCharacter);
  26169. /** Returns the current password character.
  26170. @see setPasswordCharacter
  26171. */
  26172. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  26173. /** Allows a right-click menu to appear for the editor.
  26174. (This defaults to being enabled).
  26175. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  26176. of options such as cut/copy/paste, undo/redo, etc.
  26177. */
  26178. void setPopupMenuEnabled (bool menuEnabled);
  26179. /** Returns true if the right-click menu is enabled.
  26180. @see setPopupMenuEnabled
  26181. */
  26182. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  26183. /** Returns true if a popup-menu is currently being displayed.
  26184. */
  26185. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  26186. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  26187. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26188. methods.
  26189. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26190. */
  26191. enum ColourIds
  26192. {
  26193. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  26194. transparent if necessary. */
  26195. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  26196. that because the editor can contain multiple colours, calling this
  26197. method won't change the colour of existing text - to do that, call
  26198. applyFontToAllText() after calling this method.*/
  26199. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  26200. the text - this can be transparent if you don't want to show any
  26201. highlighting.*/
  26202. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  26203. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  26204. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  26205. the edge of the component. */
  26206. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  26207. the edge of the component when it has focus. */
  26208. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  26209. around the edge of the editor. */
  26210. };
  26211. /** Sets the font to use for newly added text.
  26212. This will change the font that will be used next time any text is added or entered
  26213. into the editor. It won't change the font of any existing text - to do that, use
  26214. applyFontToAllText() instead.
  26215. @see applyFontToAllText
  26216. */
  26217. void setFont (const Font& newFont);
  26218. /** Applies a font to all the text in the editor.
  26219. This will also set the current font to use for any new text that's added.
  26220. @see setFont
  26221. */
  26222. void applyFontToAllText (const Font& newFont);
  26223. /** Returns the font that's currently being used for new text.
  26224. @see setFont
  26225. */
  26226. const Font getFont() const;
  26227. /** If set to true, focusing on the editor will highlight all its text.
  26228. (Set to false by default).
  26229. This is useful for boxes where you expect the user to re-enter all the
  26230. text when they focus on the component, rather than editing what's already there.
  26231. */
  26232. void setSelectAllWhenFocused (bool b);
  26233. /** Sets limits on the characters that can be entered.
  26234. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  26235. limit is set
  26236. @param allowedCharacters if this is non-empty, then only characters that occur in
  26237. this string are allowed to be entered into the editor.
  26238. */
  26239. void setInputRestrictions (int maxTextLength,
  26240. const String& allowedCharacters = String::empty);
  26241. /** When the text editor is empty, it can be set to display a message.
  26242. This is handy for things like telling the user what to type in the box - the
  26243. string is only displayed, it's not taken to actually be the contents of
  26244. the editor.
  26245. */
  26246. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  26247. /** Changes the size of the scrollbars that are used.
  26248. Handy if you need smaller scrollbars for a small text box.
  26249. */
  26250. void setScrollBarThickness (int newThicknessPixels);
  26251. /** Shows or hides the buttons on any scrollbars that are used.
  26252. @see ScrollBar::setButtonVisibility
  26253. */
  26254. void setScrollBarButtonVisibility (bool buttonsVisible);
  26255. /** Registers a listener to be told when things happen to the text.
  26256. @see removeListener
  26257. */
  26258. void addListener (TextEditorListener* newListener);
  26259. /** Deregisters a listener.
  26260. @see addListener
  26261. */
  26262. void removeListener (TextEditorListener* listenerToRemove);
  26263. /** Returns the entire contents of the editor. */
  26264. const String getText() const;
  26265. /** Returns a section of the contents of the editor. */
  26266. const String getTextInRange (const Range<int>& textRange) const;
  26267. /** Returns true if there are no characters in the editor.
  26268. This is more efficient than calling getText().isEmpty().
  26269. */
  26270. bool isEmpty() const;
  26271. /** Sets the entire content of the editor.
  26272. This will clear the editor and insert the given text (using the current text colour
  26273. and font). You can set the current text colour using
  26274. @code setColour (TextEditor::textColourId, ...);
  26275. @endcode
  26276. @param newText the text to add
  26277. @param sendTextChangeMessage if true, this will cause a change message to
  26278. be sent to all the listeners.
  26279. @see insertText
  26280. */
  26281. void setText (const String& newText,
  26282. bool sendTextChangeMessage = true);
  26283. /** Returns a Value object that can be used to get or set the text.
  26284. Bear in mind that this operate quite slowly if your text box contains large
  26285. amounts of text, as it needs to dynamically build the string that's involved. It's
  26286. best used for small text boxes.
  26287. */
  26288. Value& getTextValue();
  26289. /** Inserts some text at the current cursor position.
  26290. If a section of the text is highlighted, it will be replaced by
  26291. this string, otherwise it will be inserted.
  26292. To delete a section of text, you can use setHighlightedRegion() to
  26293. highlight it, and call insertTextAtCursor (String::empty).
  26294. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  26295. */
  26296. void insertTextAtCaret (const String& textToInsert);
  26297. /** Deletes all the text from the editor. */
  26298. void clear();
  26299. /** Deletes the currently selected region, and puts it on the clipboard.
  26300. @see copy, paste, SystemClipboard
  26301. */
  26302. void cut();
  26303. /** Copies any currently selected region to the clipboard.
  26304. @see cut, paste, SystemClipboard
  26305. */
  26306. void copy();
  26307. /** Pastes the contents of the clipboard into the editor at the cursor position.
  26308. @see cut, copy, SystemClipboard
  26309. */
  26310. void paste();
  26311. /** Moves the caret to be in front of a given character.
  26312. @see getCaretPosition
  26313. */
  26314. void setCaretPosition (int newIndex);
  26315. /** Returns the current index of the caret.
  26316. @see setCaretPosition
  26317. */
  26318. int getCaretPosition() const;
  26319. /** Attempts to scroll the text editor so that the caret ends up at
  26320. a specified position.
  26321. This won't affect the caret's position within the text, it tries to scroll
  26322. the entire editor vertically and horizontally so that the caret is sitting
  26323. at the given position (relative to the top-left of this component).
  26324. Depending on the amount of text available, it might not be possible to
  26325. scroll far enough for the caret to reach this exact position, but it
  26326. will go as far as it can in that direction.
  26327. */
  26328. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  26329. /** Get the graphical position of the caret.
  26330. The rectangle returned is relative to the component's top-left corner.
  26331. @see scrollEditorToPositionCaret
  26332. */
  26333. const Rectangle<int> getCaretRectangle();
  26334. /** Selects a section of the text. */
  26335. void setHighlightedRegion (const Range<int>& newSelection);
  26336. /** Returns the range of characters that are selected.
  26337. If nothing is selected, this will return an empty range.
  26338. @see setHighlightedRegion
  26339. */
  26340. const Range<int> getHighlightedRegion() const { return selection; }
  26341. /** Returns the section of text that is currently selected. */
  26342. const String getHighlightedText() const;
  26343. /** Finds the index of the character at a given position.
  26344. The co-ordinates are relative to the component's top-left.
  26345. */
  26346. int getTextIndexAt (int x, int y);
  26347. /** Counts the number of characters in the text.
  26348. This is quicker than getting the text as a string if you just need to know
  26349. the length.
  26350. */
  26351. int getTotalNumChars() const;
  26352. /** Returns the total width of the text, as it is currently laid-out.
  26353. This may be larger than the size of the TextEditor, and can change when
  26354. the TextEditor is resized or the text changes.
  26355. */
  26356. int getTextWidth() const;
  26357. /** Returns the maximum height of the text, as it is currently laid-out.
  26358. This may be larger than the size of the TextEditor, and can change when
  26359. the TextEditor is resized or the text changes.
  26360. */
  26361. int getTextHeight() const;
  26362. /** Changes the size of the gap at the top and left-edge of the editor.
  26363. By default there's a gap of 4 pixels.
  26364. */
  26365. void setIndents (int newLeftIndent, int newTopIndent);
  26366. /** Changes the size of border left around the edge of the component.
  26367. @see getBorder
  26368. */
  26369. void setBorder (const BorderSize& border);
  26370. /** Returns the size of border around the edge of the component.
  26371. @see setBorder
  26372. */
  26373. const BorderSize getBorder() const;
  26374. /** Used to disable the auto-scrolling which keeps the cursor visible.
  26375. If true (the default), the editor will scroll when the cursor moves offscreen. If
  26376. set to false, it won't.
  26377. */
  26378. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  26379. /** @internal */
  26380. void paint (Graphics& g);
  26381. /** @internal */
  26382. void paintOverChildren (Graphics& g);
  26383. /** @internal */
  26384. void mouseDown (const MouseEvent& e);
  26385. /** @internal */
  26386. void mouseUp (const MouseEvent& e);
  26387. /** @internal */
  26388. void mouseDrag (const MouseEvent& e);
  26389. /** @internal */
  26390. void mouseDoubleClick (const MouseEvent& e);
  26391. /** @internal */
  26392. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26393. /** @internal */
  26394. bool keyPressed (const KeyPress& key);
  26395. /** @internal */
  26396. bool keyStateChanged (bool isKeyDown);
  26397. /** @internal */
  26398. void focusGained (FocusChangeType cause);
  26399. /** @internal */
  26400. void focusLost (FocusChangeType cause);
  26401. /** @internal */
  26402. void resized();
  26403. /** @internal */
  26404. void enablementChanged();
  26405. /** @internal */
  26406. void colourChanged();
  26407. /** @internal */
  26408. bool isTextInputActive() const;
  26409. juce_UseDebuggingNewOperator
  26410. protected:
  26411. /** This adds the items to the popup menu.
  26412. By default it adds the cut/copy/paste items, but you can override this if
  26413. you need to replace these with your own items.
  26414. If you want to add your own items to the existing ones, you can override this,
  26415. call the base class's addPopupMenuItems() method, then append your own items.
  26416. When the menu has been shown, performPopupMenuAction() will be called to
  26417. perform the item that the user has chosen.
  26418. The default menu items will be added using item IDs in the range
  26419. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  26420. menu IDs.
  26421. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  26422. a pointer to the info about it, or may be null if the menu is being triggered
  26423. by some other means.
  26424. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  26425. */
  26426. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  26427. const MouseEvent* mouseClickEvent);
  26428. /** This is called to perform one of the items that was shown on the popup menu.
  26429. If you've overridden addPopupMenuItems(), you should also override this
  26430. to perform the actions that you've added.
  26431. If you've overridden addPopupMenuItems() but have still left the default items
  26432. on the menu, remember to call the superclass's performPopupMenuAction()
  26433. so that it can perform the default actions if that's what the user clicked on.
  26434. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  26435. */
  26436. virtual void performPopupMenuAction (int menuItemID);
  26437. /** Scrolls the minimum distance needed to get the caret into view. */
  26438. void scrollToMakeSureCursorIsVisible();
  26439. /** @internal */
  26440. void moveCaret (int newCaretPos);
  26441. /** @internal */
  26442. void moveCursorTo (int newPosition, bool isSelecting);
  26443. /** Used internally to dispatch a text-change message. */
  26444. void textChanged();
  26445. /** Begins a new transaction in the UndoManager.
  26446. */
  26447. void newTransaction();
  26448. /** Used internally to trigger an undo or redo. */
  26449. void doUndoRedo (bool isRedo);
  26450. /** Can be overridden to intercept return key presses directly */
  26451. virtual void returnPressed();
  26452. /** Can be overridden to intercept escape key presses directly */
  26453. virtual void escapePressed();
  26454. /** @internal */
  26455. void handleCommandMessage (int commandId);
  26456. private:
  26457. class Iterator;
  26458. class UniformTextSection;
  26459. class TextHolderComponent;
  26460. class InsertAction;
  26461. class RemoveAction;
  26462. friend class InsertAction;
  26463. friend class RemoveAction;
  26464. ScopedPointer <Viewport> viewport;
  26465. TextHolderComponent* textHolder;
  26466. BorderSize borderSize;
  26467. bool readOnly : 1;
  26468. bool multiline : 1;
  26469. bool wordWrap : 1;
  26470. bool returnKeyStartsNewLine : 1;
  26471. bool caretVisible : 1;
  26472. bool popupMenuEnabled : 1;
  26473. bool selectAllTextWhenFocused : 1;
  26474. bool scrollbarVisible : 1;
  26475. bool wasFocused : 1;
  26476. bool caretFlashState : 1;
  26477. bool keepCursorOnScreen : 1;
  26478. bool tabKeyUsed : 1;
  26479. bool menuActive : 1;
  26480. bool valueTextNeedsUpdating : 1;
  26481. UndoManager undoManager;
  26482. float cursorX, cursorY, cursorHeight;
  26483. int maxTextLength;
  26484. Range<int> selection;
  26485. int leftIndent, topIndent;
  26486. unsigned int lastTransactionTime;
  26487. Font currentFont;
  26488. mutable int totalNumChars;
  26489. int caretPosition;
  26490. Array <UniformTextSection*> sections;
  26491. String textToShowWhenEmpty;
  26492. Colour colourForTextWhenEmpty;
  26493. juce_wchar passwordCharacter;
  26494. Value textValue;
  26495. enum
  26496. {
  26497. notDragging,
  26498. draggingSelectionStart,
  26499. draggingSelectionEnd
  26500. } dragType;
  26501. String allowedCharacters;
  26502. ListenerList <TextEditorListener> listeners;
  26503. void coalesceSimilarSections();
  26504. void splitSection (int sectionIndex, int charToSplitAt);
  26505. void clearInternal (UndoManager* um);
  26506. void insert (const String& text, int insertIndex, const Font& font,
  26507. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  26508. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  26509. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  26510. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  26511. void updateCaretPosition();
  26512. void textWasChangedByValue();
  26513. int indexAtPosition (float x, float y);
  26514. int findWordBreakAfter (int position) const;
  26515. int findWordBreakBefore (int position) const;
  26516. friend class TextHolderComponent;
  26517. friend class TextEditorViewport;
  26518. void drawContent (Graphics& g);
  26519. void updateTextHolderSize();
  26520. float getWordWrapWidth() const;
  26521. void timerCallbackInt();
  26522. void repaintCaret();
  26523. void repaintText (const Range<int>& range);
  26524. UndoManager* getUndoManager() throw();
  26525. TextEditor (const TextEditor&);
  26526. TextEditor& operator= (const TextEditor&);
  26527. };
  26528. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  26529. /*** End of inlined file: juce_TextEditor.h ***/
  26530. class Label;
  26531. /**
  26532. A class for receiving events from a Label.
  26533. You can register a LabelListener with a Label using the Label::addListener()
  26534. method, and it will be called when the text of the label changes, either because
  26535. of a call to Label::setText() or by the user editing the text (if the label is
  26536. editable).
  26537. @see Label::addListener, Label::removeListener
  26538. */
  26539. class JUCE_API LabelListener
  26540. {
  26541. public:
  26542. /** Destructor. */
  26543. virtual ~LabelListener() {}
  26544. /** Called when a Label's text has changed.
  26545. */
  26546. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  26547. };
  26548. /**
  26549. A component that displays a text string, and can optionally become a text
  26550. editor when clicked.
  26551. */
  26552. class JUCE_API Label : public Component,
  26553. public SettableTooltipClient,
  26554. protected TextEditorListener,
  26555. private ComponentListener,
  26556. private Value::Listener
  26557. {
  26558. public:
  26559. /** Creates a Label.
  26560. @param componentName the name to give the component
  26561. @param labelText the text to show in the label
  26562. */
  26563. Label (const String& componentName = String::empty,
  26564. const String& labelText = String::empty);
  26565. /** Destructor. */
  26566. ~Label();
  26567. /** Changes the label text.
  26568. If broadcastChangeMessage is true and the new text is different to the current
  26569. text, then the class will broadcast a change message to any LabelListeners that
  26570. are registered.
  26571. */
  26572. void setText (const String& newText,
  26573. bool broadcastChangeMessage);
  26574. /** Returns the label's current text.
  26575. @param returnActiveEditorContents if this is true and the label is currently
  26576. being edited, then this method will return the
  26577. text as it's being shown in the editor. If false,
  26578. then the value returned here won't be updated until
  26579. the user has finished typing and pressed the return
  26580. key.
  26581. */
  26582. const String getText (bool returnActiveEditorContents = false) const throw();
  26583. /** Returns the text content as a Value object.
  26584. You can call Value::referTo() on this object to make the label read and control
  26585. a Value object that you supply.
  26586. */
  26587. Value& getTextValue() { return textValue; }
  26588. /** Changes the font to use to draw the text.
  26589. @see getFont
  26590. */
  26591. void setFont (const Font& newFont) throw();
  26592. /** Returns the font currently being used.
  26593. @see setFont
  26594. */
  26595. const Font& getFont() const throw();
  26596. /** A set of colour IDs to use to change the colour of various aspects of the label.
  26597. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26598. methods.
  26599. Note that you can also use the constants from TextEditor::ColourIds to change the
  26600. colour of the text editor that is opened when a label is editable.
  26601. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26602. */
  26603. enum ColourIds
  26604. {
  26605. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  26606. textColourId = 0x1000281, /**< The colour for the text. */
  26607. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  26608. Leave this transparent to not have an outline. */
  26609. };
  26610. /** Sets the style of justification to be used for positioning the text.
  26611. (The default is Justification::centredLeft)
  26612. */
  26613. void setJustificationType (const Justification& justification) throw();
  26614. /** Returns the type of justification, as set in setJustificationType(). */
  26615. const Justification getJustificationType() const throw() { return justification; }
  26616. /** Changes the gap that is left between the edge of the component and the text.
  26617. By default there's a small gap left at the sides of the component to allow for
  26618. the drawing of the border, but you can change this if necessary.
  26619. */
  26620. void setBorderSize (int horizontalBorder, int verticalBorder);
  26621. /** Returns the size of the horizontal gap being left around the text.
  26622. */
  26623. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  26624. /** Returns the size of the vertical gap being left around the text.
  26625. */
  26626. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  26627. /** Makes this label "stick to" another component.
  26628. This will cause the label to follow another component around, staying
  26629. either to its left or above it.
  26630. @param owner the component to follow
  26631. @param onLeft if true, the label will stay on the left of its component; if
  26632. false, it will stay above it.
  26633. */
  26634. void attachToComponent (Component* owner, bool onLeft);
  26635. /** If this label has been attached to another component using attachToComponent, this
  26636. returns the other component.
  26637. Returns 0 if the label is not attached.
  26638. */
  26639. Component* getAttachedComponent() const;
  26640. /** If the label is attached to the left of another component, this returns true.
  26641. Returns false if the label is above the other component. This is only relevent if
  26642. attachToComponent() has been called.
  26643. */
  26644. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  26645. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  26646. using ellipsis.
  26647. @see Graphics::drawFittedText
  26648. */
  26649. void setMinimumHorizontalScale (float newScale);
  26650. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  26651. /** Registers a listener that will be called when the label's text changes. */
  26652. void addListener (LabelListener* listener) throw();
  26653. /** Deregisters a previously-registered listener. */
  26654. void removeListener (LabelListener* listener) throw();
  26655. /** Makes the label turn into a TextEditor when clicked.
  26656. By default this is turned off.
  26657. If turned on, then single- or double-clicking will turn the label into
  26658. an editor. If the user then changes the text, then the ChangeBroadcaster
  26659. base class will be used to send change messages to any listeners that
  26660. have registered.
  26661. If the user changes the text, the textWasEdited() method will be called
  26662. afterwards, and subclasses can override this if they need to do anything
  26663. special.
  26664. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  26665. @param editOnDoubleClick if true, a double-click is needed to start editing
  26666. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  26667. edited will discard any changes; if false, then this will
  26668. commit the changes.
  26669. @see showEditor, setEditorColours, TextEditor
  26670. */
  26671. void setEditable (bool editOnSingleClick,
  26672. bool editOnDoubleClick = false,
  26673. bool lossOfFocusDiscardsChanges = false) throw();
  26674. /** Returns true if this option was set using setEditable(). */
  26675. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  26676. /** Returns true if this option was set using setEditable(). */
  26677. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  26678. /** Returns true if this option has been set in a call to setEditable(). */
  26679. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  26680. /** Returns true if the user can edit this label's text. */
  26681. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  26682. /** Makes the editor appear as if the label had been clicked by the user.
  26683. @see textWasEdited, setEditable
  26684. */
  26685. void showEditor();
  26686. /** Hides the editor if it was being shown.
  26687. @param discardCurrentEditorContents if true, the label's text will be
  26688. reset to whatever it was before the editor
  26689. was shown; if false, the current contents of the
  26690. editor will be used to set the label's text
  26691. before it is hidden.
  26692. */
  26693. void hideEditor (bool discardCurrentEditorContents);
  26694. /** Returns true if the editor is currently focused and active. */
  26695. bool isBeingEdited() const throw();
  26696. juce_UseDebuggingNewOperator
  26697. protected:
  26698. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  26699. Subclasses can override this if they need to customise this component in some way.
  26700. */
  26701. virtual TextEditor* createEditorComponent();
  26702. /** Called after the user changes the text.
  26703. */
  26704. virtual void textWasEdited();
  26705. /** Called when the text has been altered.
  26706. */
  26707. virtual void textWasChanged();
  26708. /** Called when the text editor has just appeared, due to a user click or other
  26709. focus change.
  26710. */
  26711. virtual void editorShown (TextEditor* editorComponent);
  26712. /** Called when the text editor is going to be deleted, after editing has finished.
  26713. */
  26714. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  26715. /** @internal */
  26716. void paint (Graphics& g);
  26717. /** @internal */
  26718. void resized();
  26719. /** @internal */
  26720. void mouseUp (const MouseEvent& e);
  26721. /** @internal */
  26722. void mouseDoubleClick (const MouseEvent& e);
  26723. /** @internal */
  26724. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  26725. /** @internal */
  26726. void componentParentHierarchyChanged (Component& component);
  26727. /** @internal */
  26728. void componentVisibilityChanged (Component& component);
  26729. /** @internal */
  26730. void inputAttemptWhenModal();
  26731. /** @internal */
  26732. void focusGained (FocusChangeType);
  26733. /** @internal */
  26734. void enablementChanged();
  26735. /** @internal */
  26736. KeyboardFocusTraverser* createFocusTraverser();
  26737. /** @internal */
  26738. void textEditorTextChanged (TextEditor& editor);
  26739. /** @internal */
  26740. void textEditorReturnKeyPressed (TextEditor& editor);
  26741. /** @internal */
  26742. void textEditorEscapeKeyPressed (TextEditor& editor);
  26743. /** @internal */
  26744. void textEditorFocusLost (TextEditor& editor);
  26745. /** @internal */
  26746. void colourChanged();
  26747. /** @internal */
  26748. void valueChanged (Value&);
  26749. private:
  26750. Value textValue;
  26751. String lastTextValue;
  26752. Font font;
  26753. Justification justification;
  26754. ScopedPointer <TextEditor> editor;
  26755. ListenerList <LabelListener> listeners;
  26756. Component::SafePointer<Component> ownerComponent;
  26757. int horizontalBorderSize, verticalBorderSize;
  26758. float minimumHorizontalScale;
  26759. bool editSingleClick : 1;
  26760. bool editDoubleClick : 1;
  26761. bool lossOfFocusDiscardsChanges : 1;
  26762. bool leftOfOwnerComp : 1;
  26763. bool updateFromTextEditorContents();
  26764. void callChangeListeners();
  26765. Label (const Label&);
  26766. Label& operator= (const Label&);
  26767. };
  26768. #endif // __JUCE_LABEL_JUCEHEADER__
  26769. /*** End of inlined file: juce_Label.h ***/
  26770. class ComboBox;
  26771. /**
  26772. A class for receiving events from a ComboBox.
  26773. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  26774. method, and it will be called when the selected item in the box changes.
  26775. @see ComboBox::addListener, ComboBox::removeListener
  26776. */
  26777. class JUCE_API ComboBoxListener
  26778. {
  26779. public:
  26780. /** Destructor. */
  26781. virtual ~ComboBoxListener() {}
  26782. /** Called when a ComboBox has its selected item changed.
  26783. */
  26784. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  26785. };
  26786. /**
  26787. A component that lets the user choose from a drop-down list of choices.
  26788. The combo-box has a list of text strings, each with an associated id number,
  26789. that will be shown in the drop-down list when the user clicks on the component.
  26790. The currently selected choice is displayed in the combo-box, and this can
  26791. either be read-only text, or editable.
  26792. To find out when the user selects a different item or edits the text, you
  26793. can register a ComboBoxListener to receive callbacks.
  26794. @see ComboBoxListener
  26795. */
  26796. class JUCE_API ComboBox : public Component,
  26797. public SettableTooltipClient,
  26798. private LabelListener,
  26799. private AsyncUpdater,
  26800. private Value::Listener
  26801. {
  26802. public:
  26803. /** Creates a combo-box.
  26804. On construction, the text field will be empty, so you should call the
  26805. setSelectedId() or setText() method to choose the initial value before
  26806. displaying it.
  26807. @param componentName the name to set for the component (see Component::setName())
  26808. */
  26809. explicit ComboBox (const String& componentName = String::empty);
  26810. /** Destructor. */
  26811. ~ComboBox();
  26812. /** Sets whether the test in the combo-box is editable.
  26813. The default state for a new ComboBox is non-editable, and can only be changed
  26814. by choosing from the drop-down list.
  26815. */
  26816. void setEditableText (bool isEditable);
  26817. /** Returns true if the text is directly editable.
  26818. @see setEditableText
  26819. */
  26820. bool isTextEditable() const throw();
  26821. /** Sets the style of justification to be used for positioning the text.
  26822. The default is Justification::centredLeft. The text is displayed using a
  26823. Label component inside the ComboBox.
  26824. */
  26825. void setJustificationType (const Justification& justification) throw();
  26826. /** Returns the current justification for the text box.
  26827. @see setJustificationType
  26828. */
  26829. const Justification getJustificationType() const throw();
  26830. /** Adds an item to be shown in the drop-down list.
  26831. @param newItemText the text of the item to show in the list
  26832. @param newItemId an associated ID number that can be set or retrieved - see
  26833. getSelectedId() and setSelectedId()
  26834. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  26835. */
  26836. void addItem (const String& newItemText,
  26837. int newItemId) throw();
  26838. /** Adds a separator line to the drop-down list.
  26839. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  26840. */
  26841. void addSeparator() throw();
  26842. /** Adds a heading to the drop-down list, so that you can group the items into
  26843. different sections.
  26844. The headings are indented slightly differently to set them apart from the
  26845. items on the list, and obviously can't be selected. You might want to add
  26846. separators between your sections too.
  26847. @see addItem, addSeparator
  26848. */
  26849. void addSectionHeading (const String& headingName) throw();
  26850. /** This allows items in the drop-down list to be selectively disabled.
  26851. When you add an item, it's enabled by default, but you can call this
  26852. method to change its status.
  26853. If you disable an item which is already selected, this won't change the
  26854. current selection - it just stops the user choosing that item from the list.
  26855. */
  26856. void setItemEnabled (int itemId,
  26857. bool shouldBeEnabled) throw();
  26858. /** Changes the text for an existing item.
  26859. */
  26860. void changeItemText (int itemId,
  26861. const String& newText) throw();
  26862. /** Removes all the items from the drop-down list.
  26863. If this call causes the content to be cleared, then a change-message
  26864. will be broadcast unless dontSendChangeMessage is true.
  26865. @see addItem, removeItem, getNumItems
  26866. */
  26867. void clear (bool dontSendChangeMessage = false);
  26868. /** Returns the number of items that have been added to the list.
  26869. Note that this doesn't include headers or separators.
  26870. */
  26871. int getNumItems() const throw();
  26872. /** Returns the text for one of the items in the list.
  26873. Note that this doesn't include headers or separators.
  26874. @param index the item's index from 0 to (getNumItems() - 1)
  26875. */
  26876. const String getItemText (int index) const throw();
  26877. /** Returns the ID for one of the items in the list.
  26878. Note that this doesn't include headers or separators.
  26879. @param index the item's index from 0 to (getNumItems() - 1)
  26880. */
  26881. int getItemId (int index) const throw();
  26882. /** Returns the index in the list of a particular item ID.
  26883. If no such ID is found, this will return -1.
  26884. */
  26885. int indexOfItemId (int itemId) const throw();
  26886. /** Returns the ID of the item that's currently shown in the box.
  26887. If no item is selected, or if the text is editable and the user
  26888. has entered something which isn't one of the items in the list, then
  26889. this will return 0.
  26890. @see setSelectedId, getSelectedItemIndex, getText
  26891. */
  26892. int getSelectedId() const throw();
  26893. /** Returns a Value object that can be used to get or set the selected item's ID.
  26894. You can call Value::referTo() on this object to make the combo box control
  26895. another Value object.
  26896. */
  26897. Value& getSelectedIdAsValue() throw() { return currentId; }
  26898. /** Sets one of the items to be the current selection.
  26899. This will set the ComboBox's text to that of the item that matches
  26900. this ID.
  26901. @param newItemId the new item to select
  26902. @param dontSendChangeMessage if set to true, this method won't trigger a
  26903. change notification
  26904. @see getSelectedId, setSelectedItemIndex, setText
  26905. */
  26906. void setSelectedId (int newItemId,
  26907. bool dontSendChangeMessage = false) throw();
  26908. /** Returns the index of the item that's currently shown in the box.
  26909. If no item is selected, or if the text is editable and the user
  26910. has entered something which isn't one of the items in the list, then
  26911. this will return -1.
  26912. @see setSelectedItemIndex, getSelectedId, getText
  26913. */
  26914. int getSelectedItemIndex() const throw();
  26915. /** Sets one of the items to be the current selection.
  26916. This will set the ComboBox's text to that of the item at the given
  26917. index in the list.
  26918. @param newItemIndex the new item to select
  26919. @param dontSendChangeMessage if set to true, this method won't trigger a
  26920. change notification
  26921. @see getSelectedItemIndex, setSelectedId, setText
  26922. */
  26923. void setSelectedItemIndex (int newItemIndex,
  26924. bool dontSendChangeMessage = false) throw();
  26925. /** Returns the text that is currently shown in the combo-box's text field.
  26926. If the ComboBox has editable text, then this text may have been edited
  26927. by the user; otherwise it will be one of the items from the list, or
  26928. possibly an empty string if nothing was selected.
  26929. @see setText, getSelectedId, getSelectedItemIndex
  26930. */
  26931. const String getText() const throw();
  26932. /** Sets the contents of the combo-box's text field.
  26933. The text passed-in will be set as the current text regardless of whether
  26934. it is one of the items in the list. If the current text isn't one of the
  26935. items, then getSelectedId() will return -1, otherwise it wil return
  26936. the approriate ID.
  26937. @param newText the text to select
  26938. @param dontSendChangeMessage if set to true, this method won't trigger a
  26939. change notification
  26940. @see getText
  26941. */
  26942. void setText (const String& newText,
  26943. bool dontSendChangeMessage = false) throw();
  26944. /** Programmatically opens the text editor to allow the user to edit the current item.
  26945. This is the same effect as when the box is clicked-on.
  26946. @see Label::showEditor();
  26947. */
  26948. void showEditor();
  26949. /** Registers a listener that will be called when the box's content changes. */
  26950. void addListener (ComboBoxListener* listener) throw();
  26951. /** Deregisters a previously-registered listener. */
  26952. void removeListener (ComboBoxListener* listener) throw();
  26953. /** Sets a message to display when there is no item currently selected.
  26954. @see getTextWhenNothingSelected
  26955. */
  26956. void setTextWhenNothingSelected (const String& newMessage) throw();
  26957. /** Returns the text that is shown when no item is selected.
  26958. @see setTextWhenNothingSelected
  26959. */
  26960. const String getTextWhenNothingSelected() const throw();
  26961. /** Sets the message to show when there are no items in the list, and the user clicks
  26962. on the drop-down box.
  26963. By default it just says "no choices", but this lets you change it to something more
  26964. meaningful.
  26965. */
  26966. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  26967. /** Returns the text shown when no items have been added to the list.
  26968. @see setTextWhenNoChoicesAvailable
  26969. */
  26970. const String getTextWhenNoChoicesAvailable() const throw();
  26971. /** Gives the ComboBox a tooltip. */
  26972. void setTooltip (const String& newTooltip);
  26973. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  26974. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26975. methods.
  26976. To change the colours of the menu that pops up
  26977. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26978. */
  26979. enum ColourIds
  26980. {
  26981. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  26982. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  26983. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  26984. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  26985. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  26986. };
  26987. /** @internal */
  26988. void labelTextChanged (Label*);
  26989. /** @internal */
  26990. void enablementChanged();
  26991. /** @internal */
  26992. void colourChanged();
  26993. /** @internal */
  26994. void focusGained (Component::FocusChangeType cause);
  26995. /** @internal */
  26996. void focusLost (Component::FocusChangeType cause);
  26997. /** @internal */
  26998. void handleAsyncUpdate();
  26999. /** @internal */
  27000. const String getTooltip() { return label->getTooltip(); }
  27001. /** @internal */
  27002. void mouseDown (const MouseEvent&);
  27003. /** @internal */
  27004. void mouseDrag (const MouseEvent&);
  27005. /** @internal */
  27006. void mouseUp (const MouseEvent&);
  27007. /** @internal */
  27008. void lookAndFeelChanged();
  27009. /** @internal */
  27010. void paint (Graphics&);
  27011. /** @internal */
  27012. void resized();
  27013. /** @internal */
  27014. bool keyStateChanged (bool isKeyDown);
  27015. /** @internal */
  27016. bool keyPressed (const KeyPress&);
  27017. /** @internal */
  27018. void valueChanged (Value&);
  27019. juce_UseDebuggingNewOperator
  27020. private:
  27021. struct ItemInfo
  27022. {
  27023. String name;
  27024. int itemId;
  27025. bool isEnabled : 1, isHeading : 1;
  27026. bool isSeparator() const throw();
  27027. bool isRealItem() const throw();
  27028. };
  27029. OwnedArray <ItemInfo> items;
  27030. Value currentId;
  27031. int lastCurrentId;
  27032. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  27033. ListenerList <ComboBoxListener> listeners;
  27034. ScopedPointer<Label> label;
  27035. String textWhenNothingSelected, noChoicesMessage;
  27036. void showPopup();
  27037. ItemInfo* getItemForId (int itemId) const throw();
  27038. ItemInfo* getItemForIndex (int index) const throw();
  27039. ComboBox (const ComboBox&);
  27040. ComboBox& operator= (const ComboBox&);
  27041. };
  27042. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  27043. /*** End of inlined file: juce_ComboBox.h ***/
  27044. /**
  27045. Manages the state of some audio and midi i/o devices.
  27046. This class keeps tracks of a currently-selected audio device, through
  27047. with which it continuously streams data from an audio callback, as well as
  27048. one or more midi inputs.
  27049. The idea is that your application will create one global instance of this object,
  27050. and let it take care of creating and deleting specific types of audio devices
  27051. internally. So when the device is changed, your callbacks will just keep running
  27052. without having to worry about this.
  27053. The manager can save and reload all of its device settings as XML, which
  27054. makes it very easy for you to save and reload the audio setup of your
  27055. application.
  27056. And to make it easy to let the user change its settings, there's a component
  27057. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  27058. device selection/sample-rate/latency controls.
  27059. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  27060. call addAudioCallback() to register your audio callback with it, and use that to process
  27061. your audio data.
  27062. The manager also acts as a handy hub for incoming midi messages, allowing a
  27063. listener to register for messages from either a specific midi device, or from whatever
  27064. the current default midi input device is. The listener then doesn't have to worry about
  27065. re-registering with different midi devices if they are changed or deleted.
  27066. And yet another neat trick is that amount of CPU time being used is measured and
  27067. available with the getCpuUsage() method.
  27068. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  27069. listeners whenever one of its settings is changed.
  27070. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  27071. */
  27072. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  27073. {
  27074. public:
  27075. /** Creates a default AudioDeviceManager.
  27076. Initially no audio device will be selected. You should call the initialise() method
  27077. and register an audio callback with setAudioCallback() before it'll be able to
  27078. actually make any noise.
  27079. */
  27080. AudioDeviceManager();
  27081. /** Destructor. */
  27082. ~AudioDeviceManager();
  27083. /**
  27084. This structure holds a set of properties describing the current audio setup.
  27085. @see AudioDeviceManager::setAudioDeviceSetup()
  27086. */
  27087. struct JUCE_API AudioDeviceSetup
  27088. {
  27089. AudioDeviceSetup();
  27090. bool operator== (const AudioDeviceSetup& other) const;
  27091. /** The name of the audio device used for output.
  27092. The name has to be one of the ones listed by the AudioDeviceManager's currently
  27093. selected device type.
  27094. This may be the same as the input device.
  27095. */
  27096. String outputDeviceName;
  27097. /** The name of the audio device used for input.
  27098. This may be the same as the output device.
  27099. */
  27100. String inputDeviceName;
  27101. /** The current sample rate.
  27102. This rate is used for both the input and output devices.
  27103. */
  27104. double sampleRate;
  27105. /** The buffer size, in samples.
  27106. This buffer size is used for both the input and output devices.
  27107. */
  27108. int bufferSize;
  27109. /** The set of active input channels.
  27110. The bits that are set in this array indicate the channels of the
  27111. input device that are active.
  27112. */
  27113. BigInteger inputChannels;
  27114. /** If this is true, it indicates that the inputChannels array
  27115. should be ignored, and instead, the device's default channels
  27116. should be used.
  27117. */
  27118. bool useDefaultInputChannels;
  27119. /** The set of active output channels.
  27120. The bits that are set in this array indicate the channels of the
  27121. input device that are active.
  27122. */
  27123. BigInteger outputChannels;
  27124. /** If this is true, it indicates that the outputChannels array
  27125. should be ignored, and instead, the device's default channels
  27126. should be used.
  27127. */
  27128. bool useDefaultOutputChannels;
  27129. };
  27130. /** Opens a set of audio devices ready for use.
  27131. This will attempt to open either a default audio device, or one that was
  27132. previously saved as XML.
  27133. @param numInputChannelsNeeded a minimum number of input channels needed
  27134. by your app.
  27135. @param numOutputChannelsNeeded a minimum number of output channels to open
  27136. @param savedState either a previously-saved state that was produced
  27137. by createStateXml(), or 0 if you want the manager
  27138. to choose the best device to open.
  27139. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  27140. fails to open, then a default device will be used
  27141. instead. If false, then on failure, no device is
  27142. opened.
  27143. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  27144. name, then that will be used as the default device
  27145. (assuming that there wasn't one specified in the XML).
  27146. The string can actually be a simple wildcard, containing "*"
  27147. and "?" characters
  27148. @param preferredSetupOptions if this is non-null, the structure will be used as the
  27149. set of preferred settings when opening the device. If you
  27150. use this parameter, the preferredDefaultDeviceName
  27151. field will be ignored
  27152. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27153. */
  27154. const String initialise (int numInputChannelsNeeded,
  27155. int numOutputChannelsNeeded,
  27156. const XmlElement* savedState,
  27157. bool selectDefaultDeviceOnFailure,
  27158. const String& preferredDefaultDeviceName = String::empty,
  27159. const AudioDeviceSetup* preferredSetupOptions = 0);
  27160. /** Returns some XML representing the current state of the manager.
  27161. This stores the current device, its samplerate, block size, etc, and
  27162. can be restored later with initialise().
  27163. */
  27164. XmlElement* createStateXml() const;
  27165. /** Returns the current device properties that are in use.
  27166. @see setAudioDeviceSetup
  27167. */
  27168. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  27169. /** Changes the current device or its settings.
  27170. If you want to change a device property, like the current sample rate or
  27171. block size, you can call getAudioDeviceSetup() to retrieve the current
  27172. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  27173. and pass it back into this method to apply the new settings.
  27174. @param newSetup the settings that you'd like to use
  27175. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  27176. settings will be taken as having been explicitly chosen by the
  27177. user, and the next time createStateXml() is called, these settings
  27178. will be returned. If it's false, then the device is treated as a
  27179. temporary or default device, and a call to createStateXml() will
  27180. return either the last settings that were made with treatAsChosenDevice
  27181. as true, or the last XML settings that were passed into initialise().
  27182. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27183. @see getAudioDeviceSetup
  27184. */
  27185. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  27186. bool treatAsChosenDevice);
  27187. /** Returns the currently-active audio device. */
  27188. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  27189. /** Returns the type of audio device currently in use.
  27190. @see setCurrentAudioDeviceType
  27191. */
  27192. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  27193. /** Returns the currently active audio device type object.
  27194. Don't keep a copy of this pointer - it's owned by the device manager and could
  27195. change at any time.
  27196. */
  27197. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  27198. /** Changes the class of audio device being used.
  27199. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  27200. this because there's only one type: CoreAudio.
  27201. For a list of types, see getAvailableDeviceTypes().
  27202. */
  27203. void setCurrentAudioDeviceType (const String& type,
  27204. bool treatAsChosenDevice);
  27205. /** Closes the currently-open device.
  27206. You can call restartLastAudioDevice() later to reopen it in the same state
  27207. that it was just in.
  27208. */
  27209. void closeAudioDevice();
  27210. /** Tries to reload the last audio device that was running.
  27211. Note that this only reloads the last device that was running before
  27212. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  27213. and can only be called after a device has been opened with SetAudioDevice().
  27214. If a device is already open, this call will do nothing.
  27215. */
  27216. void restartLastAudioDevice();
  27217. /** Registers an audio callback to be used.
  27218. The manager will redirect callbacks from whatever audio device is currently
  27219. in use to all registered callback objects. If more than one callback is
  27220. active, they will all be given the same input data, and their outputs will
  27221. be summed.
  27222. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  27223. object before returning.
  27224. To remove a callback, use removeAudioCallback().
  27225. */
  27226. void addAudioCallback (AudioIODeviceCallback* newCallback);
  27227. /** Deregisters a previously added callback.
  27228. If necessary, this method will invoke audioDeviceStopped() on the callback
  27229. object before returning.
  27230. @see addAudioCallback
  27231. */
  27232. void removeAudioCallback (AudioIODeviceCallback* callback);
  27233. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  27234. Returns a value between 0 and 1.0
  27235. */
  27236. double getCpuUsage() const;
  27237. /** Enables or disables a midi input device.
  27238. The list of devices can be obtained with the MidiInput::getDevices() method.
  27239. Any incoming messages from enabled input devices will be forwarded on to all the
  27240. listeners that have been registered with the addMidiInputCallback() method. They
  27241. can either register for messages from a particular device, or from just the
  27242. "default" midi input.
  27243. Routing the midi input via an AudioDeviceManager means that when a listener
  27244. registers for the default midi input, this default device can be changed by the
  27245. manager without the listeners having to know about it or re-register.
  27246. It also means that a listener can stay registered for a midi input that is disabled
  27247. or not present, so that when the input is re-enabled, the listener will start
  27248. receiving messages again.
  27249. @see addMidiInputCallback, isMidiInputEnabled
  27250. */
  27251. void setMidiInputEnabled (const String& midiInputDeviceName,
  27252. bool enabled);
  27253. /** Returns true if a given midi input device is being used.
  27254. @see setMidiInputEnabled
  27255. */
  27256. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  27257. /** Registers a listener for callbacks when midi events arrive from a midi input.
  27258. The device name can be empty to indicate that it wants events from whatever the
  27259. current "default" device is. Or it can be the name of one of the midi input devices
  27260. (see MidiInput::getDevices() for the names).
  27261. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  27262. events forwarded on to listeners.
  27263. */
  27264. void addMidiInputCallback (const String& midiInputDeviceName,
  27265. MidiInputCallback* callback);
  27266. /** Removes a listener that was previously registered with addMidiInputCallback().
  27267. */
  27268. void removeMidiInputCallback (const String& midiInputDeviceName,
  27269. MidiInputCallback* callback);
  27270. /** Sets a midi output device to use as the default.
  27271. The list of devices can be obtained with the MidiOutput::getDevices() method.
  27272. The specified device will be opened automatically and can be retrieved with the
  27273. getDefaultMidiOutput() method.
  27274. Pass in an empty string to deselect all devices. For the default device, you
  27275. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  27276. @see getDefaultMidiOutput, getDefaultMidiOutputName
  27277. */
  27278. void setDefaultMidiOutput (const String& deviceName);
  27279. /** Returns the name of the default midi output.
  27280. @see setDefaultMidiOutput, getDefaultMidiOutput
  27281. */
  27282. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  27283. /** Returns the current default midi output device.
  27284. If no device has been selected, or the device can't be opened, this will
  27285. return 0.
  27286. @see getDefaultMidiOutputName
  27287. */
  27288. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  27289. /** Returns a list of the types of device supported.
  27290. */
  27291. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  27292. /** Creates a list of available types.
  27293. This will add a set of new AudioIODeviceType objects to the specified list, to
  27294. represent each available types of device.
  27295. You can override this if your app needs to do something specific, like avoid
  27296. using DirectSound devices, etc.
  27297. */
  27298. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  27299. /** Plays a beep through the current audio device.
  27300. This is here to allow the audio setup UI panels to easily include a "test"
  27301. button so that the user can check where the audio is coming from.
  27302. */
  27303. void playTestSound();
  27304. /** Turns on level-measuring.
  27305. When enabled, the device manager will measure the peak input level
  27306. across all channels, and you can get this level by calling getCurrentInputLevel().
  27307. This is mainly intended for audio setup UI panels to use to create a mic
  27308. level display, so that the user can check that they've selected the right
  27309. device.
  27310. A simple filter is used to make the level decay smoothly, but this is
  27311. only intended for giving rough feedback, and not for any kind of accurate
  27312. measurement.
  27313. */
  27314. void enableInputLevelMeasurement (bool enableMeasurement);
  27315. /** Returns the current input level.
  27316. To use this, you must first enable it by calling enableInputLevelMeasurement().
  27317. See enableInputLevelMeasurement() for more info.
  27318. */
  27319. double getCurrentInputLevel() const;
  27320. juce_UseDebuggingNewOperator
  27321. private:
  27322. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  27323. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  27324. AudioDeviceSetup currentSetup;
  27325. ScopedPointer <AudioIODevice> currentAudioDevice;
  27326. SortedSet <AudioIODeviceCallback*> callbacks;
  27327. int numInputChansNeeded, numOutputChansNeeded;
  27328. String currentDeviceType;
  27329. BigInteger inputChannels, outputChannels;
  27330. ScopedPointer <XmlElement> lastExplicitSettings;
  27331. mutable bool listNeedsScanning;
  27332. bool useInputNames;
  27333. int inputLevelMeasurementEnabledCount;
  27334. double inputLevel;
  27335. ScopedPointer <AudioSampleBuffer> testSound;
  27336. int testSoundPosition;
  27337. AudioSampleBuffer tempBuffer;
  27338. StringArray midiInsFromXml;
  27339. OwnedArray <MidiInput> enabledMidiInputs;
  27340. Array <MidiInputCallback*> midiCallbacks;
  27341. Array <MidiInput*> midiCallbackDevices;
  27342. String defaultMidiOutputName;
  27343. ScopedPointer <MidiOutput> defaultMidiOutput;
  27344. CriticalSection audioCallbackLock, midiCallbackLock;
  27345. double cpuUsageMs, timeToCpuScale;
  27346. class CallbackHandler : public AudioIODeviceCallback,
  27347. public MidiInputCallback
  27348. {
  27349. public:
  27350. AudioDeviceManager* owner;
  27351. void audioDeviceIOCallback (const float** inputChannelData,
  27352. int totalNumInputChannels,
  27353. float** outputChannelData,
  27354. int totalNumOutputChannels,
  27355. int numSamples);
  27356. void audioDeviceAboutToStart (AudioIODevice*);
  27357. void audioDeviceStopped();
  27358. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  27359. };
  27360. CallbackHandler callbackHandler;
  27361. friend class CallbackHandler;
  27362. void audioDeviceIOCallbackInt (const float** inputChannelData,
  27363. int totalNumInputChannels,
  27364. float** outputChannelData,
  27365. int totalNumOutputChannels,
  27366. int numSamples);
  27367. void audioDeviceAboutToStartInt (AudioIODevice* device);
  27368. void audioDeviceStoppedInt();
  27369. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  27370. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  27371. const BigInteger& ins, const BigInteger& outs);
  27372. void stopDevice();
  27373. void updateXml();
  27374. void createDeviceTypesIfNeeded();
  27375. void scanDevicesIfNeeded();
  27376. void deleteCurrentDevice();
  27377. double chooseBestSampleRate (double preferred) const;
  27378. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  27379. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  27380. AudioDeviceManager (const AudioDeviceManager&);
  27381. AudioDeviceManager& operator= (const AudioDeviceManager&);
  27382. };
  27383. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  27384. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  27385. #endif
  27386. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  27387. #endif
  27388. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  27389. #endif
  27390. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  27391. #endif
  27392. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  27393. #endif
  27394. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27395. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  27396. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27397. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27398. /**
  27399. A set of routines to convert buffers of 32-bit floating point data to and from
  27400. various integer formats.
  27401. */
  27402. class JUCE_API AudioDataConverters
  27403. {
  27404. public:
  27405. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27406. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  27407. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27408. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  27409. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27410. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27411. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27412. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  27413. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27414. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  27415. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27416. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  27417. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27418. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27419. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27420. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  27421. enum DataFormat
  27422. {
  27423. int16LE,
  27424. int16BE,
  27425. int24LE,
  27426. int24BE,
  27427. int32LE,
  27428. int32BE,
  27429. float32LE,
  27430. float32BE,
  27431. };
  27432. static void convertFloatToFormat (DataFormat destFormat,
  27433. const float* source, void* dest, int numSamples);
  27434. static void convertFormatToFloat (DataFormat sourceFormat,
  27435. const void* source, float* dest, int numSamples);
  27436. static void interleaveSamples (const float** source, float* dest,
  27437. int numSamples, int numChannels);
  27438. static void deinterleaveSamples (const float* source, float** dest,
  27439. int numSamples, int numChannels);
  27440. private:
  27441. AudioDataConverters();
  27442. AudioDataConverters (const AudioDataConverters&);
  27443. AudioDataConverters& operator= (const AudioDataConverters&);
  27444. };
  27445. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  27446. /*** End of inlined file: juce_AudioDataConverters.h ***/
  27447. #endif
  27448. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  27449. #endif
  27450. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  27451. #endif
  27452. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  27453. #endif
  27454. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  27455. /*** Start of inlined file: juce_MidiFile.h ***/
  27456. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  27457. #define __JUCE_MIDIFILE_JUCEHEADER__
  27458. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  27459. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  27460. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  27461. /**
  27462. A sequence of timestamped midi messages.
  27463. This allows the sequence to be manipulated, and also to be read from and
  27464. written to a standard midi file.
  27465. @see MidiMessage, MidiFile
  27466. */
  27467. class JUCE_API MidiMessageSequence
  27468. {
  27469. public:
  27470. /** Creates an empty midi sequence object. */
  27471. MidiMessageSequence();
  27472. /** Creates a copy of another sequence. */
  27473. MidiMessageSequence (const MidiMessageSequence& other);
  27474. /** Replaces this sequence with another one. */
  27475. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  27476. /** Destructor. */
  27477. ~MidiMessageSequence();
  27478. /** Structure used to hold midi events in the sequence.
  27479. These structures act as 'handles' on the events as they are moved about in
  27480. the list, and make it quick to find the matching note-offs for note-on events.
  27481. @see MidiMessageSequence::getEventPointer
  27482. */
  27483. class MidiEventHolder
  27484. {
  27485. public:
  27486. /** Destructor. */
  27487. ~MidiEventHolder();
  27488. /** The message itself, whose timestamp is used to specify the event's time.
  27489. */
  27490. MidiMessage message;
  27491. /** The matching note-off event (if this is a note-on event).
  27492. If this isn't a note-on, this pointer will be null.
  27493. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  27494. note-offs up-to-date after events have been moved around in the sequence
  27495. or deleted.
  27496. */
  27497. MidiEventHolder* noteOffObject;
  27498. juce_UseDebuggingNewOperator
  27499. private:
  27500. friend class MidiMessageSequence;
  27501. MidiEventHolder (const MidiMessage& message);
  27502. };
  27503. /** Clears the sequence. */
  27504. void clear();
  27505. /** Returns the number of events in the sequence. */
  27506. int getNumEvents() const;
  27507. /** Returns a pointer to one of the events. */
  27508. MidiEventHolder* getEventPointer (int index) const;
  27509. /** Returns the time of the note-up that matches the note-on at this index.
  27510. If the event at this index isn't a note-on, it'll just return 0.
  27511. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  27512. */
  27513. double getTimeOfMatchingKeyUp (int index) const;
  27514. /** Returns the index of the note-up that matches the note-on at this index.
  27515. If the event at this index isn't a note-on, it'll just return -1.
  27516. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  27517. */
  27518. int getIndexOfMatchingKeyUp (int index) const;
  27519. /** Returns the index of an event. */
  27520. int getIndexOf (MidiEventHolder* event) const;
  27521. /** Returns the index of the first event on or after the given timestamp.
  27522. If the time is beyond the end of the sequence, this will return the
  27523. number of events.
  27524. */
  27525. int getNextIndexAtTime (double timeStamp) const;
  27526. /** Returns the timestamp of the first event in the sequence.
  27527. @see getEndTime
  27528. */
  27529. double getStartTime() const;
  27530. /** Returns the timestamp of the last event in the sequence.
  27531. @see getStartTime
  27532. */
  27533. double getEndTime() const;
  27534. /** Returns the timestamp of the event at a given index.
  27535. If the index is out-of-range, this will return 0.0
  27536. */
  27537. double getEventTime (int index) const;
  27538. /** Inserts a midi message into the sequence.
  27539. The index at which the new message gets inserted will depend on its timestamp,
  27540. because the sequence is kept sorted.
  27541. Remember to call updateMatchedPairs() after adding note-on events.
  27542. @param newMessage the new message to add (an internal copy will be made)
  27543. @param timeAdjustment an optional value to add to the timestamp of the message
  27544. that will be inserted
  27545. @see updateMatchedPairs
  27546. */
  27547. void addEvent (const MidiMessage& newMessage,
  27548. double timeAdjustment = 0);
  27549. /** Deletes one of the events in the sequence.
  27550. Remember to call updateMatchedPairs() after removing events.
  27551. @param index the index of the event to delete
  27552. @param deleteMatchingNoteUp whether to also remove the matching note-off
  27553. if the event you're removing is a note-on
  27554. */
  27555. void deleteEvent (int index, bool deleteMatchingNoteUp);
  27556. /** Merges another sequence into this one.
  27557. Remember to call updateMatchedPairs() after using this method.
  27558. @param other the sequence to add from
  27559. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  27560. as they are read from the other sequence
  27561. @param firstAllowableDestTime events will not be added if their time is earlier
  27562. than this time. (This is after their time has been adjusted
  27563. by the timeAdjustmentDelta)
  27564. @param endOfAllowableDestTimes events will not be added if their time is equal to
  27565. or greater than this time. (This is after their time has
  27566. been adjusted by the timeAdjustmentDelta)
  27567. */
  27568. void addSequence (const MidiMessageSequence& other,
  27569. double timeAdjustmentDelta,
  27570. double firstAllowableDestTime,
  27571. double endOfAllowableDestTimes);
  27572. /** Makes sure all the note-on and note-off pairs are up-to-date.
  27573. Call this after moving messages about or deleting/adding messages, and it
  27574. will scan the list and make sure all the note-offs in the MidiEventHolder
  27575. structures are pointing at the correct ones.
  27576. */
  27577. void updateMatchedPairs();
  27578. /** Copies all the messages for a particular midi channel to another sequence.
  27579. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  27580. @param destSequence the sequence that the chosen events should be copied to
  27581. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  27582. channel) will also be copied across.
  27583. @see extractSysExMessages
  27584. */
  27585. void extractMidiChannelMessages (int channelNumberToExtract,
  27586. MidiMessageSequence& destSequence,
  27587. bool alsoIncludeMetaEvents) const;
  27588. /** Copies all midi sys-ex messages to another sequence.
  27589. @param destSequence this is the sequence to which any sys-exes in this sequence
  27590. will be added
  27591. @see extractMidiChannelMessages
  27592. */
  27593. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  27594. /** Removes any messages in this sequence that have a specific midi channel.
  27595. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  27596. */
  27597. void deleteMidiChannelMessages (int channelNumberToRemove);
  27598. /** Removes any sys-ex messages from this sequence.
  27599. */
  27600. void deleteSysExMessages();
  27601. /** Adds an offset to the timestamps of all events in the sequence.
  27602. @param deltaTime the amount to add to each timestamp.
  27603. */
  27604. void addTimeToMessages (double deltaTime);
  27605. /** Scans through the sequence to determine the state of any midi controllers at
  27606. a given time.
  27607. This will create a sequence of midi controller changes that can be
  27608. used to set all midi controllers to the state they would be in at the
  27609. specified time within this sequence.
  27610. As well as controllers, it will also recreate the midi program number
  27611. and pitch bend position.
  27612. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  27613. for other channels will be ignored.
  27614. @param time the time at which you want to find out the state - there are
  27615. no explicit units for this time measurement, it's the same units
  27616. as used for the timestamps of the messages
  27617. @param resultMessages an array to which midi controller-change messages will be added. This
  27618. will be the minimum number of controller changes to recreate the
  27619. state at the required time.
  27620. */
  27621. void createControllerUpdatesForTime (int channelNumber, double time,
  27622. OwnedArray<MidiMessage>& resultMessages);
  27623. /** Swaps this sequence with another one. */
  27624. void swapWith (MidiMessageSequence& other) throw();
  27625. juce_UseDebuggingNewOperator
  27626. /** @internal */
  27627. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  27628. const MidiMessageSequence::MidiEventHolder* second) throw();
  27629. private:
  27630. friend class MidiFile;
  27631. OwnedArray <MidiEventHolder> list;
  27632. void sort();
  27633. };
  27634. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  27635. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  27636. /**
  27637. Reads/writes standard midi format files.
  27638. To read a midi file, create a MidiFile object and call its readFrom() method. You
  27639. can then get the individual midi tracks from it using the getTrack() method.
  27640. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  27641. to it using the addTrack() method, and then call its writeTo() method to stream
  27642. it out.
  27643. @see MidiMessageSequence
  27644. */
  27645. class JUCE_API MidiFile
  27646. {
  27647. public:
  27648. /** Creates an empty MidiFile object.
  27649. */
  27650. MidiFile();
  27651. /** Destructor. */
  27652. ~MidiFile();
  27653. /** Returns the number of tracks in the file.
  27654. @see getTrack, addTrack
  27655. */
  27656. int getNumTracks() const throw();
  27657. /** Returns a pointer to one of the tracks in the file.
  27658. @returns a pointer to the track, or 0 if the index is out-of-range
  27659. @see getNumTracks, addTrack
  27660. */
  27661. const MidiMessageSequence* getTrack (const int index) const throw();
  27662. /** Adds a midi track to the file.
  27663. This will make its own internal copy of the sequence that is passed-in.
  27664. @see getNumTracks, getTrack
  27665. */
  27666. void addTrack (const MidiMessageSequence& trackSequence);
  27667. /** Removes all midi tracks from the file.
  27668. @see getNumTracks
  27669. */
  27670. void clear();
  27671. /** Returns the raw time format code that will be written to a stream.
  27672. After reading a midi file, this method will return the time-format that
  27673. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  27674. or setSmpteTimeFormat() methods.
  27675. If the value returned is positive, it indicates the number of midi ticks
  27676. per quarter-note - see setTicksPerQuarterNote().
  27677. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  27678. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  27679. */
  27680. short getTimeFormat() const throw();
  27681. /** Sets the time format to use when this file is written to a stream.
  27682. If this is called, the file will be written as bars/beats using the
  27683. specified resolution, rather than SMPTE absolute times, as would be
  27684. used if setSmpteTimeFormat() had been called instead.
  27685. @param ticksPerQuarterNote e.g. 96, 960
  27686. @see setSmpteTimeFormat
  27687. */
  27688. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  27689. /** Sets the time format to use when this file is written to a stream.
  27690. If this is called, the file will be written using absolute times, rather
  27691. than bars/beats as would be the case if setTicksPerBeat() had been called
  27692. instead.
  27693. @param framesPerSecond must be 24, 25, 29 or 30
  27694. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  27695. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  27696. timing, setSmpteTimeFormat (25, 40)
  27697. @see setTicksPerBeat
  27698. */
  27699. void setSmpteTimeFormat (const int framesPerSecond,
  27700. const int subframeResolution) throw();
  27701. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  27702. Useful for finding the positions of all the tempo changes in a file.
  27703. @param tempoChangeEvents a list to which all the events will be added
  27704. */
  27705. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  27706. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  27707. Useful for finding the positions of all the tempo changes in a file.
  27708. @param timeSigEvents a list to which all the events will be added
  27709. */
  27710. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  27711. /** Returns the latest timestamp in any of the tracks.
  27712. (Useful for finding the length of the file).
  27713. */
  27714. double getLastTimestamp() const;
  27715. /** Reads a midi file format stream.
  27716. After calling this, you can get the tracks that were read from the file by using the
  27717. getNumTracks() and getTrack() methods.
  27718. The timestamps of the midi events in the tracks will represent their positions in
  27719. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  27720. method.
  27721. @returns true if the stream was read successfully
  27722. */
  27723. bool readFrom (InputStream& sourceStream);
  27724. /** Writes the midi tracks as a standard midi file.
  27725. @returns true if the operation succeeded.
  27726. */
  27727. bool writeTo (OutputStream& destStream);
  27728. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  27729. This will use the midi time format and tempo/time signature info in the
  27730. tracks to convert all the timestamps to absolute values in seconds.
  27731. */
  27732. void convertTimestampTicksToSeconds();
  27733. juce_UseDebuggingNewOperator
  27734. /** @internal */
  27735. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  27736. const MidiMessageSequence::MidiEventHolder* const second);
  27737. private:
  27738. OwnedArray <MidiMessageSequence> tracks;
  27739. short timeFormat;
  27740. MidiFile (const MidiFile&);
  27741. MidiFile& operator= (const MidiFile&);
  27742. void readNextTrack (const uint8* data, int size);
  27743. void writeTrack (OutputStream& mainOut, const int trackNum);
  27744. };
  27745. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  27746. /*** End of inlined file: juce_MidiFile.h ***/
  27747. #endif
  27748. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  27749. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  27750. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  27751. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  27752. class MidiKeyboardState;
  27753. /**
  27754. Receives events from a MidiKeyboardState object.
  27755. @see MidiKeyboardState
  27756. */
  27757. class JUCE_API MidiKeyboardStateListener
  27758. {
  27759. public:
  27760. MidiKeyboardStateListener() throw() {}
  27761. virtual ~MidiKeyboardStateListener() {}
  27762. /** Called when one of the MidiKeyboardState's keys is pressed.
  27763. This will be called synchronously when the state is either processing a
  27764. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  27765. when a note is being played with its MidiKeyboardState::noteOn() method.
  27766. Note that this callback could happen from an audio callback thread, so be
  27767. careful not to block, and avoid any UI activity in the callback.
  27768. */
  27769. virtual void handleNoteOn (MidiKeyboardState* source,
  27770. int midiChannel, int midiNoteNumber, float velocity) = 0;
  27771. /** Called when one of the MidiKeyboardState's keys is released.
  27772. This will be called synchronously when the state is either processing a
  27773. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  27774. when a note is being played with its MidiKeyboardState::noteOff() method.
  27775. Note that this callback could happen from an audio callback thread, so be
  27776. careful not to block, and avoid any UI activity in the callback.
  27777. */
  27778. virtual void handleNoteOff (MidiKeyboardState* source,
  27779. int midiChannel, int midiNoteNumber) = 0;
  27780. };
  27781. /**
  27782. Represents a piano keyboard, keeping track of which keys are currently pressed.
  27783. This object can parse a stream of midi events, using them to update its idea
  27784. of which keys are pressed for each individiual midi channel.
  27785. When keys go up or down, it can broadcast these events to listener objects.
  27786. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  27787. methods, and midi messages for these events will be merged into the
  27788. midi stream that gets processed by processNextMidiBuffer().
  27789. */
  27790. class JUCE_API MidiKeyboardState
  27791. {
  27792. public:
  27793. MidiKeyboardState();
  27794. ~MidiKeyboardState();
  27795. /** Resets the state of the object.
  27796. All internal data for all the channels is reset, but no events are sent as a
  27797. result.
  27798. If you want to release any keys that are currently down, and to send out note-up
  27799. midi messages for this, use the allNotesOff() method instead.
  27800. */
  27801. void reset();
  27802. /** Returns true if the given midi key is currently held down for the given midi channel.
  27803. The channel number must be between 1 and 16. If you want to see if any notes are
  27804. on for a range of channels, use the isNoteOnForChannels() method.
  27805. */
  27806. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  27807. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  27808. The channel mask has a bit set for each midi channel you want to test for - bit
  27809. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  27810. If a note is on for at least one of the specified channels, this returns true.
  27811. */
  27812. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  27813. /** Turns a specified note on.
  27814. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  27815. next call to processNextMidiBuffer().
  27816. It will also trigger a synchronous callback to the listeners to tell them that the key has
  27817. gone down.
  27818. */
  27819. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  27820. /** Turns a specified note off.
  27821. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  27822. next call to processNextMidiBuffer().
  27823. It will also trigger a synchronous callback to the listeners to tell them that the key has
  27824. gone up.
  27825. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  27826. */
  27827. void noteOff (const int midiChannel, const int midiNoteNumber);
  27828. /** This will turn off any currently-down notes for the given midi channel.
  27829. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  27830. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  27831. and events being added to the midi stream.
  27832. */
  27833. void allNotesOff (const int midiChannel);
  27834. /** Looks at a key-up/down event and uses it to update the state of this object.
  27835. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  27836. instead.
  27837. */
  27838. void processNextMidiEvent (const MidiMessage& message);
  27839. /** Scans a midi stream for up/down events and adds its own events to it.
  27840. This will look for any up/down events and use them to update the internal state,
  27841. synchronously making suitable callbacks to the listeners.
  27842. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  27843. and noteOff() calls will be added into the buffer.
  27844. Only the section of the buffer whose timestamps are between startSample and
  27845. (startSample + numSamples) will be affected, and any events added will be placed
  27846. between these times.
  27847. If you're going to use this method, you'll need to keep calling it regularly for
  27848. it to work satisfactorily.
  27849. To process a single midi event at a time, use the processNextMidiEvent() method
  27850. instead.
  27851. */
  27852. void processNextMidiBuffer (MidiBuffer& buffer,
  27853. const int startSample,
  27854. const int numSamples,
  27855. const bool injectIndirectEvents);
  27856. /** Registers a listener for callbacks when keys go up or down.
  27857. @see removeListener
  27858. */
  27859. void addListener (MidiKeyboardStateListener* const listener) throw();
  27860. /** Deregisters a listener.
  27861. @see addListener
  27862. */
  27863. void removeListener (MidiKeyboardStateListener* const listener) throw();
  27864. juce_UseDebuggingNewOperator
  27865. private:
  27866. CriticalSection lock;
  27867. uint16 noteStates [128];
  27868. MidiBuffer eventsToAdd;
  27869. Array <MidiKeyboardStateListener*> listeners;
  27870. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  27871. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  27872. MidiKeyboardState (const MidiKeyboardState&);
  27873. MidiKeyboardState& operator= (const MidiKeyboardState&);
  27874. };
  27875. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  27876. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  27877. #endif
  27878. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  27879. #endif
  27880. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  27881. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  27882. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  27883. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  27884. /**
  27885. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  27886. processing by a block-based audio callback.
  27887. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  27888. so it can easily use a midi input or keyboard component as its source.
  27889. @see MidiMessage, MidiInput
  27890. */
  27891. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  27892. public MidiInputCallback
  27893. {
  27894. public:
  27895. /** Creates a MidiMessageCollector. */
  27896. MidiMessageCollector();
  27897. /** Destructor. */
  27898. ~MidiMessageCollector();
  27899. /** Clears any messages from the queue.
  27900. You need to call this method before starting to use the collector, so that
  27901. it knows the correct sample rate to use.
  27902. */
  27903. void reset (double sampleRate);
  27904. /** Takes an incoming real-time message and adds it to the queue.
  27905. The message's timestamp is taken, and it will be ready for retrieval as part
  27906. of the block returned by the next call to removeNextBlockOfMessages().
  27907. This method is fully thread-safe when overlapping calls are made with
  27908. removeNextBlockOfMessages().
  27909. */
  27910. void addMessageToQueue (const MidiMessage& message);
  27911. /** Removes all the pending messages from the queue as a buffer.
  27912. This will also correct the messages' timestamps to make sure they're in
  27913. the range 0 to numSamples - 1.
  27914. This call should be made regularly by something like an audio processing
  27915. callback, because the time that it happens is used in calculating the
  27916. midi event positions.
  27917. This method is fully thread-safe when overlapping calls are made with
  27918. addMessageToQueue().
  27919. */
  27920. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  27921. /** @internal */
  27922. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  27923. /** @internal */
  27924. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  27925. /** @internal */
  27926. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  27927. juce_UseDebuggingNewOperator
  27928. private:
  27929. double lastCallbackTime;
  27930. CriticalSection midiCallbackLock;
  27931. MidiBuffer incomingMessages;
  27932. double sampleRate;
  27933. MidiMessageCollector (const MidiMessageCollector&);
  27934. MidiMessageCollector& operator= (const MidiMessageCollector&);
  27935. };
  27936. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  27937. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  27938. #endif
  27939. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  27940. #endif
  27941. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27942. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  27943. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27944. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  27945. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  27946. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  27947. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  27948. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  27949. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  27950. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  27951. /*** Start of inlined file: juce_AudioProcessor.h ***/
  27952. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  27953. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  27954. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  27955. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  27956. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  27957. class AudioProcessor;
  27958. /**
  27959. Base class for the component that acts as the GUI for an AudioProcessor.
  27960. Derive your editor component from this class, and create an instance of it
  27961. by overriding the AudioProcessor::createEditor() method.
  27962. @see AudioProcessor, GenericAudioProcessorEditor
  27963. */
  27964. class JUCE_API AudioProcessorEditor : public Component
  27965. {
  27966. protected:
  27967. /** Creates an editor for the specified processor.
  27968. */
  27969. AudioProcessorEditor (AudioProcessor* const owner);
  27970. public:
  27971. /** Destructor. */
  27972. ~AudioProcessorEditor();
  27973. /** Returns a pointer to the processor that this editor represents. */
  27974. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  27975. private:
  27976. AudioProcessor* const owner;
  27977. AudioProcessorEditor (const AudioProcessorEditor&);
  27978. AudioProcessorEditor& operator= (const AudioProcessorEditor&);
  27979. };
  27980. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  27981. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  27982. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  27983. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  27984. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  27985. class AudioProcessor;
  27986. /**
  27987. Base class for listeners that want to know about changes to an AudioProcessor.
  27988. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  27989. @see AudioProcessor
  27990. */
  27991. class JUCE_API AudioProcessorListener
  27992. {
  27993. public:
  27994. /** Destructor. */
  27995. virtual ~AudioProcessorListener() {}
  27996. /** Receives a callback when a parameter is changed.
  27997. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  27998. many audio processors will change their parameter during their audio callback.
  27999. This means that not only has your handler code got to be completely thread-safe,
  28000. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  28001. this event on your message thread, use this callback to trigger an AsyncUpdater
  28002. or ChangeBroadcaster which you can respond to on the message thread.
  28003. */
  28004. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  28005. int parameterIndex,
  28006. float newValue) = 0;
  28007. /** Called to indicate that something else in the plugin has changed, like its
  28008. program, number of parameters, etc.
  28009. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28010. call it during their audio callback. This means that not only has your handler code
  28011. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28012. blocking. If you need to handle this event on your message thread, use this callback
  28013. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28014. message thread.
  28015. */
  28016. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  28017. /** Indicates that a parameter change gesture has started.
  28018. E.g. if the user is dragging a slider, this would be called when they first
  28019. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  28020. called when they release it.
  28021. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28022. call it during their audio callback. This means that not only has your handler code
  28023. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28024. blocking. If you need to handle this event on your message thread, use this callback
  28025. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28026. message thread.
  28027. @see audioProcessorParameterChangeGestureEnd
  28028. */
  28029. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  28030. int parameterIndex);
  28031. /** Indicates that a parameter change gesture has finished.
  28032. E.g. if the user is dragging a slider, this would be called when they release
  28033. the mouse button.
  28034. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28035. call it during their audio callback. This means that not only has your handler code
  28036. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28037. blocking. If you need to handle this event on your message thread, use this callback
  28038. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28039. message thread.
  28040. @see audioPluginParameterChangeGestureStart
  28041. */
  28042. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  28043. int parameterIndex);
  28044. };
  28045. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28046. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  28047. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  28048. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28049. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28050. /**
  28051. A subclass of AudioPlayHead can supply information about the position and
  28052. status of a moving play head during audio playback.
  28053. One of these can be supplied to an AudioProcessor object so that it can find
  28054. out about the position of the audio that it is rendering.
  28055. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  28056. */
  28057. class JUCE_API AudioPlayHead
  28058. {
  28059. protected:
  28060. AudioPlayHead() {}
  28061. public:
  28062. virtual ~AudioPlayHead() {}
  28063. /** Frame rate types. */
  28064. enum FrameRateType
  28065. {
  28066. fps24 = 0,
  28067. fps25 = 1,
  28068. fps2997 = 2,
  28069. fps30 = 3,
  28070. fps2997drop = 4,
  28071. fps30drop = 5,
  28072. fpsUnknown = 99
  28073. };
  28074. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  28075. */
  28076. struct CurrentPositionInfo
  28077. {
  28078. /** The tempo in BPM */
  28079. double bpm;
  28080. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  28081. int timeSigNumerator;
  28082. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  28083. int timeSigDenominator;
  28084. /** The current play position, in seconds from the start of the edit. */
  28085. double timeInSeconds;
  28086. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  28087. double editOriginTime;
  28088. /** The current play position in pulses-per-quarter-note.
  28089. This is the number of quarter notes since the edit start.
  28090. */
  28091. double ppqPosition;
  28092. /** The position of the start of the last bar, in pulses-per-quarter-note.
  28093. This is the number of quarter notes from the start of the edit to the
  28094. start of the current bar.
  28095. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  28096. it's not available, the value will be 0.
  28097. */
  28098. double ppqPositionOfLastBarStart;
  28099. /** The video frame rate, if applicable. */
  28100. FrameRateType frameRate;
  28101. /** True if the transport is currently playing. */
  28102. bool isPlaying;
  28103. /** True if the transport is currently recording.
  28104. (When isRecording is true, then isPlaying will also be true).
  28105. */
  28106. bool isRecording;
  28107. bool operator== (const CurrentPositionInfo& other) const throw();
  28108. bool operator!= (const CurrentPositionInfo& other) const throw();
  28109. void resetToDefault();
  28110. };
  28111. /** Fills-in the given structure with details about the transport's
  28112. position at the start of the current processing block.
  28113. */
  28114. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  28115. };
  28116. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28117. /*** End of inlined file: juce_AudioPlayHead.h ***/
  28118. /**
  28119. Base class for audio processing filters or plugins.
  28120. This is intended to act as a base class of audio filter that is general enough to
  28121. be wrapped as a VST, AU, RTAS, etc, or used internally.
  28122. It is also used by the plugin hosting code as the wrapper around an instance
  28123. of a loaded plugin.
  28124. Derive your filter class from this base class, and if you're building a plugin,
  28125. you should implement a global function called createPluginFilter() which creates
  28126. and returns a new instance of your subclass.
  28127. */
  28128. class JUCE_API AudioProcessor
  28129. {
  28130. protected:
  28131. /** Constructor.
  28132. You can also do your initialisation tasks in the initialiseFilterInfo()
  28133. call, which will be made after this object has been created.
  28134. */
  28135. AudioProcessor();
  28136. public:
  28137. /** Destructor. */
  28138. virtual ~AudioProcessor();
  28139. /** Returns the name of this processor.
  28140. */
  28141. virtual const String getName() const = 0;
  28142. /** Called before playback starts, to let the filter prepare itself.
  28143. The sample rate is the target sample rate, and will remain constant until
  28144. playback stops.
  28145. The estimatedSamplesPerBlock value is a HINT about the typical number of
  28146. samples that will be processed for each callback, but isn't any kind
  28147. of guarantee. The actual block sizes that the host uses may be different
  28148. each time the callback happens, and may be more or less than this value.
  28149. */
  28150. virtual void prepareToPlay (double sampleRate,
  28151. int estimatedSamplesPerBlock) = 0;
  28152. /** Called after playback has stopped, to let the filter free up any resources it
  28153. no longer needs.
  28154. */
  28155. virtual void releaseResources() = 0;
  28156. /** Renders the next block.
  28157. When this method is called, the buffer contains a number of channels which is
  28158. at least as great as the maximum number of input and output channels that
  28159. this filter is using. It will be filled with the filter's input data and
  28160. should be replaced with the filter's output.
  28161. So for example if your filter has 2 input channels and 4 output channels, then
  28162. the buffer will contain 4 channels, the first two being filled with the
  28163. input data. Your filter should read these, do its processing, and replace
  28164. the contents of all 4 channels with its output.
  28165. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  28166. all filled with data, and your filter should overwrite the first 2 of these
  28167. with its output. But be VERY careful not to write anything to the last 3
  28168. channels, as these might be mapped to memory that the host assumes is read-only!
  28169. Note that if you have more outputs than inputs, then only those channels that
  28170. correspond to an input channel are guaranteed to contain sensible data - e.g.
  28171. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  28172. but the last two channels may contain garbage, so you should be careful not to
  28173. let this pass through without being overwritten or cleared.
  28174. Also note that the buffer may have more channels than are strictly necessary,
  28175. but your should only read/write from the ones that your filter is supposed to
  28176. be using.
  28177. The number of samples in these buffers is NOT guaranteed to be the same for every
  28178. callback, and may be more or less than the estimated value given to prepareToPlay().
  28179. Your code must be able to cope with variable-sized blocks, or you're going to get
  28180. clicks and crashes!
  28181. If the filter is receiving a midi input, then the midiMessages array will be filled
  28182. with the midi messages for this block. Each message's timestamp will indicate the
  28183. message's time, as a number of samples from the start of the block.
  28184. Any messages left in the midi buffer when this method has finished are assumed to
  28185. be the filter's midi output. This means that your filter should be careful to
  28186. clear any incoming messages from the array if it doesn't want them to be passed-on.
  28187. Be very careful about what you do in this callback - it's going to be called by
  28188. the audio thread, so any kind of interaction with the UI is absolutely
  28189. out of the question. If you change a parameter in here and need to tell your UI to
  28190. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  28191. the UI components register as listeners, and then call sendChangeMessage() inside the
  28192. processBlock() method to send out an asynchronous message. You could also use
  28193. the AsyncUpdater class in a similar way.
  28194. */
  28195. virtual void processBlock (AudioSampleBuffer& buffer,
  28196. MidiBuffer& midiMessages) = 0;
  28197. /** Returns the current AudioPlayHead object that should be used to find
  28198. out the state and position of the playhead.
  28199. You can call this from your processBlock() method, and use the AudioPlayHead
  28200. object to get the details about the time of the start of the block currently
  28201. being processed.
  28202. If the host hasn't supplied a playhead object, this will return 0.
  28203. */
  28204. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  28205. /** Returns the current sample rate.
  28206. This can be called from your processBlock() method - it's not guaranteed
  28207. to be valid at any other time, and may return 0 if it's unknown.
  28208. */
  28209. double getSampleRate() const throw() { return sampleRate; }
  28210. /** Returns the current typical block size that is being used.
  28211. This can be called from your processBlock() method - it's not guaranteed
  28212. to be valid at any other time.
  28213. Remember it's not the ONLY block size that may be used when calling
  28214. processBlock, it's just the normal one. The actual block sizes used may be
  28215. larger or smaller than this, and will vary between successive calls.
  28216. */
  28217. int getBlockSize() const throw() { return blockSize; }
  28218. /** Returns the number of input channels that the host will be sending the filter.
  28219. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28220. number of channels that your filter would prefer to have, and this method lets
  28221. you know how many the host is actually using.
  28222. Note that this method is only valid during or after the prepareToPlay()
  28223. method call. Until that point, the number of channels will be unknown.
  28224. */
  28225. int getNumInputChannels() const throw() { return numInputChannels; }
  28226. /** Returns the number of output channels that the host will be sending the filter.
  28227. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28228. number of channels that your filter would prefer to have, and this method lets
  28229. you know how many the host is actually using.
  28230. Note that this method is only valid during or after the prepareToPlay()
  28231. method call. Until that point, the number of channels will be unknown.
  28232. */
  28233. int getNumOutputChannels() const throw() { return numOutputChannels; }
  28234. /** Returns the name of one of the input channels, as returned by the host.
  28235. The host might not supply very useful names for channels, and this might be
  28236. something like "1", "2", "left", "right", etc.
  28237. */
  28238. virtual const String getInputChannelName (const int channelIndex) const = 0;
  28239. /** Returns the name of one of the output channels, as returned by the host.
  28240. The host might not supply very useful names for channels, and this might be
  28241. something like "1", "2", "left", "right", etc.
  28242. */
  28243. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  28244. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28245. virtual bool isInputChannelStereoPair (int index) const = 0;
  28246. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28247. virtual bool isOutputChannelStereoPair (int index) const = 0;
  28248. /** This returns the number of samples delay that the filter imposes on the audio
  28249. passing through it.
  28250. The host will call this to find the latency - the filter itself should set this value
  28251. by calling setLatencySamples() as soon as it can during its initialisation.
  28252. */
  28253. int getLatencySamples() const throw() { return latencySamples; }
  28254. /** The filter should call this to set the number of samples delay that it introduces.
  28255. The filter should call this as soon as it can during initialisation, and can call it
  28256. later if the value changes.
  28257. */
  28258. void setLatencySamples (const int newLatency);
  28259. /** Returns true if the processor wants midi messages. */
  28260. virtual bool acceptsMidi() const = 0;
  28261. /** Returns true if the processor produces midi messages. */
  28262. virtual bool producesMidi() const = 0;
  28263. /** This returns a critical section that will automatically be locked while the host
  28264. is calling the processBlock() method.
  28265. Use it from your UI or other threads to lock access to variables that are used
  28266. by the process callback, but obviously be careful not to keep it locked for
  28267. too long, because that could cause stuttering playback. If you need to do something
  28268. that'll take a long time and need the processing to stop while it happens, use the
  28269. suspendProcessing() method instead.
  28270. @see suspendProcessing
  28271. */
  28272. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  28273. /** Enables and disables the processing callback.
  28274. If you need to do something time-consuming on a thread and would like to make sure
  28275. the audio processing callback doesn't happen until you've finished, use this
  28276. to disable the callback and re-enable it again afterwards.
  28277. E.g.
  28278. @code
  28279. void loadNewPatch()
  28280. {
  28281. suspendProcessing (true);
  28282. ..do something that takes ages..
  28283. suspendProcessing (false);
  28284. }
  28285. @endcode
  28286. If the host tries to make an audio callback while processing is suspended, the
  28287. filter will return an empty buffer, but won't block the audio thread like it would
  28288. do if you use the getCallbackLock() critical section to synchronise access.
  28289. If you're going to use this, your processBlock() method must call isSuspended() and
  28290. check whether it's suspended or not. If it is, then it should skip doing any real
  28291. processing, either emitting silence or passing the input through unchanged.
  28292. @see getCallbackLock
  28293. */
  28294. void suspendProcessing (const bool shouldBeSuspended);
  28295. /** Returns true if processing is currently suspended.
  28296. @see suspendProcessing
  28297. */
  28298. bool isSuspended() const throw() { return suspended; }
  28299. /** A plugin can override this to be told when it should reset any playing voices.
  28300. The default implementation does nothing, but a host may call this to tell the
  28301. plugin that it should stop any tails or sounds that have been left running.
  28302. */
  28303. virtual void reset();
  28304. /** Returns true if the processor is being run in an offline mode for rendering.
  28305. If the processor is being run live on realtime signals, this returns false.
  28306. If the mode is unknown, this will assume it's realtime and return false.
  28307. This value may be unreliable until the prepareToPlay() method has been called,
  28308. and could change each time prepareToPlay() is called.
  28309. @see setNonRealtime()
  28310. */
  28311. bool isNonRealtime() const throw() { return nonRealtime; }
  28312. /** Called by the host to tell this processor whether it's being used in a non-realime
  28313. capacity for offline rendering or bouncing.
  28314. Whatever value is passed-in will be
  28315. */
  28316. void setNonRealtime (const bool isNonRealtime) throw();
  28317. /** Creates the filter's UI.
  28318. This can return 0 if you want a UI-less filter, in which case the host may create
  28319. a generic UI that lets the user twiddle the parameters directly.
  28320. If you do want to pass back a component, the component should be created and set to
  28321. the correct size before returning it.
  28322. Remember not to do anything silly like allowing your filter to keep a pointer to
  28323. the component that gets created - it could be deleted later without any warning, which
  28324. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  28325. The correct way to handle the connection between an editor component and its
  28326. filter is to use something like a ChangeBroadcaster so that the editor can
  28327. register itself as a listener, and be told when a change occurs. This lets them
  28328. safely unregister themselves when they are deleted.
  28329. Here are a few things to bear in mind when writing an editor:
  28330. - Initially there won't be an editor, until the user opens one, or they might
  28331. not open one at all. Your filter mustn't rely on it being there.
  28332. - An editor object may be deleted and a replacement one created again at any time.
  28333. - It's safe to assume that an editor will be deleted before its filter.
  28334. */
  28335. virtual AudioProcessorEditor* createEditor() = 0;
  28336. /** Returns the active editor, if there is one.
  28337. Bear in mind this can return 0, even if an editor has previously been
  28338. opened.
  28339. */
  28340. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  28341. /** Returns the active editor, or if there isn't one, it will create one.
  28342. This may call createEditor() internally to create the component.
  28343. */
  28344. AudioProcessorEditor* createEditorIfNeeded();
  28345. /** This must return the correct value immediately after the object has been
  28346. created, and mustn't change the number of parameters later.
  28347. */
  28348. virtual int getNumParameters() = 0;
  28349. /** Returns the name of a particular parameter. */
  28350. virtual const String getParameterName (int parameterIndex) = 0;
  28351. /** Called by the host to find out the value of one of the filter's parameters.
  28352. The host will expect the value returned to be between 0 and 1.0.
  28353. This could be called quite frequently, so try to make your code efficient.
  28354. It's also likely to be called by non-UI threads, so the code in here should
  28355. be thread-aware.
  28356. */
  28357. virtual float getParameter (int parameterIndex) = 0;
  28358. /** Returns the value of a parameter as a text string. */
  28359. virtual const String getParameterText (int parameterIndex) = 0;
  28360. /** The host will call this method to change the value of one of the filter's parameters.
  28361. The host may call this at any time, including during the audio processing
  28362. callback, so the filter has to process this very fast and avoid blocking.
  28363. If you want to set the value of a parameter internally, e.g. from your
  28364. editor component, then don't call this directly - instead, use the
  28365. setParameterNotifyingHost() method, which will also send a message to
  28366. the host telling it about the change. If the message isn't sent, the host
  28367. won't be able to automate your parameters properly.
  28368. The value passed will be between 0 and 1.0.
  28369. */
  28370. virtual void setParameter (int parameterIndex,
  28371. float newValue) = 0;
  28372. /** Your filter can call this when it needs to change one of its parameters.
  28373. This could happen when the editor or some other internal operation changes
  28374. a parameter. This method will call the setParameter() method to change the
  28375. value, and will then send a message to the host telling it about the change.
  28376. Note that to make sure the host correctly handles automation, you should call
  28377. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  28378. tell the host when the user has started and stopped changing the parameter.
  28379. */
  28380. void setParameterNotifyingHost (int parameterIndex,
  28381. float newValue);
  28382. /** Returns true if the host can automate this parameter.
  28383. By default, this returns true for all parameters.
  28384. */
  28385. virtual bool isParameterAutomatable (int parameterIndex) const;
  28386. /** Should return true if this parameter is a "meta" parameter.
  28387. A meta-parameter is a parameter that changes other params. It is used
  28388. by some hosts (e.g. AudioUnit hosts).
  28389. By default this returns false.
  28390. */
  28391. virtual bool isMetaParameter (int parameterIndex) const;
  28392. /** Sends a signal to the host to tell it that the user is about to start changing this
  28393. parameter.
  28394. This allows the host to know when a parameter is actively being held by the user, and
  28395. it may use this information to help it record automation.
  28396. If you call this, it must be matched by a later call to endParameterChangeGesture().
  28397. */
  28398. void beginParameterChangeGesture (int parameterIndex);
  28399. /** Tells the host that the user has finished changing this parameter.
  28400. This allows the host to know when a parameter is actively being held by the user, and
  28401. it may use this information to help it record automation.
  28402. A call to this method must follow a call to beginParameterChangeGesture().
  28403. */
  28404. void endParameterChangeGesture (int parameterIndex);
  28405. /** The filter can call this when something (apart from a parameter value) has changed.
  28406. It sends a hint to the host that something like the program, number of parameters,
  28407. etc, has changed, and that it should update itself.
  28408. */
  28409. void updateHostDisplay();
  28410. /** Returns the number of preset programs the filter supports.
  28411. The value returned must be valid as soon as this object is created, and
  28412. must not change over its lifetime.
  28413. This value shouldn't be less than 1.
  28414. */
  28415. virtual int getNumPrograms() = 0;
  28416. /** Returns the number of the currently active program.
  28417. */
  28418. virtual int getCurrentProgram() = 0;
  28419. /** Called by the host to change the current program.
  28420. */
  28421. virtual void setCurrentProgram (int index) = 0;
  28422. /** Must return the name of a given program. */
  28423. virtual const String getProgramName (int index) = 0;
  28424. /** Called by the host to rename a program.
  28425. */
  28426. virtual void changeProgramName (int index, const String& newName) = 0;
  28427. /** The host will call this method when it wants to save the filter's internal state.
  28428. This must copy any info about the filter's state into the block of memory provided,
  28429. so that the host can store this and later restore it using setStateInformation().
  28430. Note that there's also a getCurrentProgramStateInformation() method, which only
  28431. stores the current program, not the state of the entire filter.
  28432. See also the helper function copyXmlToBinary() for storing settings as XML.
  28433. @see getCurrentProgramStateInformation
  28434. */
  28435. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  28436. /** The host will call this method if it wants to save the state of just the filter's
  28437. current program.
  28438. Unlike getStateInformation, this should only return the current program's state.
  28439. Not all hosts support this, and if you don't implement it, the base class
  28440. method just calls getStateInformation() instead. If you do implement it, be
  28441. sure to also implement getCurrentProgramStateInformation.
  28442. @see getStateInformation, setCurrentProgramStateInformation
  28443. */
  28444. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  28445. /** This must restore the filter's state from a block of data previously created
  28446. using getStateInformation().
  28447. Note that there's also a setCurrentProgramStateInformation() method, which tries
  28448. to restore just the current program, not the state of the entire filter.
  28449. See also the helper function getXmlFromBinary() for loading settings as XML.
  28450. @see setCurrentProgramStateInformation
  28451. */
  28452. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  28453. /** The host will call this method if it wants to restore the state of just the filter's
  28454. current program.
  28455. Not all hosts support this, and if you don't implement it, the base class
  28456. method just calls setStateInformation() instead. If you do implement it, be
  28457. sure to also implement getCurrentProgramStateInformation.
  28458. @see setStateInformation, getCurrentProgramStateInformation
  28459. */
  28460. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  28461. /** Adds a listener that will be called when an aspect of this processor changes. */
  28462. void addListener (AudioProcessorListener* const newListener) throw();
  28463. /** Removes a previously added listener. */
  28464. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  28465. /** Not for public use - this is called before deleting an editor component. */
  28466. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  28467. /** Not for public use - this is called to initialise the processor. */
  28468. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  28469. /** Not for public use - this is called to initialise the processor before playing. */
  28470. void setPlayConfigDetails (const int numIns, const int numOuts,
  28471. const double sampleRate,
  28472. const int blockSize) throw();
  28473. juce_UseDebuggingNewOperator
  28474. protected:
  28475. /** Helper function that just converts an xml element into a binary blob.
  28476. Use this in your filter's getStateInformation() method if you want to
  28477. store its state as xml.
  28478. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  28479. from a binary blob.
  28480. */
  28481. static void copyXmlToBinary (const XmlElement& xml,
  28482. JUCE_NAMESPACE::MemoryBlock& destData);
  28483. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  28484. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  28485. an XmlElement object that the caller must delete when no longer needed.
  28486. */
  28487. static XmlElement* getXmlFromBinary (const void* data,
  28488. const int sizeInBytes);
  28489. /** @internal */
  28490. AudioPlayHead* playHead;
  28491. /** @internal */
  28492. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  28493. private:
  28494. Array <AudioProcessorListener*> listeners;
  28495. AudioProcessorEditor* activeEditor;
  28496. double sampleRate;
  28497. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  28498. bool suspended, nonRealtime;
  28499. CriticalSection callbackLock, listenerLock;
  28500. #if JUCE_DEBUG
  28501. BigInteger changingParams;
  28502. #endif
  28503. AudioProcessor (const AudioProcessor&);
  28504. AudioProcessor& operator= (const AudioProcessor&);
  28505. };
  28506. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28507. /*** End of inlined file: juce_AudioProcessor.h ***/
  28508. /*** Start of inlined file: juce_PluginDescription.h ***/
  28509. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28510. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28511. /**
  28512. A small class to represent some facts about a particular type of plugin.
  28513. This class is for storing and managing the details about a plugin without
  28514. actually having to load an instance of it.
  28515. A KnownPluginList contains a list of PluginDescription objects.
  28516. @see KnownPluginList
  28517. */
  28518. class JUCE_API PluginDescription
  28519. {
  28520. public:
  28521. PluginDescription() throw();
  28522. PluginDescription (const PluginDescription& other) throw();
  28523. PluginDescription& operator= (const PluginDescription& other) throw();
  28524. ~PluginDescription() throw();
  28525. /** The name of the plugin. */
  28526. String name;
  28527. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  28528. */
  28529. String pluginFormatName;
  28530. /** A category, such as "Dynamics", "Reverbs", etc.
  28531. */
  28532. String category;
  28533. /** The manufacturer. */
  28534. String manufacturerName;
  28535. /** The version. This string doesn't have any particular format. */
  28536. String version;
  28537. /** Either the file containing the plugin module, or some other unique way
  28538. of identifying it.
  28539. E.g. for an AU, this would be an ID string that the component manager
  28540. could use to retrieve the plugin. For a VST, it's the file path.
  28541. */
  28542. String fileOrIdentifier;
  28543. /** The last time the plugin file was changed.
  28544. This is handy when scanning for new or changed plugins.
  28545. */
  28546. Time lastFileModTime;
  28547. /** A unique ID for the plugin.
  28548. Note that this might not be unique between formats, e.g. a VST and some
  28549. other format might actually have the same id.
  28550. @see createIdentifierString
  28551. */
  28552. int uid;
  28553. /** True if the plugin identifies itself as a synthesiser. */
  28554. bool isInstrument;
  28555. /** The number of inputs. */
  28556. int numInputChannels;
  28557. /** The number of outputs. */
  28558. int numOutputChannels;
  28559. /** Returns true if the two descriptions refer the the same plugin.
  28560. This isn't quite as simple as them just having the same file (because of
  28561. shell plugins).
  28562. */
  28563. bool isDuplicateOf (const PluginDescription& other) const;
  28564. /** Returns a string that can be saved and used to uniquely identify the
  28565. plugin again.
  28566. This contains less info than the XML encoding, and is independent of the
  28567. plugin's file location, so can be used to store a plugin ID for use
  28568. across different machines.
  28569. */
  28570. const String createIdentifierString() const throw();
  28571. /** Creates an XML object containing these details.
  28572. @see loadFromXml
  28573. */
  28574. XmlElement* createXml() const;
  28575. /** Reloads the info in this structure from an XML record that was previously
  28576. saved with createXML().
  28577. Returns true if the XML was a valid plugin description.
  28578. */
  28579. bool loadFromXml (const XmlElement& xml);
  28580. juce_UseDebuggingNewOperator
  28581. };
  28582. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  28583. /*** End of inlined file: juce_PluginDescription.h ***/
  28584. /**
  28585. Base class for an active instance of a plugin.
  28586. This derives from the AudioProcessor class, and adds some extra functionality
  28587. that helps when wrapping dynamically loaded plugins.
  28588. @see AudioProcessor, AudioPluginFormat
  28589. */
  28590. class JUCE_API AudioPluginInstance : public AudioProcessor
  28591. {
  28592. public:
  28593. /** Destructor.
  28594. Make sure that you delete any UI components that belong to this plugin before
  28595. deleting the plugin.
  28596. */
  28597. virtual ~AudioPluginInstance();
  28598. /** Fills-in the appropriate parts of this plugin description object.
  28599. */
  28600. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  28601. juce_UseDebuggingNewOperator
  28602. protected:
  28603. AudioPluginInstance();
  28604. AudioPluginInstance (const AudioPluginInstance&);
  28605. AudioPluginInstance& operator= (const AudioPluginInstance&);
  28606. };
  28607. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28608. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  28609. class PluginDescription;
  28610. /**
  28611. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  28612. Use the static getNumFormats() and getFormat() calls to find the types
  28613. of format that are available.
  28614. */
  28615. class JUCE_API AudioPluginFormat
  28616. {
  28617. public:
  28618. /** Destructor. */
  28619. virtual ~AudioPluginFormat();
  28620. /** Returns the format name.
  28621. E.g. "VST", "AudioUnit", etc.
  28622. */
  28623. virtual const String getName() const = 0;
  28624. /** This tries to create descriptions for all the plugin types available in
  28625. a binary module file.
  28626. The file will be some kind of DLL or bundle.
  28627. Normally there will only be one type returned, but some plugins
  28628. (e.g. VST shells) can use a single DLL to create a set of different plugin
  28629. subtypes, so in that case, each subtype is returned as a separate object.
  28630. */
  28631. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28632. const String& fileOrIdentifier) = 0;
  28633. /** Tries to recreate a type from a previously generated PluginDescription.
  28634. @see PluginDescription::createInstance
  28635. */
  28636. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  28637. /** Should do a quick check to see if this file or directory might be a plugin of
  28638. this format.
  28639. This is for searching for potential files, so it shouldn't actually try to
  28640. load the plugin or do anything time-consuming.
  28641. */
  28642. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  28643. /** Returns a readable version of the name of the plugin that this identifier refers to.
  28644. */
  28645. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  28646. /** Checks whether this plugin could possibly be loaded.
  28647. It doesn't actually need to load it, just to check whether the file or component
  28648. still exists.
  28649. */
  28650. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  28651. /** Searches a suggested set of directories for any plugins in this format.
  28652. The path might be ignored, e.g. by AUs, which are found by the OS rather
  28653. than manually.
  28654. */
  28655. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  28656. bool recursive) = 0;
  28657. /** Returns the typical places to look for this kind of plugin.
  28658. Note that if this returns no paths, it means that the format can't be scanned-for
  28659. (i.e. it's an internal format that doesn't live in files)
  28660. */
  28661. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  28662. juce_UseDebuggingNewOperator
  28663. protected:
  28664. AudioPluginFormat() throw();
  28665. AudioPluginFormat (const AudioPluginFormat&);
  28666. AudioPluginFormat& operator= (const AudioPluginFormat&);
  28667. };
  28668. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28669. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  28670. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  28671. /**
  28672. Implements a plugin format manager for AudioUnits.
  28673. */
  28674. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  28675. {
  28676. public:
  28677. AudioUnitPluginFormat();
  28678. ~AudioUnitPluginFormat();
  28679. const String getName() const { return "AudioUnit"; }
  28680. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  28681. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  28682. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  28683. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  28684. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  28685. bool doesPluginStillExist (const PluginDescription& desc);
  28686. const FileSearchPath getDefaultLocationsToSearch();
  28687. juce_UseDebuggingNewOperator
  28688. private:
  28689. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  28690. AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  28691. };
  28692. #endif
  28693. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28694. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  28695. #endif
  28696. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  28697. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  28698. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  28699. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  28700. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  28701. // Sorry, this file is just a placeholder at the moment!...
  28702. /**
  28703. Implements a plugin format manager for DirectX plugins.
  28704. */
  28705. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  28706. {
  28707. public:
  28708. DirectXPluginFormat();
  28709. ~DirectXPluginFormat();
  28710. const String getName() const { return "DirectX"; }
  28711. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  28712. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  28713. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  28714. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  28715. const FileSearchPath getDefaultLocationsToSearch();
  28716. juce_UseDebuggingNewOperator
  28717. private:
  28718. DirectXPluginFormat (const DirectXPluginFormat&);
  28719. DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  28720. };
  28721. #endif
  28722. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  28723. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  28724. #endif
  28725. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  28726. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  28727. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  28728. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  28729. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  28730. // Sorry, this file is just a placeholder at the moment!...
  28731. /**
  28732. Implements a plugin format manager for DirectX plugins.
  28733. */
  28734. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  28735. {
  28736. public:
  28737. LADSPAPluginFormat();
  28738. ~LADSPAPluginFormat();
  28739. const String getName() const { return "LADSPA"; }
  28740. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  28741. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  28742. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  28743. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  28744. const FileSearchPath getDefaultLocationsToSearch();
  28745. juce_UseDebuggingNewOperator
  28746. private:
  28747. LADSPAPluginFormat (const LADSPAPluginFormat&);
  28748. LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  28749. };
  28750. #endif
  28751. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  28752. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  28753. #endif
  28754. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  28755. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  28756. #ifdef __aeffect__
  28757. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  28758. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  28759. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  28760. events to the list.
  28761. This is used by both the VST hosting code and the plugin wrapper.
  28762. */
  28763. class VSTMidiEventList
  28764. {
  28765. public:
  28766. VSTMidiEventList()
  28767. : numEventsUsed (0), numEventsAllocated (0)
  28768. {
  28769. }
  28770. ~VSTMidiEventList()
  28771. {
  28772. freeEvents();
  28773. }
  28774. void clear()
  28775. {
  28776. numEventsUsed = 0;
  28777. if (events != 0)
  28778. events->numEvents = 0;
  28779. }
  28780. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  28781. {
  28782. ensureSize (numEventsUsed + 1);
  28783. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  28784. events->numEvents = ++numEventsUsed;
  28785. if (numBytes <= 4)
  28786. {
  28787. if (e->type == kVstSysExType)
  28788. {
  28789. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  28790. e->type = kVstMidiType;
  28791. e->byteSize = sizeof (VstMidiEvent);
  28792. e->noteLength = 0;
  28793. e->noteOffset = 0;
  28794. e->detune = 0;
  28795. e->noteOffVelocity = 0;
  28796. }
  28797. e->deltaFrames = frameOffset;
  28798. memcpy (e->midiData, midiData, numBytes);
  28799. }
  28800. else
  28801. {
  28802. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  28803. if (se->type == kVstSysExType)
  28804. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  28805. else
  28806. se->sysexDump = (char*) juce_malloc (numBytes);
  28807. memcpy (se->sysexDump, midiData, numBytes);
  28808. se->type = kVstSysExType;
  28809. se->byteSize = sizeof (VstMidiSysexEvent);
  28810. se->deltaFrames = frameOffset;
  28811. se->flags = 0;
  28812. se->dumpBytes = numBytes;
  28813. se->resvd1 = 0;
  28814. se->resvd2 = 0;
  28815. }
  28816. }
  28817. // Handy method to pull the events out of an event buffer supplied by the host
  28818. // or plugin.
  28819. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  28820. {
  28821. for (int i = 0; i < events->numEvents; ++i)
  28822. {
  28823. const VstEvent* const e = events->events[i];
  28824. if (e != 0)
  28825. {
  28826. if (e->type == kVstMidiType)
  28827. {
  28828. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  28829. 4, e->deltaFrames);
  28830. }
  28831. else if (e->type == kVstSysExType)
  28832. {
  28833. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  28834. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  28835. e->deltaFrames);
  28836. }
  28837. }
  28838. }
  28839. }
  28840. void ensureSize (int numEventsNeeded)
  28841. {
  28842. if (numEventsNeeded > numEventsAllocated)
  28843. {
  28844. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  28845. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  28846. if (events == 0)
  28847. events.calloc (size, 1);
  28848. else
  28849. events.realloc (size, 1);
  28850. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  28851. {
  28852. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  28853. (int) sizeof (VstMidiSysexEvent)));
  28854. e->type = kVstMidiType;
  28855. e->byteSize = sizeof (VstMidiEvent);
  28856. events->events[i] = (VstEvent*) e;
  28857. }
  28858. numEventsAllocated = numEventsNeeded;
  28859. }
  28860. }
  28861. void freeEvents()
  28862. {
  28863. if (events != 0)
  28864. {
  28865. for (int i = numEventsAllocated; --i >= 0;)
  28866. {
  28867. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  28868. if (e->type == kVstSysExType)
  28869. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  28870. juce_free (e);
  28871. }
  28872. events.free();
  28873. numEventsUsed = 0;
  28874. numEventsAllocated = 0;
  28875. }
  28876. }
  28877. HeapBlock <VstEvents> events;
  28878. private:
  28879. int numEventsUsed, numEventsAllocated;
  28880. };
  28881. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  28882. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  28883. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  28884. #endif
  28885. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  28886. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  28887. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  28888. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  28889. #if JUCE_PLUGINHOST_VST
  28890. /**
  28891. Implements a plugin format manager for VSTs.
  28892. */
  28893. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  28894. {
  28895. public:
  28896. VSTPluginFormat();
  28897. ~VSTPluginFormat();
  28898. const String getName() const { return "VST"; }
  28899. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  28900. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  28901. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  28902. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  28903. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  28904. bool doesPluginStillExist (const PluginDescription& desc);
  28905. const FileSearchPath getDefaultLocationsToSearch();
  28906. juce_UseDebuggingNewOperator
  28907. private:
  28908. VSTPluginFormat (const VSTPluginFormat&);
  28909. VSTPluginFormat& operator= (const VSTPluginFormat&);
  28910. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  28911. };
  28912. #endif
  28913. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  28914. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  28915. #endif
  28916. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28917. #endif
  28918. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  28919. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  28920. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  28921. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  28922. /**
  28923. This maintains a list of known AudioPluginFormats.
  28924. @see AudioPluginFormat
  28925. */
  28926. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  28927. {
  28928. public:
  28929. AudioPluginFormatManager() throw();
  28930. /** Destructor. */
  28931. ~AudioPluginFormatManager() throw();
  28932. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  28933. /** Adds any formats that it knows about, e.g. VST.
  28934. */
  28935. void addDefaultFormats();
  28936. /** Returns the number of types of format that are available.
  28937. Use getFormat() to get one of them.
  28938. */
  28939. int getNumFormats() throw();
  28940. /** Returns one of the available formats.
  28941. @see getNumFormats
  28942. */
  28943. AudioPluginFormat* getFormat (const int index) throw();
  28944. /** Adds a format to the list.
  28945. The object passed in will be owned and deleted by the manager.
  28946. */
  28947. void addFormat (AudioPluginFormat* const format) throw();
  28948. /** Tries to load the type for this description, by trying all the formats
  28949. that this manager knows about.
  28950. The caller is responsible for deleting the object that is returned.
  28951. If it can't load the plugin, it returns 0 and leaves a message in the
  28952. errorMessage string.
  28953. */
  28954. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  28955. String& errorMessage) const;
  28956. /** Checks that the file or component for this plugin actually still exists.
  28957. (This won't try to load the plugin)
  28958. */
  28959. bool doesPluginStillExist (const PluginDescription& description) const;
  28960. juce_UseDebuggingNewOperator
  28961. private:
  28962. OwnedArray <AudioPluginFormat> formats;
  28963. AudioPluginFormatManager (const AudioPluginFormatManager&);
  28964. AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  28965. };
  28966. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  28967. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  28968. #endif
  28969. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28970. #endif
  28971. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  28972. /*** Start of inlined file: juce_KnownPluginList.h ***/
  28973. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  28974. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  28975. /**
  28976. Manages a list of plugin types.
  28977. This can be easily edited, saved and loaded, and used to create instances of
  28978. the plugin types in it.
  28979. @see PluginListComponent
  28980. */
  28981. class JUCE_API KnownPluginList : public ChangeBroadcaster
  28982. {
  28983. public:
  28984. /** Creates an empty list.
  28985. */
  28986. KnownPluginList();
  28987. /** Destructor. */
  28988. ~KnownPluginList();
  28989. /** Clears the list. */
  28990. void clear();
  28991. /** Returns the number of types currently in the list.
  28992. @see getType
  28993. */
  28994. int getNumTypes() const throw() { return types.size(); }
  28995. /** Returns one of the types.
  28996. @see getNumTypes
  28997. */
  28998. PluginDescription* getType (int index) const throw() { return types [index]; }
  28999. /** Looks for a type in the list which comes from this file.
  29000. */
  29001. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  29002. /** Looks for a type in the list which matches a plugin type ID.
  29003. The identifierString parameter must have been created by
  29004. PluginDescription::createIdentifierString().
  29005. */
  29006. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  29007. /** Adds a type manually from its description. */
  29008. bool addType (const PluginDescription& type);
  29009. /** Removes a type. */
  29010. void removeType (int index) throw();
  29011. /** Looks for all types that can be loaded from a given file, and adds them
  29012. to the list.
  29013. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29014. re-tested if it's not already in the list, or if the file's modification
  29015. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29016. false, the file will always be reloaded and tested.
  29017. Returns true if any new types were added, and all the types found in this
  29018. file (even if it was already known and hasn't been re-scanned) get returned
  29019. in the array.
  29020. */
  29021. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  29022. bool dontRescanIfAlreadyInList,
  29023. OwnedArray <PluginDescription>& typesFound,
  29024. AudioPluginFormat& formatToUse);
  29025. /** Returns true if the specified file is already known about and if it
  29026. hasn't been modified since our entry was created.
  29027. */
  29028. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  29029. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  29030. If any types are found in the files, their descriptions are returned in the array.
  29031. */
  29032. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  29033. OwnedArray <PluginDescription>& typesFound);
  29034. /** Sort methods used to change the order of the plugins in the list.
  29035. */
  29036. enum SortMethod
  29037. {
  29038. defaultOrder = 0,
  29039. sortAlphabetically,
  29040. sortByCategory,
  29041. sortByManufacturer,
  29042. sortByFileSystemLocation
  29043. };
  29044. /** Adds all the plugin types to a popup menu so that the user can select one.
  29045. Depending on the sort method, it may add sub-menus for categories,
  29046. manufacturers, etc.
  29047. Use getIndexChosenByMenu() to find out the type that was chosen.
  29048. */
  29049. void addToMenu (PopupMenu& menu,
  29050. const SortMethod sortMethod) const;
  29051. /** Converts a menu item index that has been chosen into its index in this list.
  29052. Returns -1 if it's not an ID that was used.
  29053. @see addToMenu
  29054. */
  29055. int getIndexChosenByMenu (int menuResultCode) const;
  29056. /** Sorts the list. */
  29057. void sort (const SortMethod method);
  29058. /** Creates some XML that can be used to store the state of this list.
  29059. */
  29060. XmlElement* createXml() const;
  29061. /** Recreates the state of this list from its stored XML format.
  29062. */
  29063. void recreateFromXml (const XmlElement& xml);
  29064. juce_UseDebuggingNewOperator
  29065. private:
  29066. OwnedArray <PluginDescription> types;
  29067. KnownPluginList (const KnownPluginList&);
  29068. KnownPluginList& operator= (const KnownPluginList&);
  29069. };
  29070. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29071. /*** End of inlined file: juce_KnownPluginList.h ***/
  29072. #endif
  29073. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29074. #endif
  29075. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29076. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  29077. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29078. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29079. /**
  29080. Scans a directory for plugins, and adds them to a KnownPluginList.
  29081. To use one of these, create it and call scanNextFile() repeatedly, until
  29082. it returns false.
  29083. */
  29084. class JUCE_API PluginDirectoryScanner
  29085. {
  29086. public:
  29087. /**
  29088. Creates a scanner.
  29089. @param listToAddResultsTo this will get the new types added to it.
  29090. @param formatToLookFor this is the type of format that you want to look for
  29091. @param directoriesToSearch the path to search
  29092. @param searchRecursively true to search recursively
  29093. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  29094. be used as a file to store the names of any plugins
  29095. that crash during initialisation. If there are
  29096. any plugins listed in it, then these will always
  29097. be scanned after all other possible files have
  29098. been tried - in this way, even if there's a few
  29099. dodgy plugins in your path, then a couple of rescans
  29100. will still manage to find all the proper plugins.
  29101. It's probably best to choose a file in the user's
  29102. application data directory (alongside your app's
  29103. settings file) for this. The file format it uses
  29104. is just a list of filenames of the modules that
  29105. failed.
  29106. */
  29107. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  29108. AudioPluginFormat& formatToLookFor,
  29109. FileSearchPath directoriesToSearch,
  29110. bool searchRecursively,
  29111. const File& deadMansPedalFile);
  29112. /** Destructor. */
  29113. ~PluginDirectoryScanner();
  29114. /** Tries the next likely-looking file.
  29115. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29116. re-tested if it's not already in the list, or if the file's modification
  29117. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29118. false, the file will always be reloaded and tested.
  29119. Returns false when there are no more files to try.
  29120. */
  29121. bool scanNextFile (bool dontRescanIfAlreadyInList);
  29122. /** Returns the description of the plugin that will be scanned during the next
  29123. call to scanNextFile().
  29124. This is handy if you want to show the user which file is currently getting
  29125. scanned.
  29126. */
  29127. const String getNextPluginFileThatWillBeScanned() const throw();
  29128. /** Returns the estimated progress, between 0 and 1.
  29129. */
  29130. float getProgress() const { return progress; }
  29131. /** This returns a list of all the filenames of things that looked like being
  29132. a plugin file, but which failed to open for some reason.
  29133. */
  29134. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  29135. juce_UseDebuggingNewOperator
  29136. private:
  29137. KnownPluginList& list;
  29138. AudioPluginFormat& format;
  29139. StringArray filesOrIdentifiersToScan;
  29140. File deadMansPedalFile;
  29141. StringArray failedFiles;
  29142. int nextIndex;
  29143. float progress;
  29144. const StringArray getDeadMansPedalFile() throw();
  29145. void setDeadMansPedalFile (const StringArray& newContents) throw();
  29146. PluginDirectoryScanner (const PluginDirectoryScanner&);
  29147. PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  29148. };
  29149. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29150. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  29151. #endif
  29152. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29153. /*** Start of inlined file: juce_PluginListComponent.h ***/
  29154. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29155. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29156. /*** Start of inlined file: juce_ListBox.h ***/
  29157. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  29158. #define __JUCE_LISTBOX_JUCEHEADER__
  29159. class ListViewport;
  29160. /**
  29161. A subclass of this is used to drive a ListBox.
  29162. @see ListBox
  29163. */
  29164. class JUCE_API ListBoxModel
  29165. {
  29166. public:
  29167. /** Destructor. */
  29168. virtual ~ListBoxModel() {}
  29169. /** This has to return the number of items in the list.
  29170. @see ListBox::getNumRows()
  29171. */
  29172. virtual int getNumRows() = 0;
  29173. /** This method must be implemented to draw a row of the list.
  29174. */
  29175. virtual void paintListBoxItem (int rowNumber,
  29176. Graphics& g,
  29177. int width, int height,
  29178. bool rowIsSelected) = 0;
  29179. /** This is used to create or update a custom component to go in a row of the list.
  29180. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  29181. and handle mouse clicks with listBoxItemClicked().
  29182. This method will be called whenever a custom component might need to be updated - e.g.
  29183. when the table is changed, or TableListBox::updateContent() is called.
  29184. If you don't need a custom component for the specified row, then return 0.
  29185. If you do want a custom component, and the existingComponentToUpdate is null, then
  29186. this method must create a suitable new component and return it.
  29187. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  29188. by this method. In this case, the method must either update it to make sure it's correctly representing
  29189. the given row (which may be different from the one that the component was created for), or it can
  29190. delete this component and return a new one.
  29191. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  29192. */
  29193. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  29194. Component* existingComponentToUpdate);
  29195. /** This can be overridden to react to the user clicking on a row.
  29196. @see listBoxItemDoubleClicked
  29197. */
  29198. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  29199. /** This can be overridden to react to the user double-clicking on a row.
  29200. @see listBoxItemClicked
  29201. */
  29202. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  29203. /** This can be overridden to react to the user double-clicking on a part of the list where
  29204. there are no rows.
  29205. @see listBoxItemClicked
  29206. */
  29207. virtual void backgroundClicked();
  29208. /** Override this to be informed when rows are selected or deselected.
  29209. This will be called whenever a row is selected or deselected. If a range of
  29210. rows is selected all at once, this will just be called once for that event.
  29211. @param lastRowSelected the last row that the user selected. If no
  29212. rows are currently selected, this may be -1.
  29213. */
  29214. virtual void selectedRowsChanged (int lastRowSelected);
  29215. /** Override this to be informed when the delete key is pressed.
  29216. If no rows are selected when they press the key, this won't be called.
  29217. @param lastRowSelected the last row that had been selected when they pressed the
  29218. key - if there are multiple selections, this might not be
  29219. very useful
  29220. */
  29221. virtual void deleteKeyPressed (int lastRowSelected);
  29222. /** Override this to be informed when the return key is pressed.
  29223. If no rows are selected when they press the key, this won't be called.
  29224. @param lastRowSelected the last row that had been selected when they pressed the
  29225. key - if there are multiple selections, this might not be
  29226. very useful
  29227. */
  29228. virtual void returnKeyPressed (int lastRowSelected);
  29229. /** Override this to be informed when the list is scrolled.
  29230. This might be caused by the user moving the scrollbar, or by programmatic changes
  29231. to the list position.
  29232. */
  29233. virtual void listWasScrolled();
  29234. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  29235. If this returns a non-empty name then when the user drags a row, the listbox will
  29236. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  29237. a drag-and-drop operation, using this string as the source description, with the listbox
  29238. itself as the source component.
  29239. @see DragAndDropContainer::startDragging
  29240. */
  29241. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  29242. /** You can override this to provide tool tips for specific rows.
  29243. @see TooltipClient
  29244. */
  29245. virtual const String getTooltipForRow (int row);
  29246. };
  29247. /**
  29248. A list of items that can be scrolled vertically.
  29249. To create a list, you'll need to create a subclass of ListBoxModel. This can
  29250. either paint each row of the list and respond to events via callbacks, or for
  29251. more specialised tasks, it can supply a custom component to fill each row.
  29252. @see ComboBox, TableListBox
  29253. */
  29254. class JUCE_API ListBox : public Component,
  29255. public SettableTooltipClient
  29256. {
  29257. public:
  29258. /** Creates a ListBox.
  29259. The model pointer passed-in can be null, in which case you can set it later
  29260. with setModel().
  29261. */
  29262. ListBox (const String& componentName,
  29263. ListBoxModel* model);
  29264. /** Destructor. */
  29265. ~ListBox();
  29266. /** Changes the current data model to display. */
  29267. void setModel (ListBoxModel* newModel);
  29268. /** Returns the current list model. */
  29269. ListBoxModel* getModel() const throw() { return model; }
  29270. /** Causes the list to refresh its content.
  29271. Call this when the number of rows in the list changes, or if you want it
  29272. to call refreshComponentForRow() on all the row components.
  29273. Be careful not to call it from a different thread, though, as it's not
  29274. thread-safe.
  29275. */
  29276. void updateContent();
  29277. /** Turns on multiple-selection of rows.
  29278. By default this is disabled.
  29279. When your row component gets clicked you'll need to call the
  29280. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  29281. clicked and to get it to do the appropriate selection based on whether
  29282. the ctrl/shift keys are held down.
  29283. */
  29284. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  29285. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  29286. This function is here primarily for the ComboBox class to use, but might be
  29287. useful for some other purpose too.
  29288. */
  29289. void setMouseMoveSelectsRows (bool shouldSelect);
  29290. /** Selects a row.
  29291. If the row is already selected, this won't do anything.
  29292. @param rowNumber the row to select
  29293. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  29294. the selected row is off-screen, it'll scroll to make
  29295. sure that row is on-screen
  29296. @param deselectOthersFirst if true and there are multiple selections, these will
  29297. first be deselected before this item is selected
  29298. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  29299. deselectAllRows, selectRangeOfRows
  29300. */
  29301. void selectRow (int rowNumber,
  29302. bool dontScrollToShowThisRow = false,
  29303. bool deselectOthersFirst = true);
  29304. /** Selects a set of rows.
  29305. This will add these rows to the current selection, so you might need to
  29306. clear the current selection first with deselectAllRows()
  29307. @param firstRow the first row to select (inclusive)
  29308. @param lastRow the last row to select (inclusive)
  29309. */
  29310. void selectRangeOfRows (int firstRow,
  29311. int lastRow);
  29312. /** Deselects a row.
  29313. If it's not currently selected, this will do nothing.
  29314. @see selectRow, deselectAllRows
  29315. */
  29316. void deselectRow (int rowNumber);
  29317. /** Deselects any currently selected rows.
  29318. @see deselectRow
  29319. */
  29320. void deselectAllRows();
  29321. /** Selects or deselects a row.
  29322. If the row's currently selected, this deselects it, and vice-versa.
  29323. */
  29324. void flipRowSelection (int rowNumber);
  29325. /** Returns a sparse set indicating the rows that are currently selected.
  29326. @see setSelectedRows
  29327. */
  29328. const SparseSet<int> getSelectedRows() const;
  29329. /** Sets the rows that should be selected, based on an explicit set of ranges.
  29330. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  29331. method will be called. If it's false, no notification will be sent to the model.
  29332. @see getSelectedRows
  29333. */
  29334. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  29335. bool sendNotificationEventToModel = true);
  29336. /** Checks whether a row is selected.
  29337. */
  29338. bool isRowSelected (int rowNumber) const;
  29339. /** Returns the number of rows that are currently selected.
  29340. @see getSelectedRow, isRowSelected, getLastRowSelected
  29341. */
  29342. int getNumSelectedRows() const;
  29343. /** Returns the row number of a selected row.
  29344. This will return the row number of the Nth selected row. The row numbers returned will
  29345. be sorted in order from low to high.
  29346. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  29347. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  29348. selected
  29349. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  29350. */
  29351. int getSelectedRow (int index = 0) const;
  29352. /** Returns the last row that the user selected.
  29353. This isn't the same as the highest row number that is currently selected - if the user
  29354. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  29355. If nothing is selected, it will return -1.
  29356. */
  29357. int getLastRowSelected() const;
  29358. /** Multiply-selects rows based on the modifier keys.
  29359. If no modifier keys are down, this will select the given row and
  29360. deselect any others.
  29361. If the ctrl (or command on the Mac) key is down, it'll flip the
  29362. state of the selected row.
  29363. If the shift key is down, it'll select up to the given row from the
  29364. last row selected.
  29365. @see selectRow
  29366. */
  29367. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  29368. const ModifierKeys& modifiers);
  29369. /** Scrolls the list to a particular position.
  29370. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  29371. 1.0 scrolls to the bottom.
  29372. If the total number of rows all fit onto the screen at once, then this
  29373. method won't do anything.
  29374. @see getVerticalPosition
  29375. */
  29376. void setVerticalPosition (double newProportion);
  29377. /** Returns the current vertical position as a proportion of the total.
  29378. This can be used in conjunction with setVerticalPosition() to save and restore
  29379. the list's position. It returns a value in the range 0 to 1.
  29380. @see setVerticalPosition
  29381. */
  29382. double getVerticalPosition() const;
  29383. /** Scrolls if necessary to make sure that a particular row is visible.
  29384. */
  29385. void scrollToEnsureRowIsOnscreen (int row);
  29386. /** Returns a pointer to the scrollbar.
  29387. (Unlikely to be useful for most people).
  29388. */
  29389. ScrollBar* getVerticalScrollBar() const throw();
  29390. /** Returns a pointer to the scrollbar.
  29391. (Unlikely to be useful for most people).
  29392. */
  29393. ScrollBar* getHorizontalScrollBar() const throw();
  29394. /** Finds the row index that contains a given x,y position.
  29395. The position is relative to the ListBox's top-left.
  29396. If no row exists at this position, the method will return -1.
  29397. @see getComponentForRowNumber
  29398. */
  29399. int getRowContainingPosition (int x, int y) const throw();
  29400. /** Finds a row index that would be the most suitable place to insert a new
  29401. item for a given position.
  29402. This is useful when the user is e.g. dragging and dropping onto the listbox,
  29403. because it lets you easily choose the best position to insert the item that
  29404. they drop, based on where they drop it.
  29405. If the position is out of range, this will return -1. If the position is
  29406. beyond the end of the list, it will return getNumRows() to indicate the end
  29407. of the list.
  29408. @see getComponentForRowNumber
  29409. */
  29410. int getInsertionIndexForPosition (int x, int y) const throw();
  29411. /** Returns the position of one of the rows, relative to the top-left of
  29412. the listbox.
  29413. This may be off-screen, and the range of the row number that is passed-in is
  29414. not checked to see if it's a valid row.
  29415. */
  29416. const Rectangle<int> getRowPosition (int rowNumber,
  29417. bool relativeToComponentTopLeft) const throw();
  29418. /** Finds the row component for a given row in the list.
  29419. The component returned will have been created using createRowComponent().
  29420. If the component for this row is off-screen or if the row is out-of-range,
  29421. this will return 0.
  29422. @see getRowContainingPosition
  29423. */
  29424. Component* getComponentForRowNumber (int rowNumber) const throw();
  29425. /** Returns the row number that the given component represents.
  29426. If the component isn't one of the list's rows, this will return -1.
  29427. */
  29428. int getRowNumberOfComponent (Component* rowComponent) const throw();
  29429. /** Returns the width of a row (which may be less than the width of this component
  29430. if there's a scrollbar).
  29431. */
  29432. int getVisibleRowWidth() const throw();
  29433. /** Sets the height of each row in the list.
  29434. The default height is 22 pixels.
  29435. @see getRowHeight
  29436. */
  29437. void setRowHeight (int newHeight);
  29438. /** Returns the height of a row in the list.
  29439. @see setRowHeight
  29440. */
  29441. int getRowHeight() const throw() { return rowHeight; }
  29442. /** Returns the number of rows actually visible.
  29443. This is the number of whole rows which will fit on-screen, so the value might
  29444. be more than the actual number of rows in the list.
  29445. */
  29446. int getNumRowsOnScreen() const throw();
  29447. /** A set of colour IDs to use to change the colour of various aspects of the label.
  29448. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29449. methods.
  29450. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29451. */
  29452. enum ColourIds
  29453. {
  29454. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  29455. Make this transparent if you don't want the background to be filled. */
  29456. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  29457. Make this transparent to not have an outline. */
  29458. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  29459. };
  29460. /** Sets the thickness of a border that will be drawn around the box.
  29461. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  29462. @see outlineColourId
  29463. */
  29464. void setOutlineThickness (int outlineThickness);
  29465. /** Returns the thickness of outline that will be drawn around the listbox.
  29466. @see setOutlineColour
  29467. */
  29468. int getOutlineThickness() const throw() { return outlineThickness; }
  29469. /** Sets a component that the list should use as a header.
  29470. This will position the given component at the top of the list, maintaining the
  29471. height of the component passed-in, but rescaling it horizontally to match the
  29472. width of the items in the listbox.
  29473. The component will be deleted when setHeaderComponent() is called with a
  29474. different component, or when the listbox is deleted.
  29475. */
  29476. void setHeaderComponent (Component* newHeaderComponent);
  29477. /** Changes the width of the rows in the list.
  29478. This can be used to make the list's row components wider than the list itself - the
  29479. width of the rows will be either the width of the list or this value, whichever is
  29480. greater, and if the rows become wider than the list, a horizontal scrollbar will
  29481. appear.
  29482. The default value for this is 0, which means that the rows will always
  29483. be the same width as the list.
  29484. */
  29485. void setMinimumContentWidth (int newMinimumWidth);
  29486. /** Returns the space currently available for the row items, taking into account
  29487. borders, scrollbars, etc.
  29488. */
  29489. int getVisibleContentWidth() const throw();
  29490. /** Repaints one of the rows.
  29491. This is a lightweight alternative to calling updateContent, and just causes a
  29492. repaint of the row's area.
  29493. */
  29494. void repaintRow (int rowNumber) throw();
  29495. /** This fairly obscure method creates an image that just shows the currently
  29496. selected row components.
  29497. It's a handy method for doing drag-and-drop, as it can be passed to the
  29498. DragAndDropContainer for use as the drag image.
  29499. Note that it will make the row components temporarily invisible, so if you're
  29500. using custom components this could affect them if they're sensitive to that
  29501. sort of thing.
  29502. @see Component::createComponentSnapshot
  29503. */
  29504. Image* createSnapshotOfSelectedRows (int& x, int& y);
  29505. /** Returns the viewport that this ListBox uses.
  29506. You may need to use this to change parameters such as whether scrollbars
  29507. are shown, etc.
  29508. */
  29509. Viewport* getViewport() const throw();
  29510. /** @internal */
  29511. bool keyPressed (const KeyPress& key);
  29512. /** @internal */
  29513. bool keyStateChanged (bool isKeyDown);
  29514. /** @internal */
  29515. void paint (Graphics& g);
  29516. /** @internal */
  29517. void paintOverChildren (Graphics& g);
  29518. /** @internal */
  29519. void resized();
  29520. /** @internal */
  29521. void visibilityChanged();
  29522. /** @internal */
  29523. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  29524. /** @internal */
  29525. void mouseMove (const MouseEvent&);
  29526. /** @internal */
  29527. void mouseExit (const MouseEvent&);
  29528. /** @internal */
  29529. void mouseUp (const MouseEvent&);
  29530. /** @internal */
  29531. void colourChanged();
  29532. /** @internal */
  29533. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  29534. juce_UseDebuggingNewOperator
  29535. private:
  29536. friend class ListViewport;
  29537. friend class TableListBox;
  29538. ListBoxModel* model;
  29539. ListViewport* viewport;
  29540. Component* headerComponent;
  29541. int totalItems, rowHeight, minimumRowWidth;
  29542. int outlineThickness;
  29543. int lastRowSelected;
  29544. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  29545. SparseSet <int> selected;
  29546. void selectRowInternal (int rowNumber,
  29547. bool dontScrollToShowThisRow,
  29548. bool deselectOthersFirst,
  29549. bool isMouseClick);
  29550. ListBox (const ListBox&);
  29551. ListBox& operator= (const ListBox&);
  29552. };
  29553. #endif // __JUCE_LISTBOX_JUCEHEADER__
  29554. /*** End of inlined file: juce_ListBox.h ***/
  29555. /*** Start of inlined file: juce_TextButton.h ***/
  29556. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  29557. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  29558. /**
  29559. A button that uses the standard lozenge-shaped background with a line of
  29560. text on it.
  29561. @see Button, DrawableButton
  29562. */
  29563. class JUCE_API TextButton : public Button
  29564. {
  29565. public:
  29566. /** Creates a TextButton.
  29567. @param buttonName the text to put in the button (the component's name is also
  29568. initially set to this string, but these can be changed later
  29569. using the setName() and setButtonText() methods)
  29570. @param toolTip an optional string to use as a toolip
  29571. @see Button
  29572. */
  29573. TextButton (const String& buttonName = String::empty,
  29574. const String& toolTip = String::empty);
  29575. /** Destructor. */
  29576. ~TextButton();
  29577. /** A set of colour IDs to use to change the colour of various aspects of the button.
  29578. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  29579. methods.
  29580. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  29581. */
  29582. enum ColourIds
  29583. {
  29584. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  29585. 'off'). The look-and-feel class might re-interpret this to add
  29586. effects, etc. */
  29587. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  29588. 'on'). The look-and-feel class might re-interpret this to add
  29589. effects, etc. */
  29590. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  29591. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  29592. };
  29593. /** Resizes the button to fit neatly around its current text.
  29594. If newHeight is >= 0, the button's height will be changed to this
  29595. value. If it's less than zero, its height will be unaffected.
  29596. */
  29597. void changeWidthToFitText (int newHeight = -1);
  29598. /** This can be overridden to use different fonts than the default one.
  29599. Note that you'll need to set the font's size appropriately, too.
  29600. */
  29601. virtual const Font getFont();
  29602. juce_UseDebuggingNewOperator
  29603. protected:
  29604. /** @internal */
  29605. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  29606. /** @internal */
  29607. void colourChanged();
  29608. private:
  29609. TextButton (const TextButton&);
  29610. TextButton& operator= (const TextButton&);
  29611. };
  29612. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  29613. /*** End of inlined file: juce_TextButton.h ***/
  29614. /**
  29615. A component displaying a list of plugins, with options to scan for them,
  29616. add, remove and sort them.
  29617. */
  29618. class JUCE_API PluginListComponent : public Component,
  29619. public ListBoxModel,
  29620. public ChangeListener,
  29621. public ButtonListener,
  29622. public Timer
  29623. {
  29624. public:
  29625. /**
  29626. Creates the list component.
  29627. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  29628. The properties file, if supplied, is used to store the user's last search paths.
  29629. */
  29630. PluginListComponent (KnownPluginList& listToRepresent,
  29631. const File& deadMansPedalFile,
  29632. PropertiesFile* propertiesToUse);
  29633. /** Destructor. */
  29634. ~PluginListComponent();
  29635. /** @internal */
  29636. void resized();
  29637. /** @internal */
  29638. bool isInterestedInFileDrag (const StringArray& files);
  29639. /** @internal */
  29640. void filesDropped (const StringArray& files, int, int);
  29641. /** @internal */
  29642. int getNumRows();
  29643. /** @internal */
  29644. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  29645. /** @internal */
  29646. void deleteKeyPressed (int lastRowSelected);
  29647. /** @internal */
  29648. void buttonClicked (Button* b);
  29649. /** @internal */
  29650. void changeListenerCallback (void*);
  29651. /** @internal */
  29652. void timerCallback();
  29653. juce_UseDebuggingNewOperator
  29654. private:
  29655. KnownPluginList& list;
  29656. File deadMansPedalFile;
  29657. ListBox* listBox;
  29658. TextButton* optionsButton;
  29659. PropertiesFile* propertiesToUse;
  29660. int typeToScan;
  29661. void scanFor (AudioPluginFormat* format);
  29662. PluginListComponent (const PluginListComponent&);
  29663. PluginListComponent& operator= (const PluginListComponent&);
  29664. };
  29665. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29666. /*** End of inlined file: juce_PluginListComponent.h ***/
  29667. #endif
  29668. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  29669. #endif
  29670. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  29671. #endif
  29672. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  29673. #endif
  29674. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  29675. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  29676. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  29677. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  29678. /**
  29679. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  29680. Use one of these objects if you want to wire-up a set of AudioProcessors
  29681. and play back the result.
  29682. Processors can be added to the graph as "nodes" using addNode(), and once
  29683. added, you can connect any of their input or output channels to other
  29684. nodes using addConnection().
  29685. To play back a graph through an audio device, you might want to use an
  29686. AudioProcessorPlayer object.
  29687. */
  29688. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  29689. public AsyncUpdater
  29690. {
  29691. public:
  29692. /** Creates an empty graph.
  29693. */
  29694. AudioProcessorGraph();
  29695. /** Destructor.
  29696. Any processor objects that have been added to the graph will also be deleted.
  29697. */
  29698. ~AudioProcessorGraph();
  29699. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  29700. To create a node, call AudioProcessorGraph::addNode().
  29701. */
  29702. class JUCE_API Node : public ReferenceCountedObject
  29703. {
  29704. public:
  29705. /** Destructor.
  29706. */
  29707. ~Node();
  29708. /** The ID number assigned to this node.
  29709. This is assigned by the graph that owns it, and can't be changed.
  29710. */
  29711. const uint32 id;
  29712. /** The actual processor object that this node represents.
  29713. */
  29714. AudioProcessor* const processor;
  29715. /** A set of user-definable properties that are associated with this node.
  29716. This can be used to attach values to the node for whatever purpose seems
  29717. useful. For example, you might store an x and y position if your application
  29718. is displaying the nodes on-screen.
  29719. */
  29720. NamedValueSet properties;
  29721. /** A convenient typedef for referring to a pointer to a node object.
  29722. */
  29723. typedef ReferenceCountedObjectPtr <Node> Ptr;
  29724. juce_UseDebuggingNewOperator
  29725. private:
  29726. friend class AudioProcessorGraph;
  29727. bool isPrepared;
  29728. Node (uint32 id, AudioProcessor* processor);
  29729. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  29730. void unprepare();
  29731. Node (const Node&);
  29732. Node& operator= (const Node&);
  29733. };
  29734. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  29735. To create a connection, use AudioProcessorGraph::addConnection().
  29736. */
  29737. struct JUCE_API Connection
  29738. {
  29739. public:
  29740. /** The ID number of the node which is the input source for this connection.
  29741. @see AudioProcessorGraph::getNodeForId
  29742. */
  29743. uint32 sourceNodeId;
  29744. /** The index of the output channel of the source node from which this
  29745. connection takes its data.
  29746. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  29747. it is referring to the source node's midi output. Otherwise, it is the zero-based
  29748. index of an audio output channel in the source node.
  29749. */
  29750. int sourceChannelIndex;
  29751. /** The ID number of the node which is the destination for this connection.
  29752. @see AudioProcessorGraph::getNodeForId
  29753. */
  29754. uint32 destNodeId;
  29755. /** The index of the input channel of the destination node to which this
  29756. connection delivers its data.
  29757. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  29758. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  29759. index of an audio input channel in the destination node.
  29760. */
  29761. int destChannelIndex;
  29762. juce_UseDebuggingNewOperator
  29763. private:
  29764. };
  29765. /** Deletes all nodes and connections from this graph.
  29766. Any processor objects in the graph will be deleted.
  29767. */
  29768. void clear();
  29769. /** Returns the number of nodes in the graph. */
  29770. int getNumNodes() const { return nodes.size(); }
  29771. /** Returns a pointer to one of the nodes in the graph.
  29772. This will return 0 if the index is out of range.
  29773. @see getNodeForId
  29774. */
  29775. Node* getNode (const int index) const { return nodes [index]; }
  29776. /** Searches the graph for a node with the given ID number and returns it.
  29777. If no such node was found, this returns 0.
  29778. @see getNode
  29779. */
  29780. Node* getNodeForId (const uint32 nodeId) const;
  29781. /** Adds a node to the graph.
  29782. This creates a new node in the graph, for the specified processor. Once you have
  29783. added a processor to the graph, the graph owns it and will delete it later when
  29784. it is no longer needed.
  29785. The optional nodeId parameter lets you specify an ID to use for the node, but
  29786. if the value is already in use, this new node will overwrite the old one.
  29787. If this succeeds, it returns a pointer to the newly-created node.
  29788. */
  29789. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  29790. /** Deletes a node within the graph which has the specified ID.
  29791. This will also delete any connections that are attached to this node.
  29792. */
  29793. bool removeNode (uint32 nodeId);
  29794. /** Returns the number of connections in the graph. */
  29795. int getNumConnections() const { return connections.size(); }
  29796. /** Returns a pointer to one of the connections in the graph. */
  29797. const Connection* getConnection (int index) const { return connections [index]; }
  29798. /** Searches for a connection between some specified channels.
  29799. If no such connection is found, this returns 0.
  29800. */
  29801. const Connection* getConnectionBetween (uint32 sourceNodeId,
  29802. int sourceChannelIndex,
  29803. uint32 destNodeId,
  29804. int destChannelIndex) const;
  29805. /** Returns true if there is a connection between any of the channels of
  29806. two specified nodes.
  29807. */
  29808. bool isConnected (uint32 possibleSourceNodeId,
  29809. uint32 possibleDestNodeId) const;
  29810. /** Returns true if it would be legal to connect the specified points.
  29811. */
  29812. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  29813. uint32 destNodeId, int destChannelIndex) const;
  29814. /** Attempts to connect two specified channels of two nodes.
  29815. If this isn't allowed (e.g. because you're trying to connect a midi channel
  29816. to an audio one or other such nonsense), then it'll return false.
  29817. */
  29818. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  29819. uint32 destNodeId, int destChannelIndex);
  29820. /** Deletes the connection with the specified index.
  29821. Returns true if a connection was actually deleted.
  29822. */
  29823. void removeConnection (int index);
  29824. /** Deletes any connection between two specified points.
  29825. Returns true if a connection was actually deleted.
  29826. */
  29827. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  29828. uint32 destNodeId, int destChannelIndex);
  29829. /** Removes all connections from the specified node.
  29830. */
  29831. bool disconnectNode (uint32 nodeId);
  29832. /** Performs a sanity checks of all the connections.
  29833. This might be useful if some of the processors are doing things like changing
  29834. their channel counts, which could render some connections obsolete.
  29835. */
  29836. bool removeIllegalConnections();
  29837. /** A special number that represents the midi channel of a node.
  29838. This is used as a channel index value if you want to refer to the midi input
  29839. or output instead of an audio channel.
  29840. */
  29841. static const int midiChannelIndex;
  29842. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  29843. in order to use the audio that comes into and out of the graph itself.
  29844. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  29845. node in the graph which delivers the audio that is coming into the parent
  29846. graph. This allows you to stream the data to other nodes and process the
  29847. incoming audio.
  29848. Likewise, one of these in "output" mode can be sent data which it will add to
  29849. the sum of data being sent to the graph's output.
  29850. @see AudioProcessorGraph
  29851. */
  29852. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  29853. {
  29854. public:
  29855. /** Specifies the mode in which this processor will operate.
  29856. */
  29857. enum IODeviceType
  29858. {
  29859. audioInputNode, /**< In this mode, the processor has output channels
  29860. representing all the audio input channels that are
  29861. coming into its parent audio graph. */
  29862. audioOutputNode, /**< In this mode, the processor has input channels
  29863. representing all the audio output channels that are
  29864. going out of its parent audio graph. */
  29865. midiInputNode, /**< In this mode, the processor has a midi output which
  29866. delivers the same midi data that is arriving at its
  29867. parent graph. */
  29868. midiOutputNode /**< In this mode, the processor has a midi input and
  29869. any data sent to it will be passed out of the parent
  29870. graph. */
  29871. };
  29872. /** Returns the mode of this processor. */
  29873. IODeviceType getType() const { return type; }
  29874. /** Returns the parent graph to which this processor belongs, or 0 if it
  29875. hasn't yet been added to one. */
  29876. AudioProcessorGraph* getParentGraph() const { return graph; }
  29877. /** True if this is an audio or midi input. */
  29878. bool isInput() const;
  29879. /** True if this is an audio or midi output. */
  29880. bool isOutput() const;
  29881. AudioGraphIOProcessor (const IODeviceType type);
  29882. ~AudioGraphIOProcessor();
  29883. const String getName() const;
  29884. void fillInPluginDescription (PluginDescription& d) const;
  29885. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  29886. void releaseResources();
  29887. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  29888. const String getInputChannelName (const int channelIndex) const;
  29889. const String getOutputChannelName (const int channelIndex) const;
  29890. bool isInputChannelStereoPair (int index) const;
  29891. bool isOutputChannelStereoPair (int index) const;
  29892. bool acceptsMidi() const;
  29893. bool producesMidi() const;
  29894. AudioProcessorEditor* createEditor();
  29895. int getNumParameters();
  29896. const String getParameterName (int);
  29897. float getParameter (int);
  29898. const String getParameterText (int);
  29899. void setParameter (int, float);
  29900. int getNumPrograms();
  29901. int getCurrentProgram();
  29902. void setCurrentProgram (int);
  29903. const String getProgramName (int);
  29904. void changeProgramName (int, const String&);
  29905. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  29906. void setStateInformation (const void* data, int sizeInBytes);
  29907. /** @internal */
  29908. void setParentGraph (AudioProcessorGraph* graph);
  29909. juce_UseDebuggingNewOperator
  29910. private:
  29911. const IODeviceType type;
  29912. AudioProcessorGraph* graph;
  29913. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  29914. AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  29915. };
  29916. // AudioProcessor methods:
  29917. const String getName() const;
  29918. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  29919. void releaseResources();
  29920. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  29921. const String getInputChannelName (const int channelIndex) const;
  29922. const String getOutputChannelName (const int channelIndex) const;
  29923. bool isInputChannelStereoPair (int index) const;
  29924. bool isOutputChannelStereoPair (int index) const;
  29925. bool acceptsMidi() const;
  29926. bool producesMidi() const;
  29927. AudioProcessorEditor* createEditor() { return 0; }
  29928. int getNumParameters() { return 0; }
  29929. const String getParameterName (int) { return String::empty; }
  29930. float getParameter (int) { return 0; }
  29931. const String getParameterText (int) { return String::empty; }
  29932. void setParameter (int, float) { }
  29933. int getNumPrograms() { return 0; }
  29934. int getCurrentProgram() { return 0; }
  29935. void setCurrentProgram (int) { }
  29936. const String getProgramName (int) { return String::empty; }
  29937. void changeProgramName (int, const String&) { }
  29938. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  29939. void setStateInformation (const void* data, int sizeInBytes);
  29940. /** @internal */
  29941. void handleAsyncUpdate();
  29942. juce_UseDebuggingNewOperator
  29943. private:
  29944. ReferenceCountedArray <Node> nodes;
  29945. OwnedArray <Connection> connections;
  29946. int lastNodeId;
  29947. AudioSampleBuffer renderingBuffers;
  29948. OwnedArray <MidiBuffer> midiBuffers;
  29949. CriticalSection renderLock;
  29950. Array<void*> renderingOps;
  29951. friend class AudioGraphIOProcessor;
  29952. AudioSampleBuffer* currentAudioInputBuffer;
  29953. AudioSampleBuffer currentAudioOutputBuffer;
  29954. MidiBuffer* currentMidiInputBuffer;
  29955. MidiBuffer currentMidiOutputBuffer;
  29956. void clearRenderingSequence();
  29957. void buildRenderingSequence();
  29958. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  29959. AudioProcessorGraph (const AudioProcessorGraph&);
  29960. AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  29961. };
  29962. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  29963. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  29964. #endif
  29965. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  29966. #endif
  29967. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  29968. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  29969. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  29970. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  29971. /**
  29972. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  29973. To use one of these, just make it the callback used by your AudioIODevice, and
  29974. give it a processor to use by calling setProcessor().
  29975. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  29976. input to send both streams through the processor.
  29977. @see AudioProcessor, AudioProcessorGraph
  29978. */
  29979. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  29980. public MidiInputCallback
  29981. {
  29982. public:
  29983. /**
  29984. */
  29985. AudioProcessorPlayer();
  29986. /** Destructor. */
  29987. virtual ~AudioProcessorPlayer();
  29988. /** Sets the processor that should be played.
  29989. The processor that is passed in will not be deleted or owned by this object.
  29990. To stop anything playing, pass in 0 to this method.
  29991. */
  29992. void setProcessor (AudioProcessor* const processorToPlay);
  29993. /** Returns the current audio processor that is being played.
  29994. */
  29995. AudioProcessor* getCurrentProcessor() const { return processor; }
  29996. /** Returns a midi message collector that you can pass midi messages to if you
  29997. want them to be injected into the midi stream that is being sent to the
  29998. processor.
  29999. */
  30000. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  30001. /** @internal */
  30002. void audioDeviceIOCallback (const float** inputChannelData,
  30003. int totalNumInputChannels,
  30004. float** outputChannelData,
  30005. int totalNumOutputChannels,
  30006. int numSamples);
  30007. /** @internal */
  30008. void audioDeviceAboutToStart (AudioIODevice* device);
  30009. /** @internal */
  30010. void audioDeviceStopped();
  30011. /** @internal */
  30012. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  30013. juce_UseDebuggingNewOperator
  30014. private:
  30015. AudioProcessor* processor;
  30016. CriticalSection lock;
  30017. double sampleRate;
  30018. int blockSize;
  30019. bool isPrepared;
  30020. int numInputChans, numOutputChans;
  30021. float* channels [128];
  30022. AudioSampleBuffer tempBuffer;
  30023. MidiBuffer incomingMidi;
  30024. MidiMessageCollector messageCollector;
  30025. AudioProcessorPlayer (const AudioProcessorPlayer&);
  30026. AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  30027. };
  30028. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30029. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  30030. #endif
  30031. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30032. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30033. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30034. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30035. /*** Start of inlined file: juce_PropertyPanel.h ***/
  30036. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  30037. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  30038. /*** Start of inlined file: juce_PropertyComponent.h ***/
  30039. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30040. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30041. class EditableProperty;
  30042. /**
  30043. A base class for a component that goes in a PropertyPanel and displays one of
  30044. an item's properties.
  30045. Subclasses of this are used to display a property in various forms, e.g. a
  30046. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  30047. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  30048. A subclass must implement the refresh() method which will be called to tell the
  30049. component to update itself, and is also responsible for calling this it when the
  30050. item that it refers to is changed.
  30051. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  30052. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  30053. */
  30054. class JUCE_API PropertyComponent : public Component,
  30055. public SettableTooltipClient
  30056. {
  30057. public:
  30058. /** Creates a PropertyComponent.
  30059. @param propertyName the name is stored as this component's name, and is
  30060. used as the name displayed next to this component in
  30061. a property panel
  30062. @param preferredHeight the height that the component should be given - some
  30063. items may need to be larger than a normal row height.
  30064. This value can also be set if a subclass changes the
  30065. preferredHeight member variable.
  30066. */
  30067. PropertyComponent (const String& propertyName,
  30068. int preferredHeight = 25);
  30069. /** Destructor. */
  30070. ~PropertyComponent();
  30071. /** Returns this item's preferred height.
  30072. This value is specified either in the constructor or by a subclass changing the
  30073. preferredHeight member variable.
  30074. */
  30075. int getPreferredHeight() const throw() { return preferredHeight; }
  30076. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  30077. /** Updates the property component if the item it refers to has changed.
  30078. A subclass must implement this method, and other objects may call it to
  30079. force it to refresh itself.
  30080. The subclass should be economical in the amount of work is done, so for
  30081. example it should check whether it really needs to do a repaint rather than
  30082. just doing one every time this method is called, as it may be called when
  30083. the value being displayed hasn't actually changed.
  30084. */
  30085. virtual void refresh() = 0;
  30086. /** The default paint method fills the background and draws a label for the
  30087. item's name.
  30088. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  30089. */
  30090. void paint (Graphics& g);
  30091. /** The default resize method positions any child component to the right of this
  30092. one, based on the look and feel's default label size.
  30093. */
  30094. void resized();
  30095. /** By default, this just repaints the component. */
  30096. void enablementChanged();
  30097. juce_UseDebuggingNewOperator
  30098. protected:
  30099. /** Used by the PropertyPanel to determine how high this component needs to be.
  30100. A subclass can update this value in its constructor but shouldn't alter it later
  30101. as changes won't necessarily be picked up.
  30102. */
  30103. int preferredHeight;
  30104. };
  30105. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30106. /*** End of inlined file: juce_PropertyComponent.h ***/
  30107. /**
  30108. A panel that holds a list of PropertyComponent objects.
  30109. This panel displays a list of PropertyComponents, and allows them to be organised
  30110. into collapsible sections.
  30111. To use, simply create one of these and add your properties to it with addProperties()
  30112. or addSection().
  30113. @see PropertyComponent
  30114. */
  30115. class JUCE_API PropertyPanel : public Component
  30116. {
  30117. public:
  30118. /** Creates an empty property panel. */
  30119. PropertyPanel();
  30120. /** Destructor. */
  30121. ~PropertyPanel();
  30122. /** Deletes all property components from the panel.
  30123. */
  30124. void clear();
  30125. /** Adds a set of properties to the panel.
  30126. The components in the list will be owned by this object and will be automatically
  30127. deleted later on when no longer needed.
  30128. These properties are added without them being inside a named section. If you
  30129. want them to be kept together in a collapsible section, use addSection() instead.
  30130. */
  30131. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  30132. /** Adds a set of properties to the panel.
  30133. These properties are added at the bottom of the list, under a section heading with
  30134. a plus/minus button that allows it to be opened and closed.
  30135. The components in the list will be owned by this object and will be automatically
  30136. deleted later on when no longer needed.
  30137. To add properies without them being in a section, use addProperties().
  30138. */
  30139. void addSection (const String& sectionTitle,
  30140. const Array <PropertyComponent*>& newPropertyComponents,
  30141. bool shouldSectionInitiallyBeOpen = true);
  30142. /** Calls the refresh() method of all PropertyComponents in the panel */
  30143. void refreshAll() const;
  30144. /** Returns a list of all the names of sections in the panel.
  30145. These are the sections that have been added with addSection().
  30146. */
  30147. const StringArray getSectionNames() const;
  30148. /** Returns true if the section at this index is currently open.
  30149. The index is from 0 up to the number of items returned by getSectionNames().
  30150. */
  30151. bool isSectionOpen (int sectionIndex) const;
  30152. /** Opens or closes one of the sections.
  30153. The index is from 0 up to the number of items returned by getSectionNames().
  30154. */
  30155. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  30156. /** Enables or disables one of the sections.
  30157. The index is from 0 up to the number of items returned by getSectionNames().
  30158. */
  30159. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  30160. /** Saves the current state of open/closed sections so it can be restored later.
  30161. The caller is responsible for deleting the object that is returned.
  30162. To restore this state, use restoreOpennessState().
  30163. @see restoreOpennessState
  30164. */
  30165. XmlElement* getOpennessState() const;
  30166. /** Restores a previously saved arrangement of open/closed sections.
  30167. This will try to restore a snapshot of the panel's state that was created by
  30168. the getOpennessState() method. If any of the sections named in the original
  30169. XML aren't present, they will be ignored.
  30170. @see getOpennessState
  30171. */
  30172. void restoreOpennessState (const XmlElement& newState);
  30173. /** Sets a message to be displayed when there are no properties in the panel.
  30174. The default message is "nothing selected".
  30175. */
  30176. void setMessageWhenEmpty (const String& newMessage);
  30177. /** Returns the message that is displayed when there are no properties.
  30178. @see setMessageWhenEmpty
  30179. */
  30180. const String& getMessageWhenEmpty() const;
  30181. /** @internal */
  30182. void paint (Graphics& g);
  30183. /** @internal */
  30184. void resized();
  30185. juce_UseDebuggingNewOperator
  30186. private:
  30187. Viewport* viewport;
  30188. class PropertyHolderComponent;
  30189. PropertyHolderComponent* propertyHolderComponent;
  30190. String messageWhenEmpty;
  30191. void updatePropHolderLayout() const;
  30192. void updatePropHolderLayout (int width) const;
  30193. };
  30194. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  30195. /*** End of inlined file: juce_PropertyPanel.h ***/
  30196. /**
  30197. A type of UI component that displays the parameters of an AudioProcessor as
  30198. a simple list of sliders.
  30199. This can be used for showing an editor for a processor that doesn't supply
  30200. its own custom editor.
  30201. @see AudioProcessor
  30202. */
  30203. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  30204. {
  30205. public:
  30206. GenericAudioProcessorEditor (AudioProcessor* const owner);
  30207. ~GenericAudioProcessorEditor();
  30208. void paint (Graphics& g);
  30209. void resized();
  30210. juce_UseDebuggingNewOperator
  30211. private:
  30212. PropertyPanel* panel;
  30213. GenericAudioProcessorEditor (const GenericAudioProcessorEditor&);
  30214. GenericAudioProcessorEditor& operator= (const GenericAudioProcessorEditor&);
  30215. };
  30216. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30217. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30218. #endif
  30219. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30220. /*** Start of inlined file: juce_Sampler.h ***/
  30221. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30222. #define __JUCE_SAMPLER_JUCEHEADER__
  30223. /*** Start of inlined file: juce_Synthesiser.h ***/
  30224. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  30225. #define __JUCE_SYNTHESISER_JUCEHEADER__
  30226. /**
  30227. Describes one of the sounds that a Synthesiser can play.
  30228. A synthesiser can contain one or more sounds, and a sound can choose which
  30229. midi notes and channels can trigger it.
  30230. The SynthesiserSound is a passive class that just describes what the sound is -
  30231. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  30232. more than one SynthesiserVoice to play the same sound at the same time.
  30233. @see Synthesiser, SynthesiserVoice
  30234. */
  30235. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  30236. {
  30237. protected:
  30238. SynthesiserSound();
  30239. public:
  30240. /** Destructor. */
  30241. virtual ~SynthesiserSound();
  30242. /** Returns true if this sound should be played when a given midi note is pressed.
  30243. The Synthesiser will use this information when deciding which sounds to trigger
  30244. for a given note.
  30245. */
  30246. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  30247. /** Returns true if the sound should be triggered by midi events on a given channel.
  30248. The Synthesiser will use this information when deciding which sounds to trigger
  30249. for a given note.
  30250. */
  30251. virtual bool appliesToChannel (const int midiChannel) = 0;
  30252. /**
  30253. */
  30254. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  30255. juce_UseDebuggingNewOperator
  30256. };
  30257. /**
  30258. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  30259. A voice plays a single sound at a time, and a synthesiser holds an array of
  30260. voices so that it can play polyphonically.
  30261. @see Synthesiser, SynthesiserSound
  30262. */
  30263. class JUCE_API SynthesiserVoice
  30264. {
  30265. public:
  30266. /** Creates a voice. */
  30267. SynthesiserVoice();
  30268. /** Destructor. */
  30269. virtual ~SynthesiserVoice();
  30270. /** Returns the midi note that this voice is currently playing.
  30271. Returns a value less than 0 if no note is playing.
  30272. */
  30273. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  30274. /** Returns the sound that this voice is currently playing.
  30275. Returns 0 if it's not playing.
  30276. */
  30277. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  30278. /** Must return true if this voice object is capable of playing the given sound.
  30279. If there are different classes of sound, and different classes of voice, a voice can
  30280. choose which ones it wants to take on.
  30281. A typical implementation of this method may just return true if there's only one type
  30282. of voice and sound, or it might check the type of the sound object passed-in and
  30283. see if it's one that it understands.
  30284. */
  30285. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  30286. /** Called to start a new note.
  30287. This will be called during the rendering callback, so must be fast and thread-safe.
  30288. */
  30289. virtual void startNote (const int midiNoteNumber,
  30290. const float velocity,
  30291. SynthesiserSound* sound,
  30292. const int currentPitchWheelPosition) = 0;
  30293. /** Called to stop a note.
  30294. This will be called during the rendering callback, so must be fast and thread-safe.
  30295. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  30296. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  30297. and allow the synth to reassign it another sound.
  30298. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  30299. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  30300. finishes playing (during the rendering callback), it must make sure that it calls
  30301. clearCurrentNote().
  30302. */
  30303. virtual void stopNote (const bool allowTailOff) = 0;
  30304. /** Called to let the voice know that the pitch wheel has been moved.
  30305. This will be called during the rendering callback, so must be fast and thread-safe.
  30306. */
  30307. virtual void pitchWheelMoved (const int newValue) = 0;
  30308. /** Called to let the voice know that a midi controller has been moved.
  30309. This will be called during the rendering callback, so must be fast and thread-safe.
  30310. */
  30311. virtual void controllerMoved (const int controllerNumber,
  30312. const int newValue) = 0;
  30313. /** Renders the next block of data for this voice.
  30314. The output audio data must be added to the current contents of the buffer provided.
  30315. Only the region of the buffer between startSample and (startSample + numSamples)
  30316. should be altered by this method.
  30317. If the voice is currently silent, it should just return without doing anything.
  30318. If the sound that the voice is playing finishes during the course of this rendered
  30319. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  30320. The size of the blocks that are rendered can change each time it is called, and may
  30321. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  30322. the voice's methods will be called to tell it about note and controller events.
  30323. */
  30324. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  30325. int startSample,
  30326. int numSamples) = 0;
  30327. /** Returns true if the voice is currently playing a sound which is mapped to the given
  30328. midi channel.
  30329. If it's not currently playing, this will return false.
  30330. */
  30331. bool isPlayingChannel (int midiChannel) const;
  30332. /** Changes the voice's reference sample rate.
  30333. The rate is set so that subclasses know the output rate and can set their pitch
  30334. accordingly.
  30335. This method is called by the synth, and subclasses can access the current rate with
  30336. the currentSampleRate member.
  30337. */
  30338. void setCurrentPlaybackSampleRate (double newRate);
  30339. juce_UseDebuggingNewOperator
  30340. protected:
  30341. /** Returns the current target sample rate at which rendering is being done.
  30342. This is available for subclasses so they can pitch things correctly.
  30343. */
  30344. double getSampleRate() const { return currentSampleRate; }
  30345. /** Resets the state of this voice after a sound has finished playing.
  30346. The subclass must call this when it finishes playing a note and becomes available
  30347. to play new ones.
  30348. It must either call it in the stopNote() method, or if the voice is tailing off,
  30349. then it should call it later during the renderNextBlock method, as soon as it
  30350. finishes its tail-off.
  30351. It can also be called at any time during the render callback if the sound happens
  30352. to have finished, e.g. if it's playing a sample and the sample finishes.
  30353. */
  30354. void clearCurrentNote();
  30355. private:
  30356. friend class Synthesiser;
  30357. double currentSampleRate;
  30358. int currentlyPlayingNote;
  30359. uint32 noteOnTime;
  30360. SynthesiserSound::Ptr currentlyPlayingSound;
  30361. };
  30362. /**
  30363. Base class for a musical device that can play sounds.
  30364. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  30365. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  30366. which can play back one of these sounds.
  30367. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  30368. set of sounds, and a set of voices it can use to play them. If you only give it
  30369. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  30370. have available.
  30371. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  30372. events that go in will be scanned for note on/off messages, and these are used to
  30373. start and stop the voices playing the appropriate sounds.
  30374. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  30375. noteOff() and other controller methods.
  30376. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  30377. what the target playback rate is. This value is passed on to the voices so that
  30378. they can pitch their output correctly.
  30379. */
  30380. class JUCE_API Synthesiser
  30381. {
  30382. public:
  30383. /** Creates a new synthesiser.
  30384. You'll need to add some sounds and voices before it'll make any sound..
  30385. */
  30386. Synthesiser();
  30387. /** Destructor. */
  30388. virtual ~Synthesiser();
  30389. /** Deletes all voices. */
  30390. void clearVoices();
  30391. /** Returns the number of voices that have been added. */
  30392. int getNumVoices() const { return voices.size(); }
  30393. /** Returns one of the voices that have been added. */
  30394. SynthesiserVoice* getVoice (int index) const;
  30395. /** Adds a new voice to the synth.
  30396. All the voices should be the same class of object and are treated equally.
  30397. The object passed in will be managed by the synthesiser, which will delete
  30398. it later on when no longer needed. The caller should not retain a pointer to the
  30399. voice.
  30400. */
  30401. void addVoice (SynthesiserVoice* newVoice);
  30402. /** Deletes one of the voices. */
  30403. void removeVoice (int index);
  30404. /** Deletes all sounds. */
  30405. void clearSounds();
  30406. /** Returns the number of sounds that have been added to the synth. */
  30407. int getNumSounds() const { return sounds.size(); }
  30408. /** Returns one of the sounds. */
  30409. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  30410. /** Adds a new sound to the synthesiser.
  30411. The object passed in is reference counted, so will be deleted when it is removed
  30412. from the synthesiser, and when no voices are still using it.
  30413. */
  30414. void addSound (const SynthesiserSound::Ptr& newSound);
  30415. /** Removes and deletes one of the sounds. */
  30416. void removeSound (int index);
  30417. /** If set to true, then the synth will try to take over an existing voice if
  30418. it runs out and needs to play another note.
  30419. The value of this boolean is passed into findFreeVoice(), so the result will
  30420. depend on the implementation of this method.
  30421. */
  30422. void setNoteStealingEnabled (bool shouldStealNotes);
  30423. /** Returns true if note-stealing is enabled.
  30424. @see setNoteStealingEnabled
  30425. */
  30426. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  30427. /** Triggers a note-on event.
  30428. The default method here will find all the sounds that want to be triggered by
  30429. this note/channel. For each sound, it'll try to find a free voice, and use the
  30430. voice to start playing the sound.
  30431. Subclasses might want to override this if they need a more complex algorithm.
  30432. This method will be called automatically according to the midi data passed into
  30433. renderNextBlock(), but may be called explicitly too.
  30434. */
  30435. virtual void noteOn (const int midiChannel,
  30436. const int midiNoteNumber,
  30437. const float velocity);
  30438. /** Triggers a note-off event.
  30439. This will turn off any voices that are playing a sound for the given note/channel.
  30440. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  30441. (if they can do). If this is false, the notes will all be cut off immediately.
  30442. This method will be called automatically according to the midi data passed into
  30443. renderNextBlock(), but may be called explicitly too.
  30444. */
  30445. virtual void noteOff (const int midiChannel,
  30446. const int midiNoteNumber,
  30447. const bool allowTailOff);
  30448. /** Turns off all notes.
  30449. This will turn off any voices that are playing a sound on the given midi channel.
  30450. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  30451. which channel they're playing.
  30452. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  30453. (if they can do). If this is false, the notes will all be cut off immediately.
  30454. This method will be called automatically according to the midi data passed into
  30455. renderNextBlock(), but may be called explicitly too.
  30456. */
  30457. virtual void allNotesOff (const int midiChannel,
  30458. const bool allowTailOff);
  30459. /** Sends a pitch-wheel message.
  30460. This will send a pitch-wheel message to any voices that are playing sounds on
  30461. the given midi channel.
  30462. This method will be called automatically according to the midi data passed into
  30463. renderNextBlock(), but may be called explicitly too.
  30464. @param midiChannel the midi channel for the event
  30465. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  30466. */
  30467. virtual void handlePitchWheel (const int midiChannel,
  30468. const int wheelValue);
  30469. /** Sends a midi controller message.
  30470. This will send a midi controller message to any voices that are playing sounds on
  30471. the given midi channel.
  30472. This method will be called automatically according to the midi data passed into
  30473. renderNextBlock(), but may be called explicitly too.
  30474. @param midiChannel the midi channel for the event
  30475. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  30476. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  30477. */
  30478. virtual void handleController (const int midiChannel,
  30479. const int controllerNumber,
  30480. const int controllerValue);
  30481. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  30482. render.
  30483. This value is propagated to the voices so that they can use it to render the correct
  30484. pitches.
  30485. */
  30486. void setCurrentPlaybackSampleRate (const double sampleRate);
  30487. /** Creates the next block of audio output.
  30488. This will process the next numSamples of data from all the voices, and add that output
  30489. to the audio block supplied, starting from the offset specified. Note that the
  30490. data will be added to the current contents of the buffer, so you should clear it
  30491. before calling this method if necessary.
  30492. The midi events in the inputMidi buffer are parsed for note and controller events,
  30493. and these are used to trigger the voices. Note that the startSample offset applies
  30494. both to the audio output buffer and the midi input buffer, so any midi events
  30495. with timestamps outside the specified region will be ignored.
  30496. */
  30497. void renderNextBlock (AudioSampleBuffer& outputAudio,
  30498. const MidiBuffer& inputMidi,
  30499. int startSample,
  30500. int numSamples);
  30501. juce_UseDebuggingNewOperator
  30502. protected:
  30503. /** This is used to control access to the rendering callback and the note trigger methods. */
  30504. CriticalSection lock;
  30505. OwnedArray <SynthesiserVoice> voices;
  30506. ReferenceCountedArray <SynthesiserSound> sounds;
  30507. /** The last pitch-wheel values for each midi channel. */
  30508. int lastPitchWheelValues [16];
  30509. /** Searches through the voices to find one that's not currently playing, and which
  30510. can play the given sound.
  30511. Returns 0 if all voices are busy and stealing isn't enabled.
  30512. This can be overridden to implement custom voice-stealing algorithms.
  30513. */
  30514. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  30515. const bool stealIfNoneAvailable) const;
  30516. /** Starts a specified voice playing a particular sound.
  30517. You'll probably never need to call this, it's used internally by noteOn(), but
  30518. may be needed by subclasses for custom behaviours.
  30519. */
  30520. void startVoice (SynthesiserVoice* voice,
  30521. SynthesiserSound* sound,
  30522. int midiChannel,
  30523. int midiNoteNumber,
  30524. float velocity);
  30525. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  30526. int findFreeVoice (const bool) const { return 0; }
  30527. private:
  30528. double sampleRate;
  30529. uint32 lastNoteOnCounter;
  30530. bool shouldStealNotes;
  30531. Synthesiser (const Synthesiser&);
  30532. Synthesiser& operator= (const Synthesiser&);
  30533. };
  30534. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  30535. /*** End of inlined file: juce_Synthesiser.h ***/
  30536. /**
  30537. A subclass of SynthesiserSound that represents a sampled audio clip.
  30538. This is a pretty basic sampler, and just attempts to load the whole audio stream
  30539. into memory.
  30540. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  30541. give it some SampledSound objects to play.
  30542. @see SamplerVoice, Synthesiser, SynthesiserSound
  30543. */
  30544. class JUCE_API SamplerSound : public SynthesiserSound
  30545. {
  30546. public:
  30547. /** Creates a sampled sound from an audio reader.
  30548. This will attempt to load the audio from the source into memory and store
  30549. it in this object.
  30550. @param name a name for the sample
  30551. @param source the audio to load. This object can be safely deleted by the
  30552. caller after this constructor returns
  30553. @param midiNotes the set of midi keys that this sound should be played on. This
  30554. is used by the SynthesiserSound::appliesToNote() method
  30555. @param midiNoteForNormalPitch the midi note at which the sample should be played
  30556. with its natural rate. All other notes will be pitched
  30557. up or down relative to this one
  30558. @param attackTimeSecs the attack (fade-in) time, in seconds
  30559. @param releaseTimeSecs the decay (fade-out) time, in seconds
  30560. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  30561. source, in seconds
  30562. */
  30563. SamplerSound (const String& name,
  30564. AudioFormatReader& source,
  30565. const BigInteger& midiNotes,
  30566. int midiNoteForNormalPitch,
  30567. double attackTimeSecs,
  30568. double releaseTimeSecs,
  30569. double maxSampleLengthSeconds);
  30570. /** Destructor. */
  30571. ~SamplerSound();
  30572. /** Returns the sample's name */
  30573. const String& getName() const { return name; }
  30574. /** Returns the audio sample data.
  30575. This could be 0 if there was a problem loading it.
  30576. */
  30577. AudioSampleBuffer* getAudioData() const { return data; }
  30578. bool appliesToNote (const int midiNoteNumber);
  30579. bool appliesToChannel (const int midiChannel);
  30580. juce_UseDebuggingNewOperator
  30581. private:
  30582. friend class SamplerVoice;
  30583. String name;
  30584. ScopedPointer <AudioSampleBuffer> data;
  30585. double sourceSampleRate;
  30586. BigInteger midiNotes;
  30587. int length, attackSamples, releaseSamples;
  30588. int midiRootNote;
  30589. };
  30590. /**
  30591. A subclass of SynthesiserVoice that can play a SamplerSound.
  30592. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  30593. give it some SampledSound objects to play.
  30594. @see SamplerSound, Synthesiser, SynthesiserVoice
  30595. */
  30596. class JUCE_API SamplerVoice : public SynthesiserVoice
  30597. {
  30598. public:
  30599. /** Creates a SamplerVoice.
  30600. */
  30601. SamplerVoice();
  30602. /** Destructor. */
  30603. ~SamplerVoice();
  30604. bool canPlaySound (SynthesiserSound* sound);
  30605. void startNote (const int midiNoteNumber,
  30606. const float velocity,
  30607. SynthesiserSound* sound,
  30608. const int currentPitchWheelPosition);
  30609. void stopNote (const bool allowTailOff);
  30610. void pitchWheelMoved (const int newValue);
  30611. void controllerMoved (const int controllerNumber,
  30612. const int newValue);
  30613. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  30614. juce_UseDebuggingNewOperator
  30615. private:
  30616. double pitchRatio;
  30617. double sourceSamplePosition;
  30618. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  30619. bool isInAttack, isInRelease;
  30620. };
  30621. #endif // __JUCE_SAMPLER_JUCEHEADER__
  30622. /*** End of inlined file: juce_Sampler.h ***/
  30623. #endif
  30624. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  30625. #endif
  30626. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  30627. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  30628. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  30629. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  30630. /*** Start of inlined file: juce_ActionListenerList.h ***/
  30631. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  30632. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  30633. /**
  30634. A set of ActionListeners.
  30635. Listeners can be added and removed from the list, and messages can be
  30636. broadcast to all the listeners.
  30637. @see ActionListener, ActionBroadcaster
  30638. */
  30639. class JUCE_API ActionListenerList : public MessageListener
  30640. {
  30641. public:
  30642. /** Creates an empty list. */
  30643. ActionListenerList() throw();
  30644. /** Destructor. */
  30645. ~ActionListenerList() throw();
  30646. /** Adds a listener to the list.
  30647. (Trying to add a listener that's already on the list will have no effect).
  30648. */
  30649. void addActionListener (ActionListener* listener) throw();
  30650. /** Removes a listener from the list.
  30651. If the listener isn't on the list, this won't have any effect.
  30652. */
  30653. void removeActionListener (ActionListener* listener) throw();
  30654. /** Removes all listeners from the list. */
  30655. void removeAllActionListeners() throw();
  30656. /** Broadcasts a message to all the registered listeners.
  30657. This sends the message asynchronously.
  30658. If a listener is on the list when this method is called but is removed from
  30659. the list before the message arrives, it won't receive the message. Similarly
  30660. listeners that are added to the list after the message is sent but before it
  30661. arrives won't get the message either.
  30662. */
  30663. void sendActionMessage (const String& message) const;
  30664. /** @internal */
  30665. void handleMessage (const Message&);
  30666. juce_UseDebuggingNewOperator
  30667. private:
  30668. SortedSet <void*> actionListeners_;
  30669. CriticalSection actionListenerLock_;
  30670. ActionListenerList (const ActionListenerList&);
  30671. ActionListenerList& operator= (const ActionListenerList&);
  30672. };
  30673. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  30674. /*** End of inlined file: juce_ActionListenerList.h ***/
  30675. /** Manages a list of ActionListeners, and can send them messages.
  30676. To quickly add methods to your class that can add/remove action
  30677. listeners and broadcast to them, you can derive from this.
  30678. @see ActionListenerList, ActionListener
  30679. */
  30680. class JUCE_API ActionBroadcaster
  30681. {
  30682. public:
  30683. /** Creates an ActionBroadcaster. */
  30684. ActionBroadcaster() throw();
  30685. /** Destructor. */
  30686. virtual ~ActionBroadcaster();
  30687. /** Adds a listener to the list.
  30688. (Trying to add a listener that's already on the list will have no effect).
  30689. */
  30690. void addActionListener (ActionListener* listener);
  30691. /** Removes a listener from the list.
  30692. If the listener isn't on the list, this won't have any effect.
  30693. */
  30694. void removeActionListener (ActionListener* listener);
  30695. /** Removes all listeners from the list. */
  30696. void removeAllActionListeners();
  30697. /** Broadcasts a message to all the registered listeners.
  30698. @see ActionListenerList::sendActionMessage
  30699. */
  30700. void sendActionMessage (const String& message) const;
  30701. private:
  30702. ActionListenerList actionListenerList;
  30703. ActionBroadcaster (const ActionBroadcaster&);
  30704. ActionBroadcaster& operator= (const ActionBroadcaster&);
  30705. };
  30706. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  30707. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  30708. #endif
  30709. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  30710. #endif
  30711. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  30712. #endif
  30713. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  30714. #endif
  30715. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  30716. /*** Start of inlined file: juce_CallbackMessage.h ***/
  30717. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  30718. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  30719. /**
  30720. A message that calls a custom function when it gets delivered.
  30721. You can use this class to fire off actions that you want to be performed later
  30722. on the message thread.
  30723. Unlike other Message objects, these don't get sent to a MessageListener, you
  30724. just call the post() method to send them, and when they arrive, your
  30725. messageCallback() method will automatically be invoked.
  30726. @see MessageListener, MessageManager, ActionListener, ChangeListener
  30727. */
  30728. class JUCE_API CallbackMessage : public Message
  30729. {
  30730. public:
  30731. CallbackMessage() throw();
  30732. /** Destructor. */
  30733. ~CallbackMessage() throw();
  30734. /** Called when the message is delivered.
  30735. You should implement this method and make it do whatever action you want
  30736. to perform.
  30737. Note that like all other messages, this object will be deleted immediately
  30738. after this method has been invoked.
  30739. */
  30740. virtual void messageCallback() = 0;
  30741. /** Instead of sending this message to a MessageListener, just call this method
  30742. to post it to the event queue.
  30743. After you've called this, this object will belong to the MessageManager,
  30744. which will delete it later. So make sure you don't delete the object yourself,
  30745. call post() more than once, or call post() on a stack-based obect!
  30746. */
  30747. void post();
  30748. juce_UseDebuggingNewOperator
  30749. private:
  30750. CallbackMessage (const CallbackMessage&);
  30751. CallbackMessage& operator= (const CallbackMessage&);
  30752. };
  30753. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  30754. /*** End of inlined file: juce_CallbackMessage.h ***/
  30755. #endif
  30756. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  30757. #endif
  30758. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  30759. #endif
  30760. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  30761. #endif
  30762. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  30763. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  30764. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  30765. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  30766. class InterprocessConnectionServer;
  30767. /**
  30768. Manages a simple two-way messaging connection to another process, using either
  30769. a socket or a named pipe as the transport medium.
  30770. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  30771. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  30772. and incoming messages will result in a callback via the messageReceived()
  30773. method.
  30774. To open a pipe and wait for another client to connect to it, use the createPipe()
  30775. method.
  30776. To act as a socket server and create connections for one or more client, see the
  30777. InterprocessConnectionServer class.
  30778. @see InterprocessConnectionServer, Socket, NamedPipe
  30779. */
  30780. class JUCE_API InterprocessConnection : public Thread,
  30781. private MessageListener
  30782. {
  30783. public:
  30784. /** Creates a connection.
  30785. Connections are created manually, connecting them with the connectToSocket()
  30786. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  30787. when a client wants to connect.
  30788. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  30789. connectionLost() and messageReceived() methods will
  30790. always be made using the message thread; if false,
  30791. these will be called immediately on the connection's
  30792. own thread.
  30793. @param magicMessageHeaderNumber a magic number to use in the header to check the
  30794. validity of the data blocks being sent and received. This
  30795. can be any number, but the sender and receiver must obviously
  30796. use matching values or they won't recognise each other.
  30797. */
  30798. InterprocessConnection (bool callbacksOnMessageThread = true,
  30799. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  30800. /** Destructor. */
  30801. ~InterprocessConnection();
  30802. /** Tries to connect this object to a socket.
  30803. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  30804. object waiting to receive client connections on this port number.
  30805. @param hostName the host computer, either a network address or name
  30806. @param portNumber the socket port number to try to connect to
  30807. @param timeOutMillisecs how long to keep trying before giving up
  30808. @returns true if the connection is established successfully
  30809. @see Socket
  30810. */
  30811. bool connectToSocket (const String& hostName,
  30812. int portNumber,
  30813. int timeOutMillisecs);
  30814. /** Tries to connect the object to an existing named pipe.
  30815. For this to work, another process on the same computer must already have opened
  30816. an InterprocessConnection object and used createPipe() to create a pipe for this
  30817. to connect to.
  30818. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  30819. @returns true if it connects successfully.
  30820. @see createPipe, NamedPipe
  30821. */
  30822. bool connectToPipe (const String& pipeName,
  30823. int pipeReceiveMessageTimeoutMs = -1);
  30824. /** Tries to create a new pipe for other processes to connect to.
  30825. This creates a pipe with the given name, so that other processes can use
  30826. connectToPipe() to connect to the other end.
  30827. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  30828. If another process is already using this pipe, this will fail and return false.
  30829. */
  30830. bool createPipe (const String& pipeName,
  30831. int pipeReceiveMessageTimeoutMs = -1);
  30832. /** Disconnects and closes any currently-open sockets or pipes. */
  30833. void disconnect();
  30834. /** True if a socket or pipe is currently active. */
  30835. bool isConnected() const;
  30836. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  30837. StreamingSocket* getSocket() const throw() { return socket; }
  30838. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  30839. NamedPipe* getPipe() const throw() { return pipe; }
  30840. /** Returns the name of the machine at the other end of this connection.
  30841. This will return an empty string if the other machine isn't known for
  30842. some reason.
  30843. */
  30844. const String getConnectedHostName() const;
  30845. /** Tries to send a message to the other end of this connection.
  30846. This will fail if it's not connected, or if there's some kind of write error. If
  30847. it succeeds, the connection object at the other end will receive the message by
  30848. a callback to its messageReceived() method.
  30849. @see messageReceived
  30850. */
  30851. bool sendMessage (const MemoryBlock& message);
  30852. /** Called when the connection is first connected.
  30853. If the connection was created with the callbacksOnMessageThread flag set, then
  30854. this will be called on the message thread; otherwise it will be called on a server
  30855. thread.
  30856. */
  30857. virtual void connectionMade() = 0;
  30858. /** Called when the connection is broken.
  30859. If the connection was created with the callbacksOnMessageThread flag set, then
  30860. this will be called on the message thread; otherwise it will be called on a server
  30861. thread.
  30862. */
  30863. virtual void connectionLost() = 0;
  30864. /** Called when a message arrives.
  30865. When the object at the other end of this connection sends us a message with sendMessage(),
  30866. this callback is used to deliver it to us.
  30867. If the connection was created with the callbacksOnMessageThread flag set, then
  30868. this will be called on the message thread; otherwise it will be called on a server
  30869. thread.
  30870. @see sendMessage
  30871. */
  30872. virtual void messageReceived (const MemoryBlock& message) = 0;
  30873. juce_UseDebuggingNewOperator
  30874. private:
  30875. CriticalSection pipeAndSocketLock;
  30876. ScopedPointer <StreamingSocket> socket;
  30877. ScopedPointer <NamedPipe> pipe;
  30878. bool callbackConnectionState;
  30879. const bool useMessageThread;
  30880. const uint32 magicMessageHeader;
  30881. int pipeReceiveMessageTimeout;
  30882. friend class InterprocessConnectionServer;
  30883. void initialiseWithSocket (StreamingSocket* socket_);
  30884. void initialiseWithPipe (NamedPipe* pipe_);
  30885. void handleMessage (const Message& message);
  30886. void connectionMadeInt();
  30887. void connectionLostInt();
  30888. void deliverDataInt (const MemoryBlock& data);
  30889. bool readNextMessageInt();
  30890. void run();
  30891. InterprocessConnection (const InterprocessConnection&);
  30892. InterprocessConnection& operator= (const InterprocessConnection&);
  30893. };
  30894. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  30895. /*** End of inlined file: juce_InterprocessConnection.h ***/
  30896. #endif
  30897. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  30898. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  30899. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  30900. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  30901. /**
  30902. An object that waits for client sockets to connect to a port on this host, and
  30903. creates InterprocessConnection objects for each one.
  30904. To use this, create a class derived from it which implements the createConnectionObject()
  30905. method, so that it creates suitable connection objects for each client that tries
  30906. to connect.
  30907. @see InterprocessConnection
  30908. */
  30909. class JUCE_API InterprocessConnectionServer : private Thread
  30910. {
  30911. public:
  30912. /** Creates an uninitialised server object.
  30913. */
  30914. InterprocessConnectionServer();
  30915. /** Destructor. */
  30916. ~InterprocessConnectionServer();
  30917. /** Starts an internal thread which listens on the given port number.
  30918. While this is running, in another process tries to connect with the
  30919. InterprocessConnection::connectToSocket() method, this object will call
  30920. createConnectionObject() to create a connection to that client.
  30921. Use stop() to stop the thread running.
  30922. @see createConnectionObject, stop
  30923. */
  30924. bool beginWaitingForSocket (int portNumber);
  30925. /** Terminates the listener thread, if it's active.
  30926. @see beginWaitingForSocket
  30927. */
  30928. void stop();
  30929. protected:
  30930. /** Creates a suitable connection object for a client process that wants to
  30931. connect to this one.
  30932. This will be called by the listener thread when a client process tries
  30933. to connect, and must return a new InterprocessConnection object that will
  30934. then run as this end of the connection.
  30935. @see InterprocessConnection
  30936. */
  30937. virtual InterprocessConnection* createConnectionObject() = 0;
  30938. public:
  30939. juce_UseDebuggingNewOperator
  30940. private:
  30941. ScopedPointer <StreamingSocket> socket;
  30942. void run();
  30943. InterprocessConnectionServer (const InterprocessConnectionServer&);
  30944. InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  30945. };
  30946. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  30947. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  30948. #endif
  30949. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  30950. #endif
  30951. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  30952. #endif
  30953. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  30954. #endif
  30955. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  30956. /*** Start of inlined file: juce_MessageManager.h ***/
  30957. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  30958. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  30959. class Component;
  30960. class MessageManagerLock;
  30961. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  30962. */
  30963. typedef void* (MessageCallbackFunction) (void* userData);
  30964. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  30965. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  30966. */
  30967. class JUCE_API MessageManager
  30968. {
  30969. public:
  30970. /** Returns the global instance of the MessageManager. */
  30971. static MessageManager* getInstance() throw();
  30972. /** Runs the event dispatch loop until a stop message is posted.
  30973. This method is only intended to be run by the application's startup routine,
  30974. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  30975. @see stopDispatchLoop
  30976. */
  30977. void runDispatchLoop();
  30978. /** Sends a signal that the dispatch loop should terminate.
  30979. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  30980. will be interrupted and will return.
  30981. @see runDispatchLoop
  30982. */
  30983. void stopDispatchLoop();
  30984. /** Returns true if the stopDispatchLoop() method has been called.
  30985. */
  30986. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  30987. /** Synchronously dispatches messages until a given time has elapsed.
  30988. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  30989. otherwise returns true.
  30990. */
  30991. bool runDispatchLoopUntil (int millisecondsToRunFor);
  30992. /** Calls a function using the message-thread.
  30993. This can be used by any thread to cause this function to be called-back
  30994. by the message thread. If it's the message-thread that's calling this method,
  30995. then the function will just be called; if another thread is calling, a message
  30996. will be posted to the queue, and this method will block until that message
  30997. is delivered, the function is called, and the result is returned.
  30998. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  30999. thread has a critical section locked, which an unrelated message callback then tries to lock
  31000. before the message thread gets round to processing this callback.
  31001. @param callback the function to call - its signature must be @code
  31002. void* myCallbackFunction (void*) @endcode
  31003. @param userData a user-defined pointer that will be passed to the function that gets called
  31004. @returns the value that the callback function returns.
  31005. @see MessageManagerLock
  31006. */
  31007. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  31008. void* userData);
  31009. /** Returns true if the caller-thread is the message thread. */
  31010. bool isThisTheMessageThread() const throw();
  31011. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  31012. (Best to ignore this method unless you really know what you're doing..)
  31013. @see getCurrentMessageThread
  31014. */
  31015. void setCurrentThreadAsMessageThread();
  31016. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  31017. (Best to ignore this method unless you really know what you're doing..)
  31018. @see setCurrentMessageThread
  31019. */
  31020. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  31021. /** Returns true if the caller thread has currenltly got the message manager locked.
  31022. see the MessageManagerLock class for more info about this.
  31023. This will be true if the caller is the message thread, because that automatically
  31024. gains a lock while a message is being dispatched.
  31025. */
  31026. bool currentThreadHasLockedMessageManager() const throw();
  31027. /** Sends a message to all other JUCE applications that are running.
  31028. @param messageText the string that will be passed to the actionListenerCallback()
  31029. method of the broadcast listeners in the other app.
  31030. @see registerBroadcastListener, ActionListener
  31031. */
  31032. static void broadcastMessage (const String& messageText) throw();
  31033. /** Registers a listener to get told about broadcast messages.
  31034. The actionListenerCallback() callback's string parameter
  31035. is the message passed into broadcastMessage().
  31036. @see broadcastMessage
  31037. */
  31038. void registerBroadcastListener (ActionListener* listener) throw();
  31039. /** Deregisters a broadcast listener. */
  31040. void deregisterBroadcastListener (ActionListener* listener) throw();
  31041. /** @internal */
  31042. void deliverMessage (void*);
  31043. /** @internal */
  31044. void deliverBroadcastMessage (const String&);
  31045. /** @internal */
  31046. ~MessageManager() throw();
  31047. juce_UseDebuggingNewOperator
  31048. private:
  31049. MessageManager() throw();
  31050. friend class MessageListener;
  31051. friend class ChangeBroadcaster;
  31052. friend class ActionBroadcaster;
  31053. friend class CallbackMessage;
  31054. static MessageManager* instance;
  31055. SortedSet <const MessageListener*> messageListeners;
  31056. ScopedPointer <ActionListenerList> broadcastListeners;
  31057. friend class JUCEApplication;
  31058. bool quitMessagePosted, quitMessageReceived;
  31059. Thread::ThreadID messageThreadId;
  31060. static void* exitModalLoopCallback (void*);
  31061. void postMessageToQueue (Message* message);
  31062. void postCallbackMessage (Message* message);
  31063. static void doPlatformSpecificInitialisation();
  31064. static void doPlatformSpecificShutdown();
  31065. friend class MessageManagerLock;
  31066. Thread::ThreadID volatile threadWithLock;
  31067. CriticalSection lockingLock;
  31068. MessageManager (const MessageManager&);
  31069. MessageManager& operator= (const MessageManager&);
  31070. };
  31071. /** Used to make sure that the calling thread has exclusive access to the message loop.
  31072. Because it's not thread-safe to call any of the Component or other UI classes
  31073. from threads other than the message thread, one of these objects can be used to
  31074. lock the message loop and allow this to be done. The message thread will be
  31075. suspended for the lifetime of the MessageManagerLock object, so create one on
  31076. the stack like this: @code
  31077. void MyThread::run()
  31078. {
  31079. someData = 1234;
  31080. const MessageManagerLock mmLock;
  31081. // the event loop will now be locked so it's safe to make a few calls..
  31082. myComponent->setBounds (newBounds);
  31083. myComponent->repaint();
  31084. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  31085. }
  31086. @endcode
  31087. Obviously be careful not to create one of these and leave it lying around, or
  31088. your app will grind to a halt!
  31089. Another caveat is that using this in conjunction with other CriticalSections
  31090. can create lots of interesting ways of producing a deadlock! In particular, if
  31091. your message thread calls stopThread() for a thread that uses these locks,
  31092. you'll get an (occasional) deadlock..
  31093. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  31094. */
  31095. class JUCE_API MessageManagerLock
  31096. {
  31097. public:
  31098. /** Tries to acquire a lock on the message manager.
  31099. The constructor attempts to gain a lock on the message loop, and the lock will be
  31100. kept for the lifetime of this object.
  31101. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  31102. this method will keep checking whether the thread has been given the
  31103. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  31104. without gaining the lock. If you pass a thread, you must check whether the lock was
  31105. successful by calling lockWasGained(). If this is false, your thread is being told to
  31106. die, so you should take evasive action.
  31107. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  31108. careful when doing this, because it's very easy to deadlock if your message thread
  31109. attempts to call stopThread() on a thread just as that thread attempts to get the
  31110. message lock.
  31111. If the calling thread already has the lock, nothing will be done, so it's safe and
  31112. quick to use these locks recursively.
  31113. E.g.
  31114. @code
  31115. void run()
  31116. {
  31117. ...
  31118. while (! threadShouldExit())
  31119. {
  31120. MessageManagerLock mml (Thread::getCurrentThread());
  31121. if (! mml.lockWasGained())
  31122. return; // another thread is trying to kill us!
  31123. ..do some locked stuff here..
  31124. }
  31125. ..and now the MM is now unlocked..
  31126. }
  31127. @endcode
  31128. */
  31129. MessageManagerLock (Thread* threadToCheckForExitSignal = 0) throw();
  31130. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  31131. instead of a thread.
  31132. See the MessageManagerLock (Thread*) constructor for details on how this works.
  31133. */
  31134. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal) throw();
  31135. /** Releases the current thread's lock on the message manager.
  31136. Make sure this object is created and deleted by the same thread,
  31137. otherwise there are no guarantees what will happen!
  31138. */
  31139. ~MessageManagerLock() throw();
  31140. /** Returns true if the lock was successfully acquired.
  31141. (See the constructor that takes a Thread for more info).
  31142. */
  31143. bool lockWasGained() const throw() { return locked; }
  31144. private:
  31145. class SharedEvents;
  31146. class BlockingMessage;
  31147. friend class SharedEvents;
  31148. friend class BlockingMessage;
  31149. SharedEvents* sharedEvents;
  31150. bool locked;
  31151. void init (Thread* thread, ThreadPoolJob* job) throw();
  31152. MessageManagerLock (const MessageManagerLock&);
  31153. MessageManagerLock& operator= (const MessageManagerLock&);
  31154. };
  31155. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31156. /*** End of inlined file: juce_MessageManager.h ***/
  31157. #endif
  31158. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31159. /*** Start of inlined file: juce_MultiTimer.h ***/
  31160. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31161. #define __JUCE_MULTITIMER_JUCEHEADER__
  31162. /**
  31163. A type of timer class that can run multiple timers with different frequencies,
  31164. all of which share a single callback.
  31165. This class is very similar to the Timer class, but allows you run multiple
  31166. separate timers, where each one has a unique ID number. The methods in this
  31167. class are exactly equivalent to those in Timer, but with the addition of
  31168. this ID number.
  31169. To use it, you need to create a subclass of MultiTimer, implementing the
  31170. timerCallback() method. Then you can start timers with startTimer(), and
  31171. each time the callback is triggered, it passes in the ID of the timer that
  31172. caused it.
  31173. @see Timer
  31174. */
  31175. class JUCE_API MultiTimer
  31176. {
  31177. protected:
  31178. /** Creates a MultiTimer.
  31179. When created, no timers are running, so use startTimer() to start things off.
  31180. */
  31181. MultiTimer() throw();
  31182. /** Creates a copy of another timer.
  31183. Note that this timer will not contain any running timers, even if the one you're
  31184. copying from was running.
  31185. */
  31186. MultiTimer (const MultiTimer& other) throw();
  31187. public:
  31188. /** Destructor. */
  31189. virtual ~MultiTimer();
  31190. /** The user-defined callback routine that actually gets called by each of the
  31191. timers that are running.
  31192. It's perfectly ok to call startTimer() or stopTimer() from within this
  31193. callback to change the subsequent intervals.
  31194. */
  31195. virtual void timerCallback (int timerId) = 0;
  31196. /** Starts a timer and sets the length of interval required.
  31197. If the timer is already started, this will reset it, so the
  31198. time between calling this method and the next timer callback
  31199. will not be less than the interval length passed in.
  31200. @param timerId a unique Id number that identifies the timer to
  31201. start. This is the id that will be passed back
  31202. to the timerCallback() method when this timer is
  31203. triggered
  31204. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  31205. rounded up to 1)
  31206. */
  31207. void startTimer (int timerId, int intervalInMilliseconds) throw();
  31208. /** Stops a timer.
  31209. If a timer has been started with the given ID number, it will be cancelled.
  31210. No more callbacks will be made for the specified timer after this method returns.
  31211. If this is called from a different thread, any callbacks that may
  31212. be currently executing may be allowed to finish before the method
  31213. returns.
  31214. */
  31215. void stopTimer (int timerId) throw();
  31216. /** Checks whether a timer has been started for a specified ID.
  31217. @returns true if a timer with the given ID is running.
  31218. */
  31219. bool isTimerRunning (int timerId) const throw();
  31220. /** Returns the interval for a specified timer ID.
  31221. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  31222. is running for the ID number specified.
  31223. */
  31224. int getTimerInterval (int timerId) const throw();
  31225. private:
  31226. class MultiTimerCallback;
  31227. CriticalSection timerListLock;
  31228. OwnedArray <MultiTimerCallback> timers;
  31229. MultiTimer& operator= (const MultiTimer&);
  31230. };
  31231. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  31232. /*** End of inlined file: juce_MultiTimer.h ***/
  31233. #endif
  31234. #ifndef __JUCE_TIMER_JUCEHEADER__
  31235. #endif
  31236. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31237. /*** Start of inlined file: juce_ArrowButton.h ***/
  31238. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31239. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31240. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  31241. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31242. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31243. /**
  31244. An effect filter that adds a drop-shadow behind the image's content.
  31245. (This will only work on images/components that aren't opaque, of course).
  31246. When added to a component, this effect will draw a soft-edged
  31247. shadow based on what gets drawn inside it. The shadow will also
  31248. be applied to the component's children.
  31249. For speed, this doesn't use a proper gaussian blur, but cheats by
  31250. using a simple bilinear filter. If you need a really high-quality
  31251. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31252. @see Component::setComponentEffect
  31253. */
  31254. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31255. {
  31256. public:
  31257. /** Creates a default drop-shadow effect.
  31258. To customise the shadow's appearance, use the setShadowProperties()
  31259. method.
  31260. */
  31261. DropShadowEffect();
  31262. /** Destructor. */
  31263. ~DropShadowEffect();
  31264. /** Sets up parameters affecting the shadow's appearance.
  31265. @param newRadius the (approximate) radius of the blur used
  31266. @param newOpacity the opacity with which the shadow is rendered
  31267. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  31268. component's contents
  31269. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  31270. component's contents
  31271. */
  31272. void setShadowProperties (float newRadius,
  31273. float newOpacity,
  31274. int newShadowOffsetX,
  31275. int newShadowOffsetY);
  31276. /** @internal */
  31277. void applyEffect (Image& sourceImage, Graphics& destContext);
  31278. juce_UseDebuggingNewOperator
  31279. private:
  31280. int offsetX, offsetY;
  31281. float radius, opacity;
  31282. };
  31283. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31284. /*** End of inlined file: juce_DropShadowEffect.h ***/
  31285. /**
  31286. A button with an arrow in it.
  31287. @see Button
  31288. */
  31289. class JUCE_API ArrowButton : public Button
  31290. {
  31291. public:
  31292. /** Creates an ArrowButton.
  31293. @param buttonName the name to give the button
  31294. @param arrowDirection the direction the arrow should point in, where 0.0 is
  31295. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  31296. @param arrowColour the colour to use for the arrow
  31297. */
  31298. ArrowButton (const String& buttonName,
  31299. float arrowDirection,
  31300. const Colour& arrowColour);
  31301. /** Destructor. */
  31302. ~ArrowButton();
  31303. juce_UseDebuggingNewOperator
  31304. protected:
  31305. /** @internal */
  31306. void paintButton (Graphics& g,
  31307. bool isMouseOverButton,
  31308. bool isButtonDown);
  31309. /** @internal */
  31310. void buttonStateChanged();
  31311. private:
  31312. Colour colour;
  31313. DropShadowEffect shadow;
  31314. Path path;
  31315. int offset;
  31316. ArrowButton (const ArrowButton&);
  31317. ArrowButton& operator= (const ArrowButton&);
  31318. };
  31319. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  31320. /*** End of inlined file: juce_ArrowButton.h ***/
  31321. #endif
  31322. #ifndef __JUCE_BUTTON_JUCEHEADER__
  31323. #endif
  31324. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31325. /*** Start of inlined file: juce_DrawableButton.h ***/
  31326. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31327. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31328. /*** Start of inlined file: juce_Drawable.h ***/
  31329. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  31330. #define __JUCE_DRAWABLE_JUCEHEADER__
  31331. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  31332. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  31333. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  31334. /**
  31335. Expresses a coordinate as an absolute or proportional distance from other
  31336. named coordinates.
  31337. A RelativeCoordinate represents a position as either:
  31338. - an absolute distance from the origin
  31339. - an absolute distance from another named RelativeCoordinate
  31340. - a proportion of the distance between two other named RelativeCoordinates
  31341. Of course, the coordinates that this one is relative to may themselves be relative
  31342. to other coordinates, so complex arrangements can be built up (as long as you're careful
  31343. not to create recursive loops!)
  31344. Rather than keeping pointers to the coordinates that this one is dependent on, it
  31345. stores their names, and when resolving this coordinate to an absolute value, a
  31346. NamedCoordinateFinder class is required to retrieve these coordinates by name.
  31347. @see RelativePoint, RelativeRectangle
  31348. */
  31349. class JUCE_API RelativeCoordinate
  31350. {
  31351. public:
  31352. /** Creates a zero coordinate. */
  31353. RelativeCoordinate();
  31354. /** Creates an absolute position from the parent origin on either the X or Y axis.
  31355. @param absoluteDistanceFromOrigin the distance from the origin
  31356. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  31357. */
  31358. RelativeCoordinate (double absoluteDistanceFromOrigin, bool isHorizontal);
  31359. /** Creates an absolute position relative to a named coordinate.
  31360. @param absoluteDistanceFromAnchor the distance to add to the named anchor point
  31361. @param anchorPoint the name of the coordinate from which this one will be relative. See the constructor
  31362. notes for a description of the syntax for coordinate names.
  31363. */
  31364. RelativeCoordinate (double absoluteDistanceFromAnchor, const String& anchorPoint);
  31365. /** Creates a relative position between two named points.
  31366. @param relativeProportionBetweenAnchors a value between 0 and 1 indicating this coordinate's relative position
  31367. between anchorPoint1 and anchorPoint2.
  31368. @param anchorPoint1 the name of the first coordinate from which this one will be relative. See the constructor
  31369. notes for a description of the syntax for coordinate names.
  31370. @param anchorPoint2 the name of the first coordinate from which this one will be relative. See the constructor
  31371. notes for a description of the syntax for coordinate names.
  31372. */
  31373. RelativeCoordinate (double relativeProportionBetweenAnchors, const String& anchorPoint1, const String& anchorPoint2);
  31374. /** Recreates a coordinate from a string description.
  31375. The string can be in one of the following formats:
  31376. - "123" = 123 pixels from parent origin (this is equivalent to "parent.left + 123"
  31377. or "parent.top + 123", depending on which axis the coordinate is using)
  31378. - "anchor" = the same position as the coordinate named "anchor"
  31379. - "anchor + 123" = the coordinate named "anchor" + 123 pixels
  31380. - "anchor - 123" = the coordinate named "anchor" - 123 pixels
  31381. - "50%" = 50% of the distance between the coordinate space's top-left origin and its extent
  31382. (this is equivalent to "50% * parent.left -> parent.right" or "50% * parent.top -> parent.bottom")
  31383. - "50% * anchor" = 50% of the distance between the coordinate space's origin and the coordinate named "anchor"
  31384. (this is equivalent to "50% * parent.left -> anchor" or "50% * parent.top -> anchor")
  31385. - "50% * anchor1 -> anchor2" = 50% of the distance between the coordinate "anchor1" and the coordinate "anchor2"
  31386. An anchor name can either be just a single identifier (letters, digits and underscores only - no spaces),
  31387. e.g. "marker1", or it can be a two-part name in the form "objectName.edge". For example "parent.left" is
  31388. the origin, or "myComponent.top" is the top edge of a component called "myComponent". The exact names that
  31389. will be recognised are dependent on the NamedCoordinateFinder that you provide for looking them up, but
  31390. "parent.left" and "parent.top" are always available, meaning the origin. "parent.right" and "parent.bottom"
  31391. may also be available if the coordinate space has a fixed size.
  31392. @param stringVersion the string to parse
  31393. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  31394. @see toString
  31395. */
  31396. RelativeCoordinate (const String& stringVersion, bool isHorizontal);
  31397. /** Destructor. */
  31398. ~RelativeCoordinate();
  31399. bool operator== (const RelativeCoordinate& other) const throw();
  31400. bool operator!= (const RelativeCoordinate& other) const throw();
  31401. /**
  31402. Provides an interface for looking up the position of a named anchor when resolving a RelativeCoordinate.
  31403. When using RelativeCoordinates, to resolve their names you need to provide a subclass of this which
  31404. can retrieve a coordinate by name.
  31405. */
  31406. class JUCE_API NamedCoordinateFinder
  31407. {
  31408. public:
  31409. /** Destructor. */
  31410. virtual ~NamedCoordinateFinder() {}
  31411. /** Returns the coordinate for a given name.
  31412. The objectName parameter will be the first section of the name, and the edge the name of the second part.
  31413. E.g. for "parent.right", objectName would be "parent" and edge would be "right". If the name
  31414. has no dot, the edge parameter will be an empty string.
  31415. This method must be able to resolve "parent.left", "parent.top", "parent.right" and "parent.bottom", as
  31416. well as any other objects that your application uses.
  31417. */
  31418. virtual const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const = 0;
  31419. };
  31420. /** Calculates the absolute position of this coordinate.
  31421. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31422. be needed to calculate the result.
  31423. */
  31424. double resolve (const NamedCoordinateFinder* nameFinder) const;
  31425. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  31426. This will recursively check any coordinates upon which this one depends.
  31427. */
  31428. bool references (const String& coordName, const NamedCoordinateFinder* nameFinder) const;
  31429. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  31430. bool isRecursive (const NamedCoordinateFinder* nameFinder) const;
  31431. /** Returns true if this coordinate depends on any other coordinates for its position. */
  31432. bool isDynamic() const;
  31433. /** Changes the value of this coord to make it resolve to the specified position.
  31434. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  31435. or relative position to whatever value is necessary to make its resultant position
  31436. match the position that is provided.
  31437. */
  31438. void moveToAbsolute (double absoluteTargetPosition, const NamedCoordinateFinder* nameFinder);
  31439. /** Returns true if the coordinate is calculated as a proportion of the distance between two other points.
  31440. @see toggleProportionality
  31441. */
  31442. bool isProportional() const throw() { return anchor2.isNotEmpty(); }
  31443. /** Toggles the coordinate between using a proportional or absolute position.
  31444. Note that calling this will reset the names of any anchor points, and just make the
  31445. coordinate relative to the parent origin and parent size.
  31446. */
  31447. void toggleProportionality (const NamedCoordinateFinder* nameFinder, bool isHorizontal);
  31448. /** Returns a value that can be edited to set this coordinate's position.
  31449. The meaning of this number depends on the coordinate's mode. If the coordinate is
  31450. proportional, the number will be a percentage between 0 and 100. If the
  31451. coordinate is absolute, then it will be the number of pixels from its anchor point.
  31452. @see setEditableNumber
  31453. */
  31454. const double getEditableNumber() const;
  31455. /** Sets the value that controls this coordinate's position.
  31456. The meaning of this number depends on the coordinate's mode. If the coordinate is
  31457. proportional, the number must be a percentage between 0 and 100. If the
  31458. coordinate is absolute, then it indicates the number of pixels from its anchor point.
  31459. @see setEditableNumber
  31460. */
  31461. void setEditableNumber (const double newValue);
  31462. /** Returns the name of the first anchor point from which this coordinate is relative.
  31463. */
  31464. const String getAnchorName1() const { return anchor1; }
  31465. /** Returns the name of the second anchor point from which this coordinate is relative.
  31466. The second anchor is only valid if the coordinate is in proportional mode.
  31467. */
  31468. const String getAnchorName2() const { return anchor2; }
  31469. /** Returns the first anchor point as a coordinate. */
  31470. const RelativeCoordinate getAnchorCoordinate1() const;
  31471. /** Returns the first anchor point as a coordinate.
  31472. The second anchor is only valid if the coordinate is in proportional mode.
  31473. */
  31474. const RelativeCoordinate getAnchorCoordinate2() const;
  31475. /** Changes the first anchor point, keeping the resultant position of this coordinate in
  31476. the same place it was previously.
  31477. */
  31478. void changeAnchor1 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  31479. /** Changes the second anchor point, keeping the resultant position of this coordinate in
  31480. the same place it was previously.
  31481. */
  31482. void changeAnchor2 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  31483. /** Tells the coordinate that an object is changing its name or being deleted.
  31484. If either of this coordinates anchor points match this name, they will be replaced.
  31485. If the newName string is empty, it indicates that the object is being removed, so if
  31486. this coordinate was using it, the coordinate is changed to be relative to the origin
  31487. instead.
  31488. */
  31489. void renameAnchorIfUsed (const String& oldName, const String& newName,
  31490. const NamedCoordinateFinder* nameFinder);
  31491. /** Returns a string which represents this coordinate.
  31492. For details of the string syntax, see the constructor notes.
  31493. */
  31494. const String toString() const;
  31495. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  31496. As well as avoiding using string literals in your code, using these preset values
  31497. has the advantage that all instances of the same string will share the same, reference-counted
  31498. String object, so if you have thousands of points which all refer to the same
  31499. anchor points, this can save a significant amount of memory allocation.
  31500. */
  31501. struct Strings
  31502. {
  31503. static const String parent; /**< "parent" */
  31504. static const String left; /**< "left" */
  31505. static const String right; /**< "right" */
  31506. static const String top; /**< "top" */
  31507. static const String bottom; /**< "bottom" */
  31508. static const String parentLeft; /**< "parent.left" */
  31509. static const String parentTop; /**< "parent.top" */
  31510. static const String parentRight; /**< "parent.right" */
  31511. static const String parentBottom; /**< "parent.bottom" */
  31512. };
  31513. private:
  31514. String anchor1, anchor2;
  31515. double value;
  31516. double resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const;
  31517. static double resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter);
  31518. };
  31519. /**
  31520. An X-Y position stored as a pair of RelativeCoordinate values.
  31521. @see RelativeCoordinate, RelativeRectangle
  31522. */
  31523. class JUCE_API RelativePoint
  31524. {
  31525. public:
  31526. /** Creates a point at the origin. */
  31527. RelativePoint();
  31528. /** Creates an absolute point, relative to the origin. */
  31529. RelativePoint (const Point<float>& absolutePoint);
  31530. /** Creates an absolute point from two coordinates. */
  31531. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  31532. /** Creates a point from a stringified representation.
  31533. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  31534. strings is explained in the RelativeCoordinate class.
  31535. @see toString
  31536. */
  31537. RelativePoint (const String& stringVersion);
  31538. bool operator== (const RelativePoint& other) const throw();
  31539. bool operator!= (const RelativePoint& other) const throw();
  31540. /** Calculates the absolute position of this point.
  31541. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31542. be needed to calculate the result.
  31543. */
  31544. const Point<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  31545. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  31546. Calling this will leave any anchor points unchanged, but will set any absolute
  31547. or relative positions to whatever values are necessary to make the resultant position
  31548. match the position that is provided.
  31549. */
  31550. void moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31551. /** Returns a string which represents this point.
  31552. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  31553. coordinates, see the RelativeCoordinate constructor notes.
  31554. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  31555. */
  31556. const String toString() const;
  31557. /** Tells the point that an object is changing its name or being deleted.
  31558. This calls RelativeCoordinate::renameAnchorIfUsed() on its X and Y coordinates.
  31559. */
  31560. void renameAnchorIfUsed (const String& oldName, const String& newName,
  31561. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31562. /** Returns true if this point depends on any other coordinates for its position. */
  31563. bool isDynamic() const;
  31564. // The actual X and Y coords...
  31565. RelativeCoordinate x, y;
  31566. };
  31567. /**
  31568. An rectangle stored as a set of RelativeCoordinate values.
  31569. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  31570. @see RelativeCoordinate, RelativePoint
  31571. */
  31572. class JUCE_API RelativeRectangle
  31573. {
  31574. public:
  31575. /** Creates a zero-size rectangle at the origin. */
  31576. RelativeRectangle();
  31577. /** Creates an absolute rectangle, relative to the origin. */
  31578. explicit RelativeRectangle (const Rectangle<float>& rect, const String& componentName);
  31579. /** Creates a rectangle from a stringified representation.
  31580. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  31581. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  31582. RelativeCoordinate class.
  31583. @see toString
  31584. */
  31585. explicit RelativeRectangle (const String& stringVersion);
  31586. bool operator== (const RelativeRectangle& other) const throw();
  31587. bool operator!= (const RelativeRectangle& other) const throw();
  31588. /** Calculates the absolute position of this rectangle.
  31589. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  31590. be needed to calculate the result.
  31591. */
  31592. const Rectangle<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  31593. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  31594. Calling this will leave any anchor points unchanged, but will set any absolute
  31595. or relative positions to whatever values are necessary to make the resultant position
  31596. match the position that is provided.
  31597. */
  31598. void moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31599. /** Returns a string which represents this point.
  31600. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  31601. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  31602. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  31603. */
  31604. const String toString() const;
  31605. /** Tells the rectangle that an object is changing its name or being deleted.
  31606. This calls RelativeCoordinate::renameAnchorIfUsed() on the rectangle's coordinates.
  31607. */
  31608. void renameAnchorIfUsed (const String& oldName, const String& newName,
  31609. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  31610. // The actual rectangle coords...
  31611. RelativeCoordinate left, right, top, bottom;
  31612. };
  31613. /**
  31614. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  31615. One of these paths can be converted into a Path object for drawing and manipulation, but
  31616. unlike a Path, its points can be dynamic instead of just fixed.
  31617. @see RelativePoint, RelativeCoordinate
  31618. */
  31619. class JUCE_API RelativePointPath
  31620. {
  31621. public:
  31622. RelativePointPath();
  31623. RelativePointPath (const RelativePointPath& other);
  31624. RelativePointPath (const String& stringVersion);
  31625. ~RelativePointPath();
  31626. /** Resolves this points in this path and adds them to a normal Path object. */
  31627. void createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  31628. /** Returns true if the path contains any non-fixed points. */
  31629. bool containsAnyDynamicPoints() const;
  31630. /** Returns a string version of the path.
  31631. This has the same format as Path::toString(), but since it can contain RelativeCoordinate
  31632. positions, it can't be parsed by the Path class if any of the points are dynamic.
  31633. */
  31634. const String toString() const;
  31635. /** Quickly swaps the contents of this path with another. */
  31636. void swapWith (RelativePointPath& other) throw();
  31637. /** The types of element that may be contained in this path.
  31638. @see RelativePointPath::ElementBase
  31639. */
  31640. enum ElementType
  31641. {
  31642. nullElement,
  31643. startSubPathElement,
  31644. closeSubPathElement,
  31645. lineToElement,
  31646. quadraticToElement,
  31647. cubicToElement
  31648. };
  31649. /** Base class for the elements that make up a RelativePointPath.
  31650. */
  31651. class JUCE_API ElementBase
  31652. {
  31653. public:
  31654. ElementBase (ElementType type);
  31655. virtual ~ElementBase() {}
  31656. virtual void write (OutputStream& out, ElementType lastTypeWritten) const = 0;
  31657. virtual void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const = 0;
  31658. const ElementType type;
  31659. };
  31660. class JUCE_API StartSubPath : public ElementBase
  31661. {
  31662. public:
  31663. StartSubPath (const RelativePoint& pos);
  31664. ~StartSubPath() {}
  31665. void write (OutputStream& out, ElementType lastTypeWritten) const;
  31666. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  31667. RelativePoint startPos;
  31668. };
  31669. class JUCE_API CloseSubPath : public ElementBase
  31670. {
  31671. public:
  31672. CloseSubPath();
  31673. ~CloseSubPath() {}
  31674. void write (OutputStream& out, ElementType lastTypeWritten) const;
  31675. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  31676. };
  31677. class JUCE_API LineTo : public ElementBase
  31678. {
  31679. public:
  31680. LineTo (const RelativePoint& endPoint);
  31681. ~LineTo() {}
  31682. void write (OutputStream& out, ElementType lastTypeWritten) const;
  31683. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  31684. RelativePoint endPoint;
  31685. };
  31686. class JUCE_API QuadraticTo : public ElementBase
  31687. {
  31688. public:
  31689. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  31690. ~QuadraticTo() {}
  31691. void write (OutputStream& out, ElementType lastTypeWritten) const;
  31692. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  31693. RelativePoint controlPoint, endPoint;
  31694. };
  31695. class JUCE_API CubicTo : public ElementBase
  31696. {
  31697. public:
  31698. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  31699. ~CubicTo() {}
  31700. void write (OutputStream& out, ElementType lastTypeWritten) const;
  31701. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  31702. RelativePoint controlPoint1, controlPoint2, endPoint;
  31703. };
  31704. OwnedArray <ElementBase> elements;
  31705. bool usesNonZeroWinding;
  31706. private:
  31707. bool containsDynamicPoints;
  31708. void parseString (const String& s);
  31709. RelativePointPath& operator= (const RelativePointPath&);
  31710. };
  31711. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  31712. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  31713. class DrawableComposite;
  31714. /**
  31715. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  31716. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  31717. */
  31718. class JUCE_API Drawable
  31719. {
  31720. protected:
  31721. /** The base class can't be instantiated directly.
  31722. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  31723. */
  31724. Drawable();
  31725. public:
  31726. /** Destructor. */
  31727. virtual ~Drawable();
  31728. /** Creates a deep copy of this Drawable object.
  31729. Use this to create a new copy of this and any sub-objects in the tree.
  31730. */
  31731. virtual Drawable* createCopy() const = 0;
  31732. /** Renders this Drawable object.
  31733. @see drawWithin
  31734. */
  31735. void draw (Graphics& g, float opacity,
  31736. const AffineTransform& transform = AffineTransform::identity) const;
  31737. /** Renders the Drawable at a given offset within the Graphics context.
  31738. The co-ordinates passed-in are used to translate the object relative to its own
  31739. origin before drawing it - this is basically a quick way of saying:
  31740. @code
  31741. draw (g, AffineTransform::translation (x, y)).
  31742. @endcode
  31743. */
  31744. void drawAt (Graphics& g,
  31745. float x, float y,
  31746. float opacity) const;
  31747. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  31748. changing its aspect-ratio.
  31749. The object can placed arbitrarily within the rectangle based on a Justification type,
  31750. and can either be made as big as possible, or just reduced to fit.
  31751. @param g the graphics context to render onto
  31752. @param destX top-left of the target rectangle to fit it into
  31753. @param destY top-left of the target rectangle to fit it into
  31754. @param destWidth size of the target rectangle to fit the image into
  31755. @param destHeight size of the target rectangle to fit the image into
  31756. @param placement defines the alignment and rescaling to use to fit
  31757. this object within the target rectangle.
  31758. @param opacity the opacity to use, in the range 0 to 1.0
  31759. */
  31760. void drawWithin (Graphics& g,
  31761. int destX,
  31762. int destY,
  31763. int destWidth,
  31764. int destHeight,
  31765. const RectanglePlacement& placement,
  31766. float opacity) const;
  31767. /** Holds the information needed when telling a drawable to render itself.
  31768. @see Drawable::draw
  31769. */
  31770. class RenderingContext
  31771. {
  31772. public:
  31773. RenderingContext (Graphics& g, const AffineTransform& transform, float opacity) throw();
  31774. Graphics& g;
  31775. AffineTransform transform;
  31776. float opacity;
  31777. private:
  31778. RenderingContext& operator= (const RenderingContext&);
  31779. };
  31780. /** Renders this Drawable object.
  31781. @see draw
  31782. */
  31783. virtual void render (const RenderingContext& context) const = 0;
  31784. /** Returns the smallest rectangle that can contain this Drawable object.
  31785. Co-ordinates are relative to the object's own origin.
  31786. */
  31787. virtual const Rectangle<float> getBounds() const = 0;
  31788. /** Returns true if the given point is somewhere inside this Drawable.
  31789. Co-ordinates are relative to the object's own origin.
  31790. */
  31791. virtual bool hitTest (float x, float y) const = 0;
  31792. /** Returns the name given to this drawable.
  31793. @see setName
  31794. */
  31795. const String& getName() const throw() { return name; }
  31796. /** Assigns a name to this drawable. */
  31797. void setName (const String& newName) throw() { name = newName; }
  31798. /** Tries to turn some kind of image file into a drawable.
  31799. The data could be an image that the ImageFileFormat class understands, or it
  31800. could be SVG.
  31801. */
  31802. static Drawable* createFromImageData (const void* data, size_t numBytes);
  31803. /** Tries to turn a stream containing some kind of image data into a drawable.
  31804. The data could be an image that the ImageFileFormat class understands, or it
  31805. could be SVG.
  31806. */
  31807. static Drawable* createFromImageDataStream (InputStream& dataSource);
  31808. /** Tries to turn a file containing some kind of image data into a drawable.
  31809. The data could be an image that the ImageFileFormat class understands, or it
  31810. could be SVG.
  31811. */
  31812. static Drawable* createFromImageFile (const File& file);
  31813. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  31814. into a Drawable tree.
  31815. The object returned must be deleted by the caller. If something goes wrong
  31816. while parsing, it may return 0.
  31817. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  31818. implementation, but it can return the basic vector objects.
  31819. */
  31820. static Drawable* createFromSVG (const XmlElement& svgDocument);
  31821. /** This class is used when loading Drawables that contain images, and retrieves
  31822. the image for a stored identifier.
  31823. @see Drawable::createFromValueTree
  31824. */
  31825. class JUCE_API ImageProvider
  31826. {
  31827. public:
  31828. ImageProvider() {}
  31829. virtual ~ImageProvider() {}
  31830. /** Retrieves the image associated with this identifier, which could be any
  31831. kind of string, number, filename, etc.
  31832. The image that is returned will be owned by the caller, but it may come
  31833. from the ImageCache.
  31834. */
  31835. virtual Image* getImageForIdentifier (const var& imageIdentifier) = 0;
  31836. /** Returns an identifier to be used to refer to a given image.
  31837. This is used when converting a drawable into a ValueTree, so if you're
  31838. only loading drawables, you can just return a var::null here.
  31839. */
  31840. virtual const var getIdentifierForImage (Image* image) = 0;
  31841. };
  31842. /** Tries to create a Drawable from a previously-saved ValueTree.
  31843. The ValueTree must have been created by the createValueTree() method.
  31844. If there are any images used within the drawable, you'll need to provide a valid
  31845. ImageProvider object that can be used to retrieve these images from whatever type
  31846. of identifier is used to represent them.
  31847. */
  31848. static Drawable* createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  31849. /** Tries to refresh a Drawable from the same ValueTree that was used to create it.
  31850. @returns the damage rectangle that will need repainting due to any changes that were made.
  31851. */
  31852. virtual const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider) = 0;
  31853. /** Creates a ValueTree to represent this Drawable.
  31854. The VarTree that is returned can be turned back into a Drawable with
  31855. createFromValueTree().
  31856. If there are any images used in this drawable, you'll need to provide a valid
  31857. ImageProvider object that can be used to create storable representations of them.
  31858. */
  31859. virtual const ValueTree createValueTree (ImageProvider* imageProvider) const = 0;
  31860. /** Returns the tag ID that is used for a ValueTree that stores this type of drawable. */
  31861. virtual const Identifier getValueTreeType() const = 0;
  31862. /** Internal class used to manage ValueTrees that represent Drawables. */
  31863. class ValueTreeWrapperBase
  31864. {
  31865. public:
  31866. ValueTreeWrapperBase (const ValueTree& state);
  31867. ~ValueTreeWrapperBase();
  31868. ValueTree& getState() throw() { return state; }
  31869. const String getID() const;
  31870. void setID (const String& newID, UndoManager* undoManager);
  31871. protected:
  31872. ValueTree state;
  31873. static const Identifier idProperty, type, x1, x2, y1, y2, colour, radial, colours;
  31874. static const FillType readFillType (const ValueTree& v);
  31875. void replaceFillType (const Identifier& tag, const FillType& fillType, UndoManager* undoManager);
  31876. };
  31877. juce_UseDebuggingNewOperator
  31878. protected:
  31879. friend class DrawableComposite;
  31880. DrawableComposite* parent;
  31881. virtual void invalidatePoints() = 0;
  31882. private:
  31883. String name;
  31884. Drawable (const Drawable&);
  31885. Drawable& operator= (const Drawable&);
  31886. };
  31887. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  31888. /*** End of inlined file: juce_Drawable.h ***/
  31889. /**
  31890. A button that displays a Drawable.
  31891. Up to three Drawable objects can be given to this button, to represent the
  31892. 'normal', 'over' and 'down' states.
  31893. @see Button
  31894. */
  31895. class JUCE_API DrawableButton : public Button
  31896. {
  31897. public:
  31898. enum ButtonStyle
  31899. {
  31900. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  31901. ImageRaw, /**< The button will just display the images in their normal size and position.
  31902. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  31903. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  31904. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  31905. };
  31906. /** Creates a DrawableButton.
  31907. After creating one of these, use setImages() to specify the drawables to use.
  31908. @param buttonName the name to give the component
  31909. @param buttonStyle the layout to use
  31910. @see ButtonStyle, setButtonStyle, setImages
  31911. */
  31912. DrawableButton (const String& buttonName,
  31913. ButtonStyle buttonStyle);
  31914. /** Destructor. */
  31915. ~DrawableButton();
  31916. /** Sets up the images to draw for the various button states.
  31917. The button will keep its own internal copies of these drawables.
  31918. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  31919. will be made of the object passed-in if it is non-zero.
  31920. @param overImage the thing to draw for the button's 'over' state - if this is
  31921. zero, the button's normal image will be used when the mouse is
  31922. over it. An internal copy will be made of the object passed-in
  31923. if it is non-zero.
  31924. @param downImage the thing to draw for the button's 'down' state - if this is
  31925. zero, the 'over' image will be used instead (or the normal image
  31926. as a last resort). An internal copy will be made of the object
  31927. passed-in if it is non-zero.
  31928. @param disabledImage an image to draw when the button is disabled. If this is zero,
  31929. the normal image will be drawn with a reduced opacity instead.
  31930. An internal copy will be made of the object passed-in if it is
  31931. non-zero.
  31932. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  31933. state is 'on'. If this is 0, the normal image is used instead
  31934. @param overImageOn same as the overImage, but this is used when the button's toggle
  31935. state is 'on'. If this is 0, the normalImageOn is drawn instead
  31936. @param downImageOn same as the downImage, but this is used when the button's toggle
  31937. state is 'on'. If this is 0, the overImageOn is drawn instead
  31938. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  31939. state is 'on'. If this is 0, the normal image will be drawn instead
  31940. with a reduced opacity
  31941. */
  31942. void setImages (const Drawable* normalImage,
  31943. const Drawable* overImage = 0,
  31944. const Drawable* downImage = 0,
  31945. const Drawable* disabledImage = 0,
  31946. const Drawable* normalImageOn = 0,
  31947. const Drawable* overImageOn = 0,
  31948. const Drawable* downImageOn = 0,
  31949. const Drawable* disabledImageOn = 0);
  31950. /** Changes the button's style.
  31951. @see ButtonStyle
  31952. */
  31953. void setButtonStyle (ButtonStyle newStyle);
  31954. /** Changes the button's background colours.
  31955. The toggledOffColour is the colour to use when the button's toggle state
  31956. is off, and toggledOnColour when it's on.
  31957. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  31958. used to fill the background of the component.
  31959. For an ImageOnButtonBackground style, the colour is used to draw the
  31960. button's lozenge shape and exactly how the colour's used will depend
  31961. on the LookAndFeel.
  31962. */
  31963. void setBackgroundColours (const Colour& toggledOffColour,
  31964. const Colour& toggledOnColour);
  31965. /** Returns the current background colour being used.
  31966. @see setBackgroundColour
  31967. */
  31968. const Colour& getBackgroundColour() const throw();
  31969. /** Gives the button an optional amount of space around the edge of the drawable.
  31970. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  31971. ones on a button background. If the button is too small for the given gap, a
  31972. smaller gap will be used.
  31973. By default there's a gap of about 3 pixels.
  31974. */
  31975. void setEdgeIndent (int numPixelsIndent);
  31976. /** Returns the image that the button is currently displaying. */
  31977. const Drawable* getCurrentImage() const throw();
  31978. const Drawable* getNormalImage() const throw();
  31979. const Drawable* getOverImage() const throw();
  31980. const Drawable* getDownImage() const throw();
  31981. juce_UseDebuggingNewOperator
  31982. protected:
  31983. /** @internal */
  31984. void paintButton (Graphics& g,
  31985. bool isMouseOverButton,
  31986. bool isButtonDown);
  31987. private:
  31988. ButtonStyle style;
  31989. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  31990. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  31991. Colour backgroundOff, backgroundOn;
  31992. int edgeIndent;
  31993. void deleteImages();
  31994. DrawableButton (const DrawableButton&);
  31995. DrawableButton& operator= (const DrawableButton&);
  31996. };
  31997. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  31998. /*** End of inlined file: juce_DrawableButton.h ***/
  31999. #endif
  32000. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32001. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  32002. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32003. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32004. /**
  32005. A button showing an underlined weblink, that will launch the link
  32006. when it's clicked.
  32007. @see Button
  32008. */
  32009. class JUCE_API HyperlinkButton : public Button
  32010. {
  32011. public:
  32012. /** Creates a HyperlinkButton.
  32013. @param linkText the text that will be displayed in the button - this is
  32014. also set as the Component's name, but the text can be
  32015. changed later with the Button::getButtonText() method
  32016. @param linkURL the URL to launch when the user clicks the button
  32017. */
  32018. HyperlinkButton (const String& linkText,
  32019. const URL& linkURL);
  32020. /** Destructor. */
  32021. ~HyperlinkButton();
  32022. /** Changes the font to use for the text.
  32023. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  32024. to match the size of the component.
  32025. */
  32026. void setFont (const Font& newFont,
  32027. bool resizeToMatchComponentHeight,
  32028. const Justification& justificationType = Justification::horizontallyCentred);
  32029. /** A set of colour IDs to use to change the colour of various aspects of the link.
  32030. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32031. methods.
  32032. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32033. */
  32034. enum ColourIds
  32035. {
  32036. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  32037. };
  32038. /** Changes the URL that the button will trigger. */
  32039. void setURL (const URL& newURL) throw();
  32040. /** Returns the URL that the button will trigger. */
  32041. const URL& getURL() const throw() { return url; }
  32042. /** Resizes the button horizontally to fit snugly around the text.
  32043. This won't affect the button's height.
  32044. */
  32045. void changeWidthToFitText();
  32046. juce_UseDebuggingNewOperator
  32047. protected:
  32048. /** @internal */
  32049. void clicked();
  32050. /** @internal */
  32051. void colourChanged();
  32052. /** @internal */
  32053. void paintButton (Graphics& g,
  32054. bool isMouseOverButton,
  32055. bool isButtonDown);
  32056. private:
  32057. URL url;
  32058. Font font;
  32059. bool resizeFont;
  32060. Justification justification;
  32061. const Font getFontToUse() const;
  32062. HyperlinkButton (const HyperlinkButton&);
  32063. HyperlinkButton& operator= (const HyperlinkButton&);
  32064. };
  32065. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32066. /*** End of inlined file: juce_HyperlinkButton.h ***/
  32067. #endif
  32068. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32069. /*** Start of inlined file: juce_ImageButton.h ***/
  32070. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32071. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  32072. /**
  32073. As the title suggests, this is a button containing an image.
  32074. The colour and transparency of the image can be set to vary when the
  32075. button state changes.
  32076. @see Button, ShapeButton, TextButton
  32077. */
  32078. class JUCE_API ImageButton : public Button
  32079. {
  32080. public:
  32081. /** Creates an ImageButton.
  32082. Use setImage() to specify the image to use. The colours and opacities that
  32083. are specified here can be changed later using setDrawingOptions().
  32084. @param name the name to give the component
  32085. */
  32086. explicit ImageButton (const String& name);
  32087. /** Destructor. */
  32088. ~ImageButton();
  32089. /** Sets up the images to draw in various states.
  32090. Important! Bear in mind that if you pass the same image in for more than one of
  32091. these parameters, this button will delete it (or release from the ImageCache)
  32092. multiple times!
  32093. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  32094. resized to the same dimensions as the normal image
  32095. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  32096. button when the button's size changes
  32097. @param preserveImageProportions if true then any rescaling of the image to fit
  32098. the button will keep the image's x and y proportions
  32099. correct - i.e. it won't distort its shape, although
  32100. this might create gaps around the edges
  32101. @param normalImage the image to use when the button is in its normal state. The
  32102. image passed in will be deleted (or released if it
  32103. was created by the ImageCache class) when the
  32104. button no longer needs it.
  32105. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  32106. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  32107. normal image - if this colour is transparent, no overlay
  32108. will be drawn. The overlay will be drawn over the top of the
  32109. image, so you can basically add a solid or semi-transparent
  32110. colour to the image to brighten or darken it
  32111. @param overImage the image to use when the mouse is over the button. If
  32112. you want to use the same image as was set in the normalImage
  32113. parameter, this value can be 0. As for normalImage, it
  32114. will be deleted or released by the button when no longer
  32115. needed
  32116. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  32117. is over the button
  32118. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  32119. image when the mouse is over - if this colour is transparent,
  32120. no overlay will be drawn
  32121. @param downImage an image to use when the button is pressed down. If set
  32122. to zero, the 'over' image will be drawn instead (or the
  32123. normal image if there isn't an 'over' image either). This
  32124. image will be deleted or released by the button when no
  32125. longer needed
  32126. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  32127. is pressed
  32128. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  32129. image when the button is pressed down - if this colour is
  32130. transparent, no overlay will be drawn
  32131. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  32132. whenever it's inside the button's bounding rectangle. If
  32133. set to values higher than 0, the mouse will only be
  32134. considered to be over the image when the value of the
  32135. image's alpha channel at that position is greater than
  32136. this level.
  32137. */
  32138. void setImages (bool resizeButtonNowToFitThisImage,
  32139. bool rescaleImagesWhenButtonSizeChanges,
  32140. bool preserveImageProportions,
  32141. Image* normalImage,
  32142. float imageOpacityWhenNormal,
  32143. const Colour& overlayColourWhenNormal,
  32144. Image* overImage,
  32145. float imageOpacityWhenOver,
  32146. const Colour& overlayColourWhenOver,
  32147. Image* downImage,
  32148. float imageOpacityWhenDown,
  32149. const Colour& overlayColourWhenDown,
  32150. float hitTestAlphaThreshold = 0.0f);
  32151. /** Returns the currently set 'normal' image. */
  32152. Image* getNormalImage() const throw();
  32153. /** Returns the image that's drawn when the mouse is over the button.
  32154. If an 'over' image has been set, this will return it; otherwise it'll
  32155. just return the normal image.
  32156. */
  32157. Image* getOverImage() const throw();
  32158. /** Returns the image that's drawn when the button is held down.
  32159. If a 'down' image has been set, this will return it; otherwise it'll
  32160. return the 'over' image or normal image, depending on what's available.
  32161. */
  32162. Image* getDownImage() const throw();
  32163. juce_UseDebuggingNewOperator
  32164. protected:
  32165. /** @internal */
  32166. bool hitTest (int x, int y);
  32167. /** @internal */
  32168. void paintButton (Graphics& g,
  32169. bool isMouseOverButton,
  32170. bool isButtonDown);
  32171. private:
  32172. bool scaleImageToFit, preserveProportions;
  32173. unsigned char alphaThreshold;
  32174. int imageX, imageY, imageW, imageH;
  32175. Image* normalImage;
  32176. Image* overImage;
  32177. Image* downImage;
  32178. float normalOpacity, overOpacity, downOpacity;
  32179. Colour normalOverlay, overOverlay, downOverlay;
  32180. Image* getCurrentImage() const;
  32181. void deleteImages();
  32182. ImageButton (const ImageButton&);
  32183. ImageButton& operator= (const ImageButton&);
  32184. };
  32185. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  32186. /*** End of inlined file: juce_ImageButton.h ***/
  32187. #endif
  32188. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32189. /*** Start of inlined file: juce_ShapeButton.h ***/
  32190. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32191. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  32192. /**
  32193. A button that contains a filled shape.
  32194. @see Button, ImageButton, TextButton, ArrowButton
  32195. */
  32196. class JUCE_API ShapeButton : public Button
  32197. {
  32198. public:
  32199. /** Creates a ShapeButton.
  32200. @param name a name to give the component - see Component::setName()
  32201. @param normalColour the colour to fill the shape with when the mouse isn't over
  32202. @param overColour the colour to use when the mouse is over the shape
  32203. @param downColour the colour to use when the button is in the pressed-down state
  32204. */
  32205. ShapeButton (const String& name,
  32206. const Colour& normalColour,
  32207. const Colour& overColour,
  32208. const Colour& downColour);
  32209. /** Destructor. */
  32210. ~ShapeButton();
  32211. /** Sets the shape to use.
  32212. @param newShape the shape to use
  32213. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  32214. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  32215. the button is resized
  32216. @param hasDropShadow if true, the button will be given a drop-shadow effect
  32217. */
  32218. void setShape (const Path& newShape,
  32219. bool resizeNowToFitThisShape,
  32220. bool maintainShapeProportions,
  32221. bool hasDropShadow);
  32222. /** Set the colours to use for drawing the shape.
  32223. @param normalColour the colour to fill the shape with when the mouse isn't over
  32224. @param overColour the colour to use when the mouse is over the shape
  32225. @param downColour the colour to use when the button is in the pressed-down state
  32226. */
  32227. void setColours (const Colour& normalColour,
  32228. const Colour& overColour,
  32229. const Colour& downColour);
  32230. /** Sets up an outline to draw around the shape.
  32231. @param outlineColour the colour to use
  32232. @param outlineStrokeWidth the thickness of line to draw
  32233. */
  32234. void setOutline (const Colour& outlineColour,
  32235. float outlineStrokeWidth);
  32236. juce_UseDebuggingNewOperator
  32237. protected:
  32238. /** @internal */
  32239. void paintButton (Graphics& g,
  32240. bool isMouseOverButton,
  32241. bool isButtonDown);
  32242. private:
  32243. Colour normalColour, overColour, downColour, outlineColour;
  32244. DropShadowEffect shadow;
  32245. Path shape;
  32246. bool maintainShapeProportions;
  32247. float outlineWidth;
  32248. ShapeButton (const ShapeButton&);
  32249. ShapeButton& operator= (const ShapeButton&);
  32250. };
  32251. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  32252. /*** End of inlined file: juce_ShapeButton.h ***/
  32253. #endif
  32254. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  32255. #endif
  32256. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32257. /*** Start of inlined file: juce_ToggleButton.h ***/
  32258. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32259. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32260. /**
  32261. A button that can be toggled on/off.
  32262. All buttons can be toggle buttons, but this lets you create one of the
  32263. standard ones which has a tick-box and a text label next to it.
  32264. @see Button, DrawableButton, TextButton
  32265. */
  32266. class JUCE_API ToggleButton : public Button
  32267. {
  32268. public:
  32269. /** Creates a ToggleButton.
  32270. @param buttonText the text to put in the button (the component's name is also
  32271. initially set to this string, but these can be changed later
  32272. using the setName() and setButtonText() methods)
  32273. */
  32274. explicit ToggleButton (const String& buttonText = String::empty);
  32275. /** Destructor. */
  32276. ~ToggleButton();
  32277. /** Resizes the button to fit neatly around its current text.
  32278. The button's height won't be affected, only its width.
  32279. */
  32280. void changeWidthToFitText();
  32281. /** A set of colour IDs to use to change the colour of various aspects of the button.
  32282. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32283. methods.
  32284. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32285. */
  32286. enum ColourIds
  32287. {
  32288. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  32289. };
  32290. juce_UseDebuggingNewOperator
  32291. protected:
  32292. /** @internal */
  32293. void paintButton (Graphics& g,
  32294. bool isMouseOverButton,
  32295. bool isButtonDown);
  32296. /** @internal */
  32297. void colourChanged();
  32298. private:
  32299. ToggleButton (const ToggleButton&);
  32300. ToggleButton& operator= (const ToggleButton&);
  32301. };
  32302. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  32303. /*** End of inlined file: juce_ToggleButton.h ***/
  32304. #endif
  32305. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32306. /*** Start of inlined file: juce_ToolbarButton.h ***/
  32307. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32308. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32309. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  32310. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32311. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32312. /*** Start of inlined file: juce_Toolbar.h ***/
  32313. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  32314. #define __JUCE_TOOLBAR_JUCEHEADER__
  32315. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  32316. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32317. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32318. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  32319. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32320. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32321. /**
  32322. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  32323. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  32324. derive your component from this class, and make sure that it is somewhere inside a
  32325. DragAndDropContainer component.
  32326. Note: If all that you need to do is to respond to files being drag-and-dropped from
  32327. the operating system onto your component, you don't need any of these classes: instead
  32328. see the FileDragAndDropTarget class.
  32329. @see DragAndDropContainer, FileDragAndDropTarget
  32330. */
  32331. class JUCE_API DragAndDropTarget
  32332. {
  32333. public:
  32334. /** Destructor. */
  32335. virtual ~DragAndDropTarget() {}
  32336. /** Callback to check whether this target is interested in the type of object being
  32337. dragged.
  32338. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32339. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32340. @returns true if this component wants to receive the other callbacks regarging this
  32341. type of object; if it returns false, no other callbacks will be made.
  32342. */
  32343. virtual bool isInterestedInDragSource (const String& sourceDescription,
  32344. Component* sourceComponent) = 0;
  32345. /** Callback to indicate that something is being dragged over this component.
  32346. This gets called when the user moves the mouse into this component while dragging
  32347. something.
  32348. Use this callback as a trigger to make your component repaint itself to give the
  32349. user feedback about whether the item can be dropped here or not.
  32350. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32351. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32352. @param x the mouse x position, relative to this component
  32353. @param y the mouse y position, relative to this component
  32354. @see itemDragExit
  32355. */
  32356. virtual void itemDragEnter (const String& sourceDescription,
  32357. Component* sourceComponent,
  32358. int x, int y);
  32359. /** Callback to indicate that the user is dragging something over this component.
  32360. This gets called when the user moves the mouse over this component while dragging
  32361. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  32362. this lets you know what happens in-between.
  32363. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32364. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32365. @param x the mouse x position, relative to this component
  32366. @param y the mouse y position, relative to this component
  32367. */
  32368. virtual void itemDragMove (const String& sourceDescription,
  32369. Component* sourceComponent,
  32370. int x, int y);
  32371. /** Callback to indicate that something has been dragged off the edge of this component.
  32372. This gets called when the user moves the mouse out of this component while dragging
  32373. something.
  32374. If you've used itemDragEnter() to repaint your component and give feedback, use this
  32375. as a signal to repaint it in its normal state.
  32376. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32377. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32378. @see itemDragEnter
  32379. */
  32380. virtual void itemDragExit (const String& sourceDescription,
  32381. Component* sourceComponent);
  32382. /** Callback to indicate that the user has dropped something onto this component.
  32383. When the user drops an item this get called, and you can use the description to
  32384. work out whether your object wants to deal with it or not.
  32385. Note that after this is called, the itemDragExit method may not be called, so you should
  32386. clean up in here if there's anything you need to do when the drag finishes.
  32387. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  32388. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  32389. @param x the mouse x position, relative to this component
  32390. @param y the mouse y position, relative to this component
  32391. */
  32392. virtual void itemDropped (const String& sourceDescription,
  32393. Component* sourceComponent,
  32394. int x, int y) = 0;
  32395. /** Overriding this allows the target to tell the drag container whether to
  32396. draw the drag image while the cursor is over it.
  32397. By default it returns true, but if you return false, then the normal drag
  32398. image will not be shown when the cursor is over this target.
  32399. */
  32400. virtual bool shouldDrawDragImageWhenOver();
  32401. };
  32402. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  32403. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  32404. /**
  32405. Enables drag-and-drop behaviour for a component and all its sub-components.
  32406. For a component to be able to make or receive drag-and-drop events, one of its parent
  32407. components must derive from this class. It's probably best for the top-level
  32408. component to implement it.
  32409. Then to start a drag operation, any sub-component can just call the startDragging()
  32410. method, and this object will take over, tracking the mouse and sending appropriate
  32411. callbacks to any child components derived from DragAndDropTarget which the mouse
  32412. moves over.
  32413. Note: If all that you need to do is to respond to files being drag-and-dropped from
  32414. the operating system onto your component, you don't need any of these classes: you can do this
  32415. simply by overriding Component::filesDropped().
  32416. @see DragAndDropTarget
  32417. */
  32418. class JUCE_API DragAndDropContainer
  32419. {
  32420. public:
  32421. /** Creates a DragAndDropContainer.
  32422. The object that derives from this class must also be a Component.
  32423. */
  32424. DragAndDropContainer();
  32425. /** Destructor. */
  32426. virtual ~DragAndDropContainer();
  32427. /** Begins a drag-and-drop operation.
  32428. This starts a drag-and-drop operation - call it when the user drags the
  32429. mouse in your drag-source component, and this object will track mouse
  32430. movements until the user lets go of the mouse button, and will send
  32431. appropriate messages to DragAndDropTarget objects that the mouse moves
  32432. over.
  32433. findParentDragContainerFor() is a handy method to call to find the
  32434. drag container to use for a component.
  32435. @param sourceDescription a string to use as the description of the thing being
  32436. dragged - this will be passed to the objects that might be
  32437. dropped-onto so they can decide if they want to handle it or
  32438. not
  32439. @param sourceComponent the component that is being dragged
  32440. @param dragImage the image to drag around underneath the mouse. If this is
  32441. zero, a snapshot of the sourceComponent will be used instead. An
  32442. image passed-in will be deleted by this object when no longer
  32443. needed.
  32444. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  32445. window, and can be dragged to DragAndDropTargets that are the
  32446. children of components other than this one.
  32447. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  32448. at which the image should be drawn from the mouse. If it isn't
  32449. specified, then the image will be centred around the mouse. If
  32450. an image hasn't been passed-in, this will be ignored.
  32451. */
  32452. void startDragging (const String& sourceDescription,
  32453. Component* sourceComponent,
  32454. Image* dragImage = 0,
  32455. bool allowDraggingToOtherJuceWindows = false,
  32456. const Point<int>* imageOffsetFromMouse = 0);
  32457. /** Returns true if something is currently being dragged. */
  32458. bool isDragAndDropActive() const;
  32459. /** Returns the description of the thing that's currently being dragged.
  32460. If nothing's being dragged, this will return an empty string, otherwise it's the
  32461. string that was passed into startDragging().
  32462. @see startDragging
  32463. */
  32464. const String getCurrentDragDescription() const;
  32465. /** Utility to find the DragAndDropContainer for a given Component.
  32466. This will search up this component's parent hierarchy looking for the first
  32467. parent component which is a DragAndDropContainer.
  32468. It's useful when a component wants to call startDragging but doesn't know
  32469. the DragAndDropContainer it should to use.
  32470. Obviously this may return 0 if it doesn't find a suitable component.
  32471. */
  32472. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  32473. /** This performs a synchronous drag-and-drop of a set of files to some external
  32474. application.
  32475. You can call this function in response to a mouseDrag callback, and it will
  32476. block, running its own internal message loop and tracking the mouse, while it
  32477. uses a native operating system drag-and-drop operation to move or copy some
  32478. files to another application.
  32479. @param files a list of filenames to drag
  32480. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  32481. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  32482. @returns true if the files were successfully dropped somewhere, or false if it
  32483. was interrupted
  32484. @see performExternalDragDropOfText
  32485. */
  32486. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  32487. /** This performs a synchronous drag-and-drop of a block of text to some external
  32488. application.
  32489. You can call this function in response to a mouseDrag callback, and it will
  32490. block, running its own internal message loop and tracking the mouse, while it
  32491. uses a native operating system drag-and-drop operation to move or copy some
  32492. text to another application.
  32493. @param text the text to copy
  32494. @returns true if the text was successfully dropped somewhere, or false if it
  32495. was interrupted
  32496. @see performExternalDragDropOfFiles
  32497. */
  32498. static bool performExternalDragDropOfText (const String& text);
  32499. juce_UseDebuggingNewOperator
  32500. protected:
  32501. /** Override this if you want to be able to perform an external drag a set of files
  32502. when the user drags outside of this container component.
  32503. This method will be called when a drag operation moves outside the Juce-based window,
  32504. and if you want it to then perform a file drag-and-drop, add the filenames you want
  32505. to the array passed in, and return true.
  32506. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  32507. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  32508. @param files on return, the filenames you want to drag
  32509. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  32510. it must make a copy of them (see the performExternalDragDropOfFiles()
  32511. method)
  32512. @see performExternalDragDropOfFiles
  32513. */
  32514. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  32515. Component* dragSourceComponent,
  32516. StringArray& files,
  32517. bool& canMoveFiles);
  32518. private:
  32519. friend class DragImageComponent;
  32520. ScopedPointer <Component> dragImageComponent;
  32521. String currentDragDesc;
  32522. };
  32523. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  32524. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  32525. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  32526. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32527. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32528. /**
  32529. Animates a set of components, moving it to a new position.
  32530. To use this, create a ComponentAnimator, and use its animateComponent() method
  32531. to tell it to move components to destination positions. Any number of
  32532. components can be animated by one ComponentAnimator object (if you've got a
  32533. lot of components to move, it's much more efficient to share a single animator
  32534. than to have many animators running at once).
  32535. You'll need to make sure the animator object isn't deleted before it finishes
  32536. moving the components.
  32537. The class is a ChangeBroadcaster and sends a notification when any components
  32538. start or finish being animated.
  32539. */
  32540. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  32541. private Timer
  32542. {
  32543. public:
  32544. /** Creates a ComponentAnimator. */
  32545. ComponentAnimator();
  32546. /** Destructor. */
  32547. ~ComponentAnimator();
  32548. /** Starts a component moving from its current position to a specified position.
  32549. If the component is already in the middle of an animation, that will be abandoned,
  32550. and a new animation will begin, moving the component from its current location.
  32551. The start and end speed parameters let you apply some acceleration to the component's
  32552. movement.
  32553. @param component the component to move
  32554. @param finalPosition the destination position and size to move it to
  32555. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  32556. to arrive at its destination
  32557. @param startSpeed a value to indicate the relative start speed of the
  32558. animation. If this is 0, the component will start
  32559. by accelerating from rest; higher values mean that it
  32560. will have an initial speed greater than zero. If the
  32561. value if greater than 1, it will decelerate towards the
  32562. middle of its journey. To move the component at a constant
  32563. rate for its entire animation, set both the start and
  32564. end speeds to 1.0
  32565. @param endSpeed a relative speed at which the component should be moving
  32566. when the animation finishes. If this is 0, the component
  32567. will decelerate to a standstill at its final position; higher
  32568. values mean the component will still be moving when it stops.
  32569. To move the component at a constant rate for its entire
  32570. animation, set both the start and end speeds to 1.0
  32571. */
  32572. void animateComponent (Component* component,
  32573. const Rectangle<int>& finalPosition,
  32574. int millisecondsToSpendMoving,
  32575. double startSpeed = 1.0,
  32576. double endSpeed = 1.0);
  32577. /** Stops a component if it's currently being animated.
  32578. If moveComponentToItsFinalPosition is true, then the component will
  32579. be immediately moved to its destination position and size. If false, it will be
  32580. left in whatever location it currently occupies.
  32581. */
  32582. void cancelAnimation (Component* component,
  32583. bool moveComponentToItsFinalPosition);
  32584. /** Clears all of the active animations.
  32585. If moveComponentsToTheirFinalPositions is true, all the components will
  32586. be immediately set to their final positions. If false, they will be
  32587. left in whatever locations they currently occupy.
  32588. */
  32589. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  32590. /** Returns the destination position for a component.
  32591. If the component is being animated, this will return the target position that
  32592. was specified when animateComponent() was called.
  32593. If the specified component isn't currently being animated, this method will just
  32594. return its current position.
  32595. */
  32596. const Rectangle<int> getComponentDestination (Component* component);
  32597. /** Returns true if the specified component is currently being animated.
  32598. */
  32599. bool isAnimating (Component* component) const;
  32600. juce_UseDebuggingNewOperator
  32601. private:
  32602. class AnimationTask;
  32603. Array <AnimationTask*> tasks;
  32604. uint32 lastTime;
  32605. AnimationTask* findTaskFor (Component* component) const;
  32606. void timerCallback();
  32607. };
  32608. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  32609. /*** End of inlined file: juce_ComponentAnimator.h ***/
  32610. class ToolbarItemComponent;
  32611. class ToolbarItemFactory;
  32612. class MissingItemsComponent;
  32613. /**
  32614. A toolbar component.
  32615. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  32616. and looks after their order and layout.
  32617. Items (icon buttons or other custom components) are added to a toolbar using a
  32618. ToolbarItemFactory - each type of item is given a unique ID number, and a
  32619. toolbar might contain more than one instance of a particular item type.
  32620. Toolbars can be interactively customised, allowing the user to drag the items
  32621. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  32622. component as a source of new items.
  32623. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  32624. */
  32625. class JUCE_API Toolbar : public Component,
  32626. public DragAndDropContainer,
  32627. public DragAndDropTarget,
  32628. private ButtonListener
  32629. {
  32630. public:
  32631. /** Creates an empty toolbar component.
  32632. To add some icons or other components to your toolbar, you'll need to
  32633. create a ToolbarItemFactory class that can create a suitable set of
  32634. ToolbarItemComponents.
  32635. @see ToolbarItemFactory, ToolbarItemComponents
  32636. */
  32637. Toolbar();
  32638. /** Destructor.
  32639. Any items on the bar will be deleted when the toolbar is deleted.
  32640. */
  32641. ~Toolbar();
  32642. /** Changes the bar's orientation.
  32643. @see isVertical
  32644. */
  32645. void setVertical (bool shouldBeVertical);
  32646. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  32647. You can change the bar's orientation with setVertical().
  32648. */
  32649. bool isVertical() const throw() { return vertical; }
  32650. /** Returns the depth of the bar.
  32651. If the bar is horizontal, this will return its height; if it's vertical, it
  32652. will return its width.
  32653. @see getLength
  32654. */
  32655. int getThickness() const throw();
  32656. /** Returns the length of the bar.
  32657. If the bar is horizontal, this will return its width; if it's vertical, it
  32658. will return its height.
  32659. @see getThickness
  32660. */
  32661. int getLength() const throw();
  32662. /** Deletes all items from the bar.
  32663. */
  32664. void clear();
  32665. /** Adds an item to the toolbar.
  32666. The factory's ToolbarItemFactory::createItem() will be called by this method
  32667. to create the component that will actually be added to the bar.
  32668. The new item will be inserted at the specified index (if the index is -1, it
  32669. will be added to the right-hand or bottom end of the bar).
  32670. Once added, the component will be automatically deleted by this object when it
  32671. is no longer needed.
  32672. @see ToolbarItemFactory
  32673. */
  32674. void addItem (ToolbarItemFactory& factory,
  32675. int itemId,
  32676. int insertIndex = -1);
  32677. /** Deletes one of the items from the bar.
  32678. */
  32679. void removeToolbarItem (int itemIndex);
  32680. /** Returns the number of items currently on the toolbar.
  32681. @see getItemId, getItemComponent
  32682. */
  32683. int getNumItems() const throw();
  32684. /** Returns the ID of the item with the given index.
  32685. If the index is less than zero or greater than the number of items,
  32686. this will return 0.
  32687. @see getNumItems
  32688. */
  32689. int getItemId (int itemIndex) const throw();
  32690. /** Returns the component being used for the item with the given index.
  32691. If the index is less than zero or greater than the number of items,
  32692. this will return 0.
  32693. @see getNumItems
  32694. */
  32695. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  32696. /** Clears this toolbar and adds to it the default set of items that the specified
  32697. factory creates.
  32698. @see ToolbarItemFactory::getDefaultItemSet
  32699. */
  32700. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  32701. /** Options for the way items should be displayed.
  32702. @see setStyle, getStyle
  32703. */
  32704. enum ToolbarItemStyle
  32705. {
  32706. iconsOnly, /**< Means that the toolbar should just contain icons. */
  32707. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  32708. textOnly /**< Means that the toolbar only display text labels for each item. */
  32709. };
  32710. /** Returns the toolbar's current style.
  32711. @see ToolbarItemStyle, setStyle
  32712. */
  32713. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32714. /** Changes the toolbar's current style.
  32715. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  32716. */
  32717. void setStyle (const ToolbarItemStyle& newStyle);
  32718. /** Flags used by the showCustomisationDialog() method. */
  32719. enum CustomisationFlags
  32720. {
  32721. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  32722. show the "icons only" option on its choice of toolbar styles. */
  32723. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  32724. show the "icons with text" option on its choice of toolbar styles. */
  32725. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  32726. show the "text only" option on its choice of toolbar styles. */
  32727. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  32728. show a button to reset the toolbar to its default set of items. */
  32729. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  32730. };
  32731. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  32732. The dialog contains a ToolbarItemPalette and various controls for editing other
  32733. aspects of the toolbar. This method will block and run the dialog box modally,
  32734. returning when the user closes it.
  32735. The factory is used to determine the set of items that will be shown on the
  32736. palette.
  32737. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  32738. enum.
  32739. @see ToolbarItemPalette
  32740. */
  32741. void showCustomisationDialog (ToolbarItemFactory& factory,
  32742. int optionFlags = allCustomisationOptionsEnabled);
  32743. /** Turns on or off the toolbar's editing mode, in which its items can be
  32744. rearranged by the user.
  32745. (In most cases it's easier just to use showCustomisationDialog() instead of
  32746. trying to enable editing directly).
  32747. @see ToolbarItemPalette
  32748. */
  32749. void setEditingActive (bool editingEnabled);
  32750. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  32751. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32752. methods.
  32753. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32754. */
  32755. enum ColourIds
  32756. {
  32757. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  32758. more control over this, override LookAndFeel::paintToolbarBackground(). */
  32759. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  32760. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  32761. over them. */
  32762. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  32763. held down on them. */
  32764. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  32765. when the style is set to iconsWithText or textOnly. */
  32766. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  32767. the customisation dialog is active and the mouse moves over them. */
  32768. };
  32769. /** Returns a string that represents the toolbar's current set of items.
  32770. This lets you later restore the same item layout using restoreFromString().
  32771. @see restoreFromString
  32772. */
  32773. const String toString() const;
  32774. /** Restores a set of items that was previously stored in a string by the toString()
  32775. method.
  32776. The factory object is used to create any item components that are needed.
  32777. @see toString
  32778. */
  32779. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  32780. const String& savedVersion);
  32781. /** @internal */
  32782. void paint (Graphics& g);
  32783. /** @internal */
  32784. void resized();
  32785. /** @internal */
  32786. void buttonClicked (Button*);
  32787. /** @internal */
  32788. void mouseDown (const MouseEvent&);
  32789. /** @internal */
  32790. bool isInterestedInDragSource (const String&, Component*);
  32791. /** @internal */
  32792. void itemDragMove (const String&, Component*, int, int);
  32793. /** @internal */
  32794. void itemDragExit (const String&, Component*);
  32795. /** @internal */
  32796. void itemDropped (const String&, Component*, int, int);
  32797. /** @internal */
  32798. void updateAllItemPositions (const bool animate);
  32799. /** @internal */
  32800. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  32801. juce_UseDebuggingNewOperator
  32802. private:
  32803. Button* missingItemsButton;
  32804. bool vertical, isEditingActive;
  32805. ToolbarItemStyle toolbarStyle;
  32806. ComponentAnimator animator;
  32807. friend class MissingItemsComponent;
  32808. Array <ToolbarItemComponent*> items;
  32809. friend class ItemDragAndDropOverlayComponent;
  32810. static const char* const toolbarDragDescriptor;
  32811. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  32812. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  32813. Toolbar (const Toolbar&);
  32814. Toolbar& operator= (const Toolbar&);
  32815. };
  32816. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  32817. /*** End of inlined file: juce_Toolbar.h ***/
  32818. class ItemDragAndDropOverlayComponent;
  32819. /**
  32820. A component that can be used as one of the items in a Toolbar.
  32821. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  32822. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  32823. class for further info about creating them.
  32824. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  32825. components too. To do this, set the value of isBeingUsedAsAButton to false when
  32826. calling the constructor, and override contentAreaChanged(), in which you can position
  32827. any sub-components you need to add.
  32828. To add basic buttons without writing a special subclass, have a look at the
  32829. ToolbarButton class.
  32830. @see ToolbarButton, Toolbar, ToolbarItemFactory
  32831. */
  32832. class JUCE_API ToolbarItemComponent : public Button
  32833. {
  32834. public:
  32835. /** Constructor.
  32836. @param itemId the ID of the type of toolbar item which this represents
  32837. @param labelText the text to display if the toolbar's style is set to
  32838. Toolbar::iconsWithText or Toolbar::textOnly
  32839. @param isBeingUsedAsAButton set this to false if you don't want the button
  32840. to draw itself with button over/down states when the mouse
  32841. moves over it or clicks
  32842. */
  32843. ToolbarItemComponent (int itemId,
  32844. const String& labelText,
  32845. bool isBeingUsedAsAButton);
  32846. /** Destructor. */
  32847. ~ToolbarItemComponent();
  32848. /** Returns the item type ID that this component represents.
  32849. This value is in the constructor.
  32850. */
  32851. int getItemId() const throw() { return itemId; }
  32852. /** Returns the toolbar that contains this component, or 0 if it's not currently
  32853. inside one.
  32854. */
  32855. Toolbar* getToolbar() const;
  32856. /** Returns true if this component is currently inside a toolbar which is vertical.
  32857. @see Toolbar::isVertical
  32858. */
  32859. bool isToolbarVertical() const;
  32860. /** Returns the current style setting of this item.
  32861. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  32862. @see setStyle, Toolbar::getStyle
  32863. */
  32864. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  32865. /** Changes the current style setting of this item.
  32866. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  32867. by the toolbar that holds this item.
  32868. @see setStyle, Toolbar::setStyle
  32869. */
  32870. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  32871. /** Returns the area of the component that should be used to display the button image or
  32872. other contents of the item.
  32873. This content area may change when the item's style changes, and may leave a space around the
  32874. edge of the component where the text label can be shown.
  32875. @see contentAreaChanged
  32876. */
  32877. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  32878. /** This method must return the size criteria for this item, based on a given toolbar
  32879. size and orientation.
  32880. The preferredSize, minSize and maxSize values must all be set by your implementation
  32881. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  32882. toolbar, they refer to the item's height.
  32883. The preferredSize is the size that the component would like to be, and this must be
  32884. between the min and max sizes. For a fixed-size item, simply set all three variables to
  32885. the same value.
  32886. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  32887. Toolbar::getThickness().
  32888. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  32889. vertically.
  32890. */
  32891. virtual bool getToolbarItemSizes (int toolbarThickness,
  32892. bool isToolbarVertical,
  32893. int& preferredSize,
  32894. int& minSize,
  32895. int& maxSize) = 0;
  32896. /** Your subclass should use this method to draw its content area.
  32897. The graphics object that is passed-in will have been clipped and had its origin
  32898. moved to fit the content area as specified get getContentArea(). The width and height
  32899. parameters are the width and height of the content area.
  32900. If the component you're writing isn't a button, you can just do nothing in this method.
  32901. */
  32902. virtual void paintButtonArea (Graphics& g,
  32903. int width, int height,
  32904. bool isMouseOver, bool isMouseDown) = 0;
  32905. /** Callback to indicate that the content area of this item has changed.
  32906. This might be because the component was resized, or because the style changed and
  32907. the space needed for the text label is different.
  32908. See getContentArea() for a description of what the area is.
  32909. */
  32910. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  32911. /** Editing modes.
  32912. These are used by setEditingMode(), but will be rarely needed in user code.
  32913. */
  32914. enum ToolbarEditingMode
  32915. {
  32916. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  32917. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  32918. customisation mode, and the items can be dragged around. */
  32919. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  32920. dragged onto a toolbar to add it to that bar.*/
  32921. };
  32922. /** Changes the editing mode of this component.
  32923. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32924. and is unlikely to be of much use in end-user-code.
  32925. */
  32926. void setEditingMode (const ToolbarEditingMode newMode);
  32927. /** Returns the current editing mode of this component.
  32928. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  32929. and is unlikely to be of much use in end-user-code.
  32930. */
  32931. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  32932. /** @internal */
  32933. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  32934. /** @internal */
  32935. void resized();
  32936. juce_UseDebuggingNewOperator
  32937. private:
  32938. friend class Toolbar;
  32939. friend class ItemDragAndDropOverlayComponent;
  32940. const int itemId;
  32941. ToolbarEditingMode mode;
  32942. Toolbar::ToolbarItemStyle toolbarStyle;
  32943. ScopedPointer <Component> overlayComp;
  32944. int dragOffsetX, dragOffsetY;
  32945. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  32946. Rectangle<int> contentArea;
  32947. ToolbarItemComponent (const ToolbarItemComponent&);
  32948. ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  32949. };
  32950. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  32951. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  32952. /**
  32953. A type of button designed to go on a toolbar.
  32954. This simple button can have two Drawable objects specified - one for normal
  32955. use and another one (optionally) for the button's "on" state if it's a
  32956. toggle button.
  32957. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  32958. */
  32959. class JUCE_API ToolbarButton : public ToolbarItemComponent
  32960. {
  32961. public:
  32962. /** Creates a ToolbarButton.
  32963. @param itemId the ID for this toolbar item type. This is passed through to the
  32964. ToolbarItemComponent constructor
  32965. @param labelText the text to display on the button (if the toolbar is using a style
  32966. that shows text labels). This is passed through to the
  32967. ToolbarItemComponent constructor
  32968. @param normalImage a drawable object that the button should use as its icon. The object
  32969. that is passed-in here will be kept by this object and will be
  32970. deleted when no longer needed or when this button is deleted.
  32971. @param toggledOnImage a drawable object that the button can use as its icon if the button
  32972. is in a toggled-on state (see the Button::getToggleState() method). If
  32973. 0 is passed-in here, then the normal image will be used instead, regardless
  32974. of the toggle state. The object that is passed-in here will be kept by
  32975. this object and will be deleted when no longer needed or when this button
  32976. is deleted.
  32977. */
  32978. ToolbarButton (int itemId,
  32979. const String& labelText,
  32980. Drawable* normalImage,
  32981. Drawable* toggledOnImage);
  32982. /** Destructor. */
  32983. ~ToolbarButton();
  32984. /** @internal */
  32985. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  32986. int& minSize, int& maxSize);
  32987. /** @internal */
  32988. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  32989. /** @internal */
  32990. void contentAreaChanged (const Rectangle<int>& newBounds);
  32991. juce_UseDebuggingNewOperator
  32992. private:
  32993. ScopedPointer <Drawable> normalImage, toggledOnImage;
  32994. ToolbarButton (const ToolbarButton&);
  32995. ToolbarButton& operator= (const ToolbarButton&);
  32996. };
  32997. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  32998. /*** End of inlined file: juce_ToolbarButton.h ***/
  32999. #endif
  33000. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33001. /*** Start of inlined file: juce_CodeDocument.h ***/
  33002. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33003. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  33004. class CodeDocumentLine;
  33005. /**
  33006. A class for storing and manipulating a source code file.
  33007. When using a CodeEditorComponent, it takes one of these as its source object.
  33008. The CodeDocument stores its content as an array of lines, which makes it
  33009. quick to insert and delete.
  33010. @see CodeEditorComponent
  33011. */
  33012. class JUCE_API CodeDocument
  33013. {
  33014. public:
  33015. /** Creates a new, empty document.
  33016. */
  33017. CodeDocument();
  33018. /** Destructor. */
  33019. ~CodeDocument();
  33020. /** A position in a code document.
  33021. Using this class you can find a position in a code document and quickly get its
  33022. character position, line, and index. By calling setPositionMaintained (true), the
  33023. position is automatically updated when text is inserted or deleted in the document,
  33024. so that it maintains its original place in the text.
  33025. */
  33026. class JUCE_API Position
  33027. {
  33028. public:
  33029. /** Creates an uninitialised postion.
  33030. Don't attempt to call any methods on this until you've given it an owner document
  33031. to refer to!
  33032. */
  33033. Position() throw();
  33034. /** Creates a position based on a line and index in a document.
  33035. Note that this index is NOT the column number, it's the number of characters from the
  33036. start of the line. The "column" number isn't quite the same, because if the line
  33037. contains any tab characters, the relationship of the index to its visual column depends on
  33038. the number of spaces per tab being used!
  33039. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33040. they will be adjusted to keep them within its limits.
  33041. */
  33042. Position (const CodeDocument* ownerDocument,
  33043. int line, int indexInLine) throw();
  33044. /** Creates a position based on a character index in a document.
  33045. This position is placed at the specified number of characters from the start of the
  33046. document. The line and column are auto-calculated.
  33047. If the position is beyond the range of the document, it'll be adjusted to keep it
  33048. inside.
  33049. */
  33050. Position (const CodeDocument* ownerDocument,
  33051. int charactersFromStartOfDocument) throw();
  33052. /** Creates a copy of another position.
  33053. This will copy the position, but the new object will not be set to maintain its position,
  33054. even if the source object was set to do so.
  33055. */
  33056. Position (const Position& other) throw();
  33057. /** Destructor. */
  33058. ~Position() throw();
  33059. Position& operator= (const Position& other) throw();
  33060. bool operator== (const Position& other) const throw();
  33061. bool operator!= (const Position& other) const throw();
  33062. /** Points this object at a new position within the document.
  33063. If the position is beyond the range of the document, it'll be adjusted to keep it
  33064. inside.
  33065. @see getPosition, setLineAndIndex
  33066. */
  33067. void setPosition (int charactersFromStartOfDocument) throw();
  33068. /** Returns the position as the number of characters from the start of the document.
  33069. @see setPosition, getLineNumber, getIndexInLine
  33070. */
  33071. int getPosition() const throw() { return characterPos; }
  33072. /** Moves the position to a new line and index within the line.
  33073. Note that the index is NOT the column at which the position appears in an editor.
  33074. If the line contains any tab characters, the relationship of the index to its
  33075. visual position depends on the number of spaces per tab being used!
  33076. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33077. they will be adjusted to keep them within its limits.
  33078. */
  33079. void setLineAndIndex (int newLine, int newIndexInLine) throw();
  33080. /** Returns the line number of this position.
  33081. The first line in the document is numbered zero, not one!
  33082. */
  33083. int getLineNumber() const throw() { return line; }
  33084. /** Returns the number of characters from the start of the line.
  33085. Note that this value is NOT the column at which the position appears in an editor.
  33086. If the line contains any tab characters, the relationship of the index to its
  33087. visual position depends on the number of spaces per tab being used!
  33088. */
  33089. int getIndexInLine() const throw() { return indexInLine; }
  33090. /** Allows the position to be automatically updated when the document changes.
  33091. If this is set to true, the positon will register with its document so that
  33092. when the document has text inserted or deleted, this position will be automatically
  33093. moved to keep it at the same position in the text.
  33094. */
  33095. void setPositionMaintained (bool isMaintained) throw();
  33096. /** Moves the position forwards or backwards by the specified number of characters.
  33097. @see movedBy
  33098. */
  33099. void moveBy (int characterDelta) throw();
  33100. /** Returns a position which is the same as this one, moved by the specified number of
  33101. characters.
  33102. @see moveBy
  33103. */
  33104. const Position movedBy (int characterDelta) const throw();
  33105. /** Returns a position which is the same as this one, moved up or down by the specified
  33106. number of lines.
  33107. @see movedBy
  33108. */
  33109. const Position movedByLines (int deltaLines) const throw();
  33110. /** Returns the character in the document at this position.
  33111. @see getLineText
  33112. */
  33113. const juce_wchar getCharacter() const throw();
  33114. /** Returns the line from the document that this position is within.
  33115. @see getCharacter, getLineNumber
  33116. */
  33117. const String getLineText() const throw();
  33118. private:
  33119. CodeDocument* owner;
  33120. int characterPos, line, indexInLine;
  33121. bool positionMaintained;
  33122. };
  33123. /** Returns the full text of the document. */
  33124. const String getAllContent() const throw();
  33125. /** Returns a section of the document's text. */
  33126. const String getTextBetween (const Position& start, const Position& end) const throw();
  33127. /** Returns a line from the document. */
  33128. const String getLine (int lineIndex) const throw();
  33129. /** Returns the number of characters in the document. */
  33130. int getNumCharacters() const throw();
  33131. /** Returns the number of lines in the document. */
  33132. int getNumLines() const throw() { return lines.size(); }
  33133. /** Returns the number of characters in the longest line of the document. */
  33134. int getMaximumLineLength() throw();
  33135. /** Deletes a section of the text.
  33136. This operation is undoable.
  33137. */
  33138. void deleteSection (const Position& startPosition, const Position& endPosition);
  33139. /** Inserts some text into the document at a given position.
  33140. This operation is undoable.
  33141. */
  33142. void insertText (const Position& position, const String& text);
  33143. /** Clears the document and replaces it with some new text.
  33144. This operation is undoable - if you're trying to completely reset the document, you
  33145. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  33146. */
  33147. void replaceAllContent (const String& newContent);
  33148. /** Replaces the editor's contents with the contents of a stream.
  33149. This will also reset the undo history and save point marker.
  33150. */
  33151. bool loadFromStream (InputStream& stream);
  33152. /** Writes the editor's current contents to a stream. */
  33153. bool writeToStream (OutputStream& stream);
  33154. /** Returns the preferred new-line characters for the document.
  33155. This will be either "\n", "\r\n", or (rarely) "\r".
  33156. @see setNewLineCharacters
  33157. */
  33158. const String getNewLineCharacters() const throw() { return newLineChars; }
  33159. /** Sets the new-line characters that the document should use.
  33160. The string must be either "\n", "\r\n", or (rarely) "\r".
  33161. @see getNewLineCharacters
  33162. */
  33163. void setNewLineCharacters (const String& newLine) throw();
  33164. /** Begins a new undo transaction.
  33165. The document itself will not call this internally, so relies on whatever is using the
  33166. document to periodically call this to break up the undo sequence into sensible chunks.
  33167. @see UndoManager::beginNewTransaction
  33168. */
  33169. void newTransaction();
  33170. /** Undo the last operation.
  33171. @see UndoManager::undo
  33172. */
  33173. void undo();
  33174. /** Redo the last operation.
  33175. @see UndoManager::redo
  33176. */
  33177. void redo();
  33178. /** Clears the undo history.
  33179. @see UndoManager::clearUndoHistory
  33180. */
  33181. void clearUndoHistory();
  33182. /** Returns the document's UndoManager */
  33183. UndoManager& getUndoManager() throw() { return undoManager; }
  33184. /** Makes a note that the document's current state matches the one that is saved.
  33185. After this has been called, hasChangedSinceSavePoint() will return false until
  33186. the document has been altered, and then it'll start returning true. If the document is
  33187. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  33188. will again return false.
  33189. @see hasChangedSinceSavePoint
  33190. */
  33191. void setSavePoint() throw();
  33192. /** Returns true if the state of the document differs from the state it was in when
  33193. setSavePoint() was last called.
  33194. @see setSavePoint
  33195. */
  33196. bool hasChangedSinceSavePoint() const throw();
  33197. /** Searches for a word-break. */
  33198. const Position findWordBreakAfter (const Position& position) const throw();
  33199. /** Searches for a word-break. */
  33200. const Position findWordBreakBefore (const Position& position) const throw();
  33201. /** An object that receives callbacks from the CodeDocument when its text changes.
  33202. @see CodeDocument::addListener, CodeDocument::removeListener
  33203. */
  33204. class JUCE_API Listener
  33205. {
  33206. public:
  33207. Listener() {}
  33208. virtual ~Listener() {}
  33209. /** Called by a CodeDocument when it is altered.
  33210. */
  33211. virtual void codeDocumentChanged (const Position& affectedTextStart,
  33212. const Position& affectedTextEnd) = 0;
  33213. };
  33214. /** Registers a listener object to receive callbacks when the document changes.
  33215. If the listener is already registered, this method has no effect.
  33216. @see removeListener
  33217. */
  33218. void addListener (Listener* listener) throw();
  33219. /** Deregisters a listener.
  33220. @see addListener
  33221. */
  33222. void removeListener (Listener* listener) throw();
  33223. /** Iterates the text in a CodeDocument.
  33224. This class lets you read characters from a CodeDocument. It's designed to be used
  33225. by a SyntaxAnalyser object.
  33226. @see CodeDocument, SyntaxAnalyser
  33227. */
  33228. class Iterator
  33229. {
  33230. public:
  33231. Iterator (CodeDocument* document);
  33232. Iterator (const Iterator& other);
  33233. Iterator& operator= (const Iterator& other) throw();
  33234. ~Iterator() throw();
  33235. /** Reads the next character and returns it.
  33236. @see peekNextChar
  33237. */
  33238. juce_wchar nextChar();
  33239. /** Reads the next character without advancing the current position. */
  33240. juce_wchar peekNextChar() const;
  33241. /** Advances the position by one character. */
  33242. void skip();
  33243. /** Returns the position of the next character as its position within the
  33244. whole document.
  33245. */
  33246. int getPosition() const throw() { return position; }
  33247. /** Skips over any whitespace characters until the next character is non-whitespace. */
  33248. void skipWhitespace();
  33249. /** Skips forward until the next character will be the first character on the next line */
  33250. void skipToEndOfLine();
  33251. /** Returns the line number of the next character. */
  33252. int getLine() const throw() { return line; }
  33253. /** Returns true if the iterator has reached the end of the document. */
  33254. bool isEOF() const throw();
  33255. private:
  33256. CodeDocument* document;
  33257. CodeDocumentLine* currentLine;
  33258. int line, position;
  33259. };
  33260. juce_UseDebuggingNewOperator
  33261. private:
  33262. friend class CodeDocumentInsertAction;
  33263. friend class CodeDocumentDeleteAction;
  33264. friend class Iterator;
  33265. friend class Position;
  33266. OwnedArray <CodeDocumentLine> lines;
  33267. Array <Position*> positionsToMaintain;
  33268. UndoManager undoManager;
  33269. int currentActionIndex, indexOfSavedState;
  33270. int maximumLineLength;
  33271. ListenerList <Listener> listeners;
  33272. String newLineChars;
  33273. void sendListenerChangeMessage (int startLine, int endLine);
  33274. void insert (const String& text, int insertPos, bool undoable);
  33275. void remove (int startPos, int endPos, bool undoable);
  33276. void checkLastLineStatus();
  33277. CodeDocument (const CodeDocument&);
  33278. CodeDocument& operator= (const CodeDocument&);
  33279. };
  33280. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  33281. /*** End of inlined file: juce_CodeDocument.h ***/
  33282. #endif
  33283. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33284. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  33285. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33286. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33287. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  33288. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33289. #define __JUCE_CODETOKENISER_JUCEHEADER__
  33290. /**
  33291. A base class for tokenising code so that the syntax can be displayed in a
  33292. code editor.
  33293. @see CodeDocument, CodeEditorComponent
  33294. */
  33295. class JUCE_API CodeTokeniser
  33296. {
  33297. public:
  33298. CodeTokeniser() {}
  33299. virtual ~CodeTokeniser() {}
  33300. /** Reads the next token from the source and returns its token type.
  33301. This must leave the source pointing to the first character in the
  33302. next token.
  33303. */
  33304. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  33305. /** Returns a list of the names of the token types this analyser uses.
  33306. The index in this list must match the token type numbers that are
  33307. returned by readNextToken().
  33308. */
  33309. virtual const StringArray getTokenTypes() = 0;
  33310. /** Returns a suggested syntax highlighting colour for a specified
  33311. token type.
  33312. */
  33313. virtual const Colour getDefaultColour (int tokenType) = 0;
  33314. juce_UseDebuggingNewOperator
  33315. };
  33316. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  33317. /*** End of inlined file: juce_CodeTokeniser.h ***/
  33318. /**
  33319. A text editor component designed specifically for source code.
  33320. This is designed to handle syntax highlighting and fast editing of very large
  33321. files.
  33322. */
  33323. class JUCE_API CodeEditorComponent : public Component,
  33324. public TextInputTarget,
  33325. public Timer,
  33326. public ScrollBarListener,
  33327. public CodeDocument::Listener,
  33328. public AsyncUpdater
  33329. {
  33330. public:
  33331. /** Creates an editor for a document.
  33332. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  33333. The object that you pass in is not owned or deleted by the editor - you must
  33334. make sure that it doesn't get deleted while this component is still using it.
  33335. @see CodeDocument
  33336. */
  33337. CodeEditorComponent (CodeDocument& document,
  33338. CodeTokeniser* codeTokeniser);
  33339. /** Destructor. */
  33340. ~CodeEditorComponent();
  33341. /** Returns the code document that this component is editing. */
  33342. CodeDocument& getDocument() const throw() { return document; }
  33343. /** Loads the given content into the document.
  33344. This will completely reset the CodeDocument object, clear its undo history,
  33345. and fill it with this text.
  33346. */
  33347. void loadContent (const String& newContent);
  33348. /** Returns the standard character width. */
  33349. float getCharWidth() const throw() { return charWidth; }
  33350. /** Returns the height of a line of text, in pixels. */
  33351. int getLineHeight() const throw() { return lineHeight; }
  33352. /** Returns the number of whole lines visible on the screen,
  33353. This doesn't include a cut-off line that might be visible at the bottom if the
  33354. component's height isn't an exact multiple of the line-height.
  33355. */
  33356. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  33357. /** Returns the number of whole columns visible on the screen.
  33358. This doesn't include any cut-off columns at the right-hand edge.
  33359. */
  33360. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  33361. /** Returns the current caret position. */
  33362. const CodeDocument::Position getCaretPos() const { return caretPos; }
  33363. /** Moves the caret.
  33364. If selecting is true, the section of the document between the current
  33365. caret position and the new one will become selected. If false, any currently
  33366. selected region will be deselected.
  33367. */
  33368. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  33369. /** Returns the on-screen position of a character in the document.
  33370. The rectangle returned is relative to this component's top-left origin.
  33371. */
  33372. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const throw();
  33373. /** Finds the character at a given on-screen position.
  33374. The co-ordinates are relative to this component's top-left origin.
  33375. */
  33376. const CodeDocument::Position getPositionAt (int x, int y);
  33377. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  33378. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  33379. void cursorDown (bool selecting);
  33380. void cursorUp (bool selecting);
  33381. void pageDown (bool selecting);
  33382. void pageUp (bool selecting);
  33383. void scrollDown();
  33384. void scrollUp();
  33385. void scrollToLine (int newFirstLineOnScreen);
  33386. void scrollBy (int deltaLines);
  33387. void scrollToColumn (int newFirstColumnOnScreen);
  33388. void scrollToKeepCaretOnScreen();
  33389. void goToStartOfDocument (bool selecting);
  33390. void goToStartOfLine (bool selecting);
  33391. void goToEndOfDocument (bool selecting);
  33392. void goToEndOfLine (bool selecting);
  33393. void deselectAll();
  33394. void selectAll();
  33395. void insertTextAtCaret (const String& textToInsert);
  33396. void insertTabAtCaret();
  33397. void cut();
  33398. void copy();
  33399. void copyThenCut();
  33400. void paste();
  33401. void backspace (bool moveInWholeWordSteps);
  33402. void deleteForward (bool moveInWholeWordSteps);
  33403. void undo();
  33404. void redo();
  33405. const Range<int> getHighlightedRegion() const;
  33406. void setHighlightedRegion (const Range<int>& newRange);
  33407. const String getTextInRange (const Range<int>& range) const;
  33408. /** Changes the current tab settings.
  33409. This lets you change the tab size and whether pressing the tab key inserts a
  33410. tab character, or its equivalent number of spaces.
  33411. */
  33412. void setTabSize (int numSpacesPerTab,
  33413. bool insertSpacesInsteadOfTabCharacters) throw();
  33414. /** Returns the current number of spaces per tab.
  33415. @see setTabSize
  33416. */
  33417. int getTabSize() const throw() { return spacesPerTab; }
  33418. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  33419. @see setTabSize
  33420. */
  33421. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  33422. /** Changes the font.
  33423. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  33424. */
  33425. void setFont (const Font& newFont);
  33426. /** Returns the font that the editor is using. */
  33427. const Font& getFont() const throw() { return font; }
  33428. /** Resets the syntax highlighting colours to the default ones provided by the
  33429. code tokeniser.
  33430. @see CodeTokeniser::getDefaultColour
  33431. */
  33432. void resetToDefaultColours();
  33433. /** Changes one of the syntax highlighting colours.
  33434. The token type values are dependent on the tokeniser being used - use
  33435. CodeTokeniser::getTokenTypes() to get a list of the token types.
  33436. @see getColourForTokenType
  33437. */
  33438. void setColourForTokenType (int tokenType, const Colour& colour);
  33439. /** Returns one of the syntax highlighting colours.
  33440. The token type values are dependent on the tokeniser being used - use
  33441. CodeTokeniser::getTokenTypes() to get a list of the token types.
  33442. @see setColourForTokenType
  33443. */
  33444. const Colour getColourForTokenType (int tokenType) const throw();
  33445. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  33446. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33447. methods.
  33448. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33449. */
  33450. enum ColourIds
  33451. {
  33452. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  33453. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  33454. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  33455. selected text. */
  33456. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  33457. enabled. */
  33458. };
  33459. /** Changes the size of the scrollbars. */
  33460. void setScrollbarThickness (int thickness) throw();
  33461. /** Returns the thickness of the scrollbars. */
  33462. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  33463. /** @internal */
  33464. void resized();
  33465. /** @internal */
  33466. void paint (Graphics& g);
  33467. /** @internal */
  33468. bool keyPressed (const KeyPress& key);
  33469. /** @internal */
  33470. void mouseDown (const MouseEvent& e);
  33471. /** @internal */
  33472. void mouseDrag (const MouseEvent& e);
  33473. /** @internal */
  33474. void mouseUp (const MouseEvent& e);
  33475. /** @internal */
  33476. void mouseDoubleClick (const MouseEvent& e);
  33477. /** @internal */
  33478. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  33479. /** @internal */
  33480. void focusGained (FocusChangeType cause);
  33481. /** @internal */
  33482. void focusLost (FocusChangeType cause);
  33483. /** @internal */
  33484. void timerCallback();
  33485. /** @internal */
  33486. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  33487. /** @internal */
  33488. void handleAsyncUpdate();
  33489. /** @internal */
  33490. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  33491. const CodeDocument::Position& affectedTextEnd);
  33492. /** @internal */
  33493. bool isTextInputActive() const;
  33494. juce_UseDebuggingNewOperator
  33495. private:
  33496. CodeDocument& document;
  33497. Font font;
  33498. int firstLineOnScreen, gutter, spacesPerTab;
  33499. float charWidth;
  33500. int lineHeight, linesOnScreen, columnsOnScreen;
  33501. int scrollbarThickness, columnToTryToMaintain;
  33502. bool useSpacesForTabs;
  33503. double xOffset;
  33504. CodeDocument::Position caretPos;
  33505. CodeDocument::Position selectionStart, selectionEnd;
  33506. class CaretComponent;
  33507. CaretComponent* caret;
  33508. ScrollBar* verticalScrollBar;
  33509. ScrollBar* horizontalScrollBar;
  33510. enum DragType
  33511. {
  33512. notDragging,
  33513. draggingSelectionStart,
  33514. draggingSelectionEnd
  33515. };
  33516. DragType dragType;
  33517. CodeTokeniser* codeTokeniser;
  33518. Array <Colour> coloursForTokenCategories;
  33519. class CodeEditorLine;
  33520. OwnedArray <CodeEditorLine> lines;
  33521. void rebuildLineTokens();
  33522. OwnedArray <CodeDocument::Iterator> cachedIterators;
  33523. void clearCachedIterators (int firstLineToBeInvalid) throw();
  33524. void updateCachedIterators (int maxLineNum);
  33525. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  33526. void moveLineDelta (int delta, bool selecting);
  33527. void updateScrollBars();
  33528. void scrollToLineInternal (int line);
  33529. void scrollToColumnInternal (double column);
  33530. void newTransaction();
  33531. int indexToColumn (int line, int index) const throw();
  33532. int columnToIndex (int line, int column) const throw();
  33533. CodeEditorComponent (const CodeEditorComponent&);
  33534. CodeEditorComponent& operator= (const CodeEditorComponent&);
  33535. };
  33536. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  33537. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  33538. #endif
  33539. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  33540. #endif
  33541. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33542. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  33543. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33544. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33545. /**
  33546. A simple lexical analyser for syntax colouring of C++ code.
  33547. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  33548. */
  33549. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  33550. {
  33551. public:
  33552. CPlusPlusCodeTokeniser();
  33553. ~CPlusPlusCodeTokeniser();
  33554. enum TokenType
  33555. {
  33556. tokenType_error = 0,
  33557. tokenType_comment,
  33558. tokenType_builtInKeyword,
  33559. tokenType_identifier,
  33560. tokenType_integerLiteral,
  33561. tokenType_floatLiteral,
  33562. tokenType_stringLiteral,
  33563. tokenType_operator,
  33564. tokenType_bracket,
  33565. tokenType_punctuation,
  33566. tokenType_preprocessor
  33567. };
  33568. int readNextToken (CodeDocument::Iterator& source);
  33569. const StringArray getTokenTypes();
  33570. const Colour getDefaultColour (int tokenType);
  33571. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  33572. static bool isReservedKeyword (const String& token) throw();
  33573. juce_UseDebuggingNewOperator
  33574. };
  33575. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  33576. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  33577. #endif
  33578. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  33579. #endif
  33580. #ifndef __JUCE_LABEL_JUCEHEADER__
  33581. #endif
  33582. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  33583. #endif
  33584. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33585. /*** Start of inlined file: juce_ProgressBar.h ***/
  33586. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  33587. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  33588. /**
  33589. A progress bar component.
  33590. To use this, just create one and make it visible. It'll run its own timer
  33591. to keep an eye on a variable that you give it, and will automatically
  33592. redraw itself when the variable changes.
  33593. For an easy way of running a background task with a dialog box showing its
  33594. progress, see the ThreadWithProgressWindow class.
  33595. @see ThreadWithProgressWindow
  33596. */
  33597. class JUCE_API ProgressBar : public Component,
  33598. public SettableTooltipClient,
  33599. private Timer
  33600. {
  33601. public:
  33602. /** Creates a ProgressBar.
  33603. @param progress pass in a reference to a double that you're going to
  33604. update with your task's progress. The ProgressBar will
  33605. monitor the value of this variable and will redraw itself
  33606. when the value changes. The range is from 0 to 1.0. Obviously
  33607. you'd better be careful not to delete this variable while the
  33608. ProgressBar still exists!
  33609. */
  33610. explicit ProgressBar (double& progress);
  33611. /** Destructor. */
  33612. ~ProgressBar();
  33613. /** Turns the percentage display on or off.
  33614. By default this is on, and the progress bar will display a text string showing
  33615. its current percentage.
  33616. */
  33617. void setPercentageDisplay (const bool shouldDisplayPercentage);
  33618. /** Gives the progress bar a string to display inside it.
  33619. If you call this, it will turn off the percentage display.
  33620. @see setPercentageDisplay
  33621. */
  33622. void setTextToDisplay (const String& text);
  33623. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  33624. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33625. methods.
  33626. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33627. */
  33628. enum ColourIds
  33629. {
  33630. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  33631. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  33632. classes will probably use variations on this colour. */
  33633. };
  33634. juce_UseDebuggingNewOperator
  33635. protected:
  33636. /** @internal */
  33637. void paint (Graphics& g);
  33638. /** @internal */
  33639. void lookAndFeelChanged();
  33640. /** @internal */
  33641. void visibilityChanged();
  33642. /** @internal */
  33643. void colourChanged();
  33644. private:
  33645. double& progress;
  33646. double currentValue;
  33647. bool displayPercentage;
  33648. String displayedMessage, currentMessage;
  33649. uint32 lastCallbackTime;
  33650. void timerCallback();
  33651. ProgressBar (const ProgressBar&);
  33652. ProgressBar& operator= (const ProgressBar&);
  33653. };
  33654. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  33655. /*** End of inlined file: juce_ProgressBar.h ***/
  33656. #endif
  33657. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33658. /*** Start of inlined file: juce_Slider.h ***/
  33659. #ifndef __JUCE_SLIDER_JUCEHEADER__
  33660. #define __JUCE_SLIDER_JUCEHEADER__
  33661. /*** Start of inlined file: juce_SliderListener.h ***/
  33662. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  33663. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  33664. class Slider;
  33665. /**
  33666. A class for receiving callbacks from a Slider.
  33667. To be told when a slider's value changes, you can register a SliderListener
  33668. object using Slider::addListener().
  33669. @see Slider::addListener, Slider::removeListener
  33670. */
  33671. class JUCE_API SliderListener
  33672. {
  33673. public:
  33674. /** Destructor. */
  33675. virtual ~SliderListener() {}
  33676. /** Called when the slider's value is changed.
  33677. This may be caused by dragging it, or by typing in its text entry box,
  33678. or by a call to Slider::setValue().
  33679. You can find out the new value using Slider::getValue().
  33680. @see Slider::valueChanged
  33681. */
  33682. virtual void sliderValueChanged (Slider* slider) = 0;
  33683. /** Called when the slider is about to be dragged.
  33684. This is called when a drag begins, then it's followed by multiple calls
  33685. to sliderValueChanged(), and then sliderDragEnded() is called after the
  33686. user lets go.
  33687. @see sliderDragEnded, Slider::startedDragging
  33688. */
  33689. virtual void sliderDragStarted (Slider* slider);
  33690. /** Called after a drag operation has finished.
  33691. @see sliderDragStarted, Slider::stoppedDragging
  33692. */
  33693. virtual void sliderDragEnded (Slider* slider);
  33694. };
  33695. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  33696. /*** End of inlined file: juce_SliderListener.h ***/
  33697. /**
  33698. A slider control for changing a value.
  33699. The slider can be horizontal, vertical, or rotary, and can optionally have
  33700. a text-box inside it to show an editable display of the current value.
  33701. To use it, create a Slider object and use the setSliderStyle() method
  33702. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  33703. To define the values that it can be set to, see the setRange() and setValue() methods.
  33704. There are also lots of custom tweaks you can do by subclassing and overriding
  33705. some of the virtual methods, such as changing the scaling, changing the format of
  33706. the text display, custom ways of limiting the values, etc.
  33707. You can register SliderListeners with a slider, which will be informed when the value
  33708. changes, or a subclass can override valueChanged() to be informed synchronously.
  33709. @see SliderListener
  33710. */
  33711. class JUCE_API Slider : public Component,
  33712. public SettableTooltipClient,
  33713. private AsyncUpdater,
  33714. private ButtonListener,
  33715. private LabelListener,
  33716. private Value::Listener
  33717. {
  33718. public:
  33719. /** Creates a slider.
  33720. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  33721. setRange(), etc.
  33722. */
  33723. explicit Slider (const String& componentName = String::empty);
  33724. /** Destructor. */
  33725. ~Slider();
  33726. /** The types of slider available.
  33727. @see setSliderStyle, setRotaryParameters
  33728. */
  33729. enum SliderStyle
  33730. {
  33731. LinearHorizontal, /**< A traditional horizontal slider. */
  33732. LinearVertical, /**< A traditional vertical slider. */
  33733. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  33734. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  33735. @see setRotaryParameters */
  33736. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  33737. @see setRotaryParameters */
  33738. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  33739. @see setRotaryParameters */
  33740. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  33741. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33742. @see setMinValue, setMaxValue */
  33743. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  33744. @see setMinValue, setMaxValue */
  33745. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  33746. value, with the current value being somewhere between them.
  33747. @see setMinValue, setMaxValue */
  33748. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  33749. value, with the current value being somewhere between them.
  33750. @see setMinValue, setMaxValue */
  33751. };
  33752. /** Changes the type of slider interface being used.
  33753. @param newStyle the type of interface
  33754. @see setRotaryParameters, setVelocityBasedMode,
  33755. */
  33756. void setSliderStyle (SliderStyle newStyle);
  33757. /** Returns the slider's current style.
  33758. @see setSliderStyle
  33759. */
  33760. SliderStyle getSliderStyle() const { return style; }
  33761. /** Changes the properties of a rotary slider.
  33762. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  33763. the slider's minimum value is represented
  33764. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  33765. the slider's maximum value is represented. This must be
  33766. greater than startAngleRadians
  33767. @param stopAtEnd if true, then when the slider is dragged around past the
  33768. minimum or maximum, it'll stop there; if false, it'll wrap
  33769. back to the opposite value
  33770. */
  33771. void setRotaryParameters (float startAngleRadians,
  33772. float endAngleRadians,
  33773. bool stopAtEnd);
  33774. /** Sets the distance the mouse has to move to drag the slider across
  33775. the full extent of its range.
  33776. This only applies when in modes like RotaryHorizontalDrag, where it's using
  33777. relative mouse movements to adjust the slider.
  33778. */
  33779. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  33780. /** Changes the way the the mouse is used when dragging the slider.
  33781. If true, this will turn on velocity-sensitive dragging, so that
  33782. the faster the mouse moves, the bigger the movement to the slider. This
  33783. helps when making accurate adjustments if the slider's range is quite large.
  33784. If false, the slider will just try to snap to wherever the mouse is.
  33785. */
  33786. void setVelocityBasedMode (bool isVelocityBased);
  33787. /** Returns true if velocity-based mode is active.
  33788. @see setVelocityBasedMode
  33789. */
  33790. bool getVelocityBasedMode() const { return isVelocityBased; }
  33791. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  33792. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  33793. or if you're holding down ctrl.
  33794. @param sensitivity higher values than 1.0 increase the range of acceleration used
  33795. @param threshold the minimum number of pixels that the mouse needs to move for it
  33796. to be treated as a movement
  33797. @param offset values greater than 0.0 increase the minimum speed that will be used when
  33798. the threshold is reached
  33799. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  33800. key to toggle velocity-sensitive mode
  33801. */
  33802. void setVelocityModeParameters (double sensitivity = 1.0,
  33803. int threshold = 1,
  33804. double offset = 0.0,
  33805. bool userCanPressKeyToSwapMode = true);
  33806. /** Returns the velocity sensitivity setting.
  33807. @see setVelocityModeParameters
  33808. */
  33809. double getVelocitySensitivity() const { return velocityModeSensitivity; }
  33810. /** Returns the velocity threshold setting.
  33811. @see setVelocityModeParameters
  33812. */
  33813. int getVelocityThreshold() const { return velocityModeThreshold; }
  33814. /** Returns the velocity offset setting.
  33815. @see setVelocityModeParameters
  33816. */
  33817. double getVelocityOffset() const { return velocityModeOffset; }
  33818. /** Returns the velocity user key setting.
  33819. @see setVelocityModeParameters
  33820. */
  33821. bool getVelocityModeIsSwappable() const { return userKeyOverridesVelocity; }
  33822. /** Sets up a skew factor to alter the way values are distributed.
  33823. You may want to use a range of values on the slider where more accuracy
  33824. is required towards one end of the range, so this will logarithmically
  33825. spread the values across the length of the slider.
  33826. If the factor is < 1.0, the lower end of the range will fill more of the
  33827. slider's length; if the factor is > 1.0, the upper end of the range
  33828. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  33829. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  33830. method instead.
  33831. @see getSkewFactor, setSkewFactorFromMidPoint
  33832. */
  33833. void setSkewFactor (double factor);
  33834. /** Sets up a skew factor to alter the way values are distributed.
  33835. This allows you to specify the slider value that should appear in the
  33836. centre of the slider's visible range.
  33837. @see setSkewFactor, getSkewFactor
  33838. */
  33839. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  33840. /** Returns the current skew factor.
  33841. See setSkewFactor for more info.
  33842. @see setSkewFactor, setSkewFactorFromMidPoint
  33843. */
  33844. double getSkewFactor() const { return skewFactor; }
  33845. /** Used by setIncDecButtonsMode().
  33846. */
  33847. enum IncDecButtonMode
  33848. {
  33849. incDecButtonsNotDraggable,
  33850. incDecButtonsDraggable_AutoDirection,
  33851. incDecButtonsDraggable_Horizontal,
  33852. incDecButtonsDraggable_Vertical
  33853. };
  33854. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  33855. can be dragged on the buttons to drag the values.
  33856. By default this is turned off. When enabled, clicking on the buttons still works
  33857. them as normal, but by holding down the mouse on a button and dragging it a little
  33858. distance, it flips into a mode where the value can be dragged. The drag direction can
  33859. either be set explicitly to be vertical or horizontal, or can be set to
  33860. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  33861. are side-by-side or above each other.
  33862. */
  33863. void setIncDecButtonsMode (IncDecButtonMode mode);
  33864. /** The position of the slider's text-entry box.
  33865. @see setTextBoxStyle
  33866. */
  33867. enum TextEntryBoxPosition
  33868. {
  33869. NoTextBox, /**< Doesn't display a text box. */
  33870. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  33871. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  33872. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  33873. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  33874. };
  33875. /** Changes the location and properties of the text-entry box.
  33876. @param newPosition where it should go (or NoTextBox to not have one at all)
  33877. @param isReadOnly if true, it's a read-only display
  33878. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  33879. room for the slider as well!
  33880. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  33881. room for the slider as well!
  33882. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  33883. */
  33884. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  33885. bool isReadOnly,
  33886. int textEntryBoxWidth,
  33887. int textEntryBoxHeight);
  33888. /** Returns the status of the text-box.
  33889. @see setTextBoxStyle
  33890. */
  33891. const TextEntryBoxPosition getTextBoxPosition() const { return textBoxPos; }
  33892. /** Returns the width used for the text-box.
  33893. @see setTextBoxStyle
  33894. */
  33895. int getTextBoxWidth() const { return textBoxWidth; }
  33896. /** Returns the height used for the text-box.
  33897. @see setTextBoxStyle
  33898. */
  33899. int getTextBoxHeight() const { return textBoxHeight; }
  33900. /** Makes the text-box editable.
  33901. By default this is true, and the user can enter values into the textbox,
  33902. but it can be turned off if that's not suitable.
  33903. @see setTextBoxStyle, getValueFromText, getTextFromValue
  33904. */
  33905. void setTextBoxIsEditable (bool shouldBeEditable);
  33906. /** Returns true if the text-box is read-only.
  33907. @see setTextBoxStyle
  33908. */
  33909. bool isTextBoxEditable() const { return editableText; }
  33910. /** If the text-box is editable, this will give it the focus so that the user can
  33911. type directly into it.
  33912. This is basically the effect as the user clicking on it.
  33913. */
  33914. void showTextBox();
  33915. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  33916. focus away from it.
  33917. @param discardCurrentEditorContents if true, the slider's value will be left
  33918. unchanged; if false, the current contents of the
  33919. text editor will be used to set the slider position
  33920. before it is hidden.
  33921. */
  33922. void hideTextBox (bool discardCurrentEditorContents);
  33923. /** Changes the slider's current value.
  33924. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33925. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33926. want to handle it.
  33927. @param newValue the new value to set - this will be restricted by the
  33928. minimum and maximum range, and will be snapped to the
  33929. nearest interval if one has been set
  33930. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33931. any SliderListeners or the valueChanged() method
  33932. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33933. synchronously; if false, it will be asynchronous
  33934. */
  33935. void setValue (double newValue,
  33936. bool sendUpdateMessage = true,
  33937. bool sendMessageSynchronously = false);
  33938. /** Returns the slider's current value. */
  33939. double getValue() const;
  33940. /** Returns the Value object that represents the slider's current position.
  33941. You can use this Value object to connect the slider's position to external values or setters,
  33942. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  33943. your own Value object.
  33944. @see Value, getMaxValue, getMinValueObject
  33945. */
  33946. Value& getValueObject() { return currentValue; }
  33947. /** Sets the limits that the slider's value can take.
  33948. @param newMinimum the lowest value allowed
  33949. @param newMaximum the highest value allowed
  33950. @param newInterval the steps in which the value is allowed to increase - if this
  33951. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  33952. */
  33953. void setRange (double newMinimum,
  33954. double newMaximum,
  33955. double newInterval = 0);
  33956. /** Returns the current maximum value.
  33957. @see setRange
  33958. */
  33959. double getMaximum() const { return maximum; }
  33960. /** Returns the current minimum value.
  33961. @see setRange
  33962. */
  33963. double getMinimum() const { return minimum; }
  33964. /** Returns the current step-size for values.
  33965. @see setRange
  33966. */
  33967. double getInterval() const { return interval; }
  33968. /** For a slider with two or three thumbs, this returns the lower of its values.
  33969. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  33970. A slider with three values also uses the normal getValue() and setValue() methods to
  33971. control the middle value.
  33972. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  33973. */
  33974. double getMinValue() const;
  33975. /** For a slider with two or three thumbs, this returns the lower of its values.
  33976. You can use this Value object to connect the slider's position to external values or setters,
  33977. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  33978. your own Value object.
  33979. @see Value, getMinValue, getMaxValueObject
  33980. */
  33981. Value& getMinValueObject() { return valueMin; }
  33982. /** For a slider with two or three thumbs, this sets the lower of its values.
  33983. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  33984. that are registered, and will synchronously call the valueChanged() method in case subclasses
  33985. want to handle it.
  33986. @param newValue the new value to set - this will be restricted by the
  33987. minimum and maximum range, and will be snapped to the nearest
  33988. interval if one has been set.
  33989. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  33990. any SliderListeners or the valueChanged() method
  33991. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  33992. synchronously; if false, it will be asynchronous
  33993. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  33994. max value (in a two-value slider) or the mid value (in a three-value
  33995. slider). If false, then if this value goes beyond those values,
  33996. it will push them along with it.
  33997. @see getMinValue, setMaxValue, setValue
  33998. */
  33999. void setMinValue (double newValue,
  34000. bool sendUpdateMessage = true,
  34001. bool sendMessageSynchronously = false,
  34002. bool allowNudgingOfOtherValues = false);
  34003. /** For a slider with two or three thumbs, this returns the higher of its values.
  34004. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34005. A slider with three values also uses the normal getValue() and setValue() methods to
  34006. control the middle value.
  34007. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34008. */
  34009. double getMaxValue() const;
  34010. /** For a slider with two or three thumbs, this returns the higher of its values.
  34011. You can use this Value object to connect the slider's position to external values or setters,
  34012. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34013. your own Value object.
  34014. @see Value, getMaxValue, getMinValueObject
  34015. */
  34016. Value& getMaxValueObject() { return valueMax; }
  34017. /** For a slider with two or three thumbs, this sets the lower of its values.
  34018. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34019. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34020. want to handle it.
  34021. @param newValue the new value to set - this will be restricted by the
  34022. minimum and maximum range, and will be snapped to the nearest
  34023. interval if one has been set.
  34024. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34025. any SliderListeners or the valueChanged() method
  34026. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34027. synchronously; if false, it will be asynchronous
  34028. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34029. min value (in a two-value slider) or the mid value (in a three-value
  34030. slider). If false, then if this value goes beyond those values,
  34031. it will push them along with it.
  34032. @see getMaxValue, setMinValue, setValue
  34033. */
  34034. void setMaxValue (double newValue,
  34035. bool sendUpdateMessage = true,
  34036. bool sendMessageSynchronously = false,
  34037. bool allowNudgingOfOtherValues = false);
  34038. /** Adds a listener to be called when this slider's value changes. */
  34039. void addListener (SliderListener* listener);
  34040. /** Removes a previously-registered listener. */
  34041. void removeListener (SliderListener* listener);
  34042. /** This lets you choose whether double-clicking moves the slider to a given position.
  34043. By default this is turned off, but it's handy if you want a double-click to act
  34044. as a quick way of resetting a slider. Just pass in the value you want it to
  34045. go to when double-clicked.
  34046. @see getDoubleClickReturnValue
  34047. */
  34048. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  34049. double valueToSetOnDoubleClick);
  34050. /** Returns the values last set by setDoubleClickReturnValue() method.
  34051. Sets isEnabled to true if double-click is enabled, and returns the value
  34052. that was set.
  34053. @see setDoubleClickReturnValue
  34054. */
  34055. double getDoubleClickReturnValue (bool& isEnabled) const;
  34056. /** Tells the slider whether to keep sending change messages while the user
  34057. is dragging the slider.
  34058. If set to true, a change message will only be sent when the user has
  34059. dragged the slider and let go. If set to false (the default), then messages
  34060. will be continuously sent as they drag it while the mouse button is still
  34061. held down.
  34062. */
  34063. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  34064. /** This lets you change whether the slider thumb jumps to the mouse position
  34065. when you click.
  34066. By default, this is true. If it's false, then the slider moves with relative
  34067. motion when you drag it.
  34068. This only applies to linear bars, and won't affect two- or three- value
  34069. sliders.
  34070. */
  34071. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  34072. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34073. slider is being dragged.
  34074. This can be handy if your slider doesn't have a text-box, so that users can
  34075. see the value just when they're changing it.
  34076. If you pass a component as the parentComponentToUse parameter, the pop-up
  34077. bubble will be added as a child of that component when it's needed. If you
  34078. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34079. transparent window, so if you're using an OS that can't do transparent windows
  34080. you'll have to add it to a parent component instead).
  34081. */
  34082. void setPopupDisplayEnabled (bool isEnabled,
  34083. Component* parentComponentToUse);
  34084. /** If this is set to true, then right-clicking on the slider will pop-up
  34085. a menu to let the user change the way it works.
  34086. By default this is turned off, but when turned on, the menu will include
  34087. things like velocity sensitivity, and for rotary sliders, whether they
  34088. use a linear or rotary mouse-drag to move them.
  34089. */
  34090. void setPopupMenuEnabled (bool menuEnabled);
  34091. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34092. By default it's enabled.
  34093. */
  34094. void setScrollWheelEnabled (bool enabled);
  34095. /** Returns a number to indicate which thumb is currently being dragged by the
  34096. mouse.
  34097. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34098. the maximum-value thumb, or -1 if none is currently down.
  34099. */
  34100. int getThumbBeingDragged() const { return sliderBeingDragged; }
  34101. /** Callback to indicate that the user is about to start dragging the slider.
  34102. @see SliderListener::sliderDragStarted
  34103. */
  34104. virtual void startedDragging();
  34105. /** Callback to indicate that the user has just stopped dragging the slider.
  34106. @see SliderListener::sliderDragEnded
  34107. */
  34108. virtual void stoppedDragging();
  34109. /** Callback to indicate that the user has just moved the slider.
  34110. @see SliderListener::sliderValueChanged
  34111. */
  34112. virtual void valueChanged();
  34113. /** Subclasses can override this to convert a text string to a value.
  34114. When the user enters something into the text-entry box, this method is
  34115. called to convert it to a value.
  34116. The default routine just tries to convert it to a double.
  34117. @see getTextFromValue
  34118. */
  34119. virtual double getValueFromText (const String& text);
  34120. /** Turns the slider's current value into a text string.
  34121. Subclasses can override this to customise the formatting of the text-entry box.
  34122. The default implementation just turns the value into a string, using
  34123. a number of decimal places based on the range interval. If a suffix string
  34124. has been set using setTextValueSuffix(), this will be appended to the text.
  34125. @see getValueFromText
  34126. */
  34127. virtual const String getTextFromValue (double value);
  34128. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34129. a string.
  34130. This is used by the default implementation of getTextFromValue(), and is just
  34131. appended to the numeric value. For more advanced formatting, you can override
  34132. getTextFromValue() and do something else.
  34133. */
  34134. void setTextValueSuffix (const String& suffix);
  34135. /** Returns the suffix that was set by setTextValueSuffix(). */
  34136. const String getTextValueSuffix() const;
  34137. /** Allows a user-defined mapping of distance along the slider to its value.
  34138. The default implementation for this performs the skewing operation that
  34139. can be set up in the setSkewFactor() method. Override it if you need
  34140. some kind of custom mapping instead, but make sure you also implement the
  34141. inverse function in valueToProportionOfLength().
  34142. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34143. @returns the slider value that is represented by this position
  34144. @see valueToProportionOfLength
  34145. */
  34146. virtual double proportionOfLengthToValue (double proportion);
  34147. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34148. The default implementation for this performs the skewing operation that
  34149. can be set up in the setSkewFactor() method. Override it if you need
  34150. some kind of custom mapping instead, but make sure you also implement the
  34151. inverse function in proportionOfLengthToValue().
  34152. @param value a valid slider value, between the range of values specified in
  34153. setRange()
  34154. @returns a value 0 to 1.0 indicating the distance along the slider that
  34155. represents this value
  34156. @see proportionOfLengthToValue
  34157. */
  34158. virtual double valueToProportionOfLength (double value);
  34159. /** Returns the X or Y coordinate of a value along the slider's length.
  34160. If the slider is horizontal, this will be the X coordinate of the given
  34161. value, relative to the left of the slider. If it's vertical, then this will
  34162. be the Y coordinate, relative to the top of the slider.
  34163. If the slider is rotary, this will throw an assertion and return 0. If the
  34164. value is out-of-range, it will be constrained to the length of the slider.
  34165. */
  34166. float getPositionOfValue (double value);
  34167. /** This can be overridden to allow the slider to snap to user-definable values.
  34168. If overridden, it will be called when the user tries to move the slider to
  34169. a given position, and allows a subclass to sanity-check this value, possibly
  34170. returning a different value to use instead.
  34171. @param attemptedValue the value the user is trying to enter
  34172. @param userIsDragging true if the user is dragging with the mouse; false if
  34173. they are entering the value using the text box
  34174. @returns the value to use instead
  34175. */
  34176. virtual double snapValue (double attemptedValue, bool userIsDragging);
  34177. /** This can be called to force the text box to update its contents.
  34178. (Not normally needed, as this is done automatically).
  34179. */
  34180. void updateText();
  34181. /** True if the slider moves horizontally. */
  34182. bool isHorizontal() const;
  34183. /** True if the slider moves vertically. */
  34184. bool isVertical() const;
  34185. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34186. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34187. methods.
  34188. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34189. */
  34190. enum ColourIds
  34191. {
  34192. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34193. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34194. and feel class how this is used. */
  34195. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34196. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34197. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34198. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34199. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34200. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34201. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34202. };
  34203. juce_UseDebuggingNewOperator
  34204. protected:
  34205. /** @internal */
  34206. void labelTextChanged (Label*);
  34207. /** @internal */
  34208. void paint (Graphics& g);
  34209. /** @internal */
  34210. void resized();
  34211. /** @internal */
  34212. void mouseDown (const MouseEvent& e);
  34213. /** @internal */
  34214. void mouseUp (const MouseEvent& e);
  34215. /** @internal */
  34216. void mouseDrag (const MouseEvent& e);
  34217. /** @internal */
  34218. void mouseDoubleClick (const MouseEvent& e);
  34219. /** @internal */
  34220. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34221. /** @internal */
  34222. void modifierKeysChanged (const ModifierKeys& modifiers);
  34223. /** @internal */
  34224. void buttonClicked (Button* button);
  34225. /** @internal */
  34226. void lookAndFeelChanged();
  34227. /** @internal */
  34228. void enablementChanged();
  34229. /** @internal */
  34230. void focusOfChildComponentChanged (FocusChangeType cause);
  34231. /** @internal */
  34232. void handleAsyncUpdate();
  34233. /** @internal */
  34234. void colourChanged();
  34235. /** @internal */
  34236. void valueChanged (Value& value);
  34237. /** Returns the best number of decimal places to use when displaying numbers.
  34238. This is calculated from the slider's interval setting.
  34239. */
  34240. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  34241. private:
  34242. ListenerList <SliderListener> listeners;
  34243. Value currentValue, valueMin, valueMax;
  34244. double lastCurrentValue, lastValueMin, lastValueMax;
  34245. double minimum, maximum, interval, doubleClickReturnValue;
  34246. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  34247. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  34248. int velocityModeThreshold;
  34249. float rotaryStart, rotaryEnd;
  34250. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  34251. int mouseDragStartX, mouseDragStartY;
  34252. int sliderRegionStart, sliderRegionSize;
  34253. int sliderBeingDragged;
  34254. int pixelsForFullDragExtent;
  34255. Rectangle<int> sliderRect;
  34256. String textSuffix;
  34257. SliderStyle style;
  34258. TextEntryBoxPosition textBoxPos;
  34259. int textBoxWidth, textBoxHeight;
  34260. IncDecButtonMode incDecButtonMode;
  34261. bool editableText : 1, doubleClickToValue : 1;
  34262. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  34263. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  34264. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  34265. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  34266. Label* valueBox;
  34267. Button* incButton;
  34268. Button* decButton;
  34269. ScopedPointer <Component> popupDisplay;
  34270. Component* parentForPopupDisplay;
  34271. float getLinearSliderPos (double value);
  34272. void restoreMouseIfHidden();
  34273. void sendDragStart();
  34274. void sendDragEnd();
  34275. double constrainedValue (double value) const;
  34276. void triggerChangeMessage (bool synchronous);
  34277. bool incDecDragDirectionIsHorizontal() const;
  34278. Slider (const Slider&);
  34279. Slider& operator= (const Slider&);
  34280. };
  34281. #endif // __JUCE_SLIDER_JUCEHEADER__
  34282. /*** End of inlined file: juce_Slider.h ***/
  34283. #endif
  34284. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34285. #endif
  34286. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34287. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  34288. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34289. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34290. class TableHeaderComponent;
  34291. /**
  34292. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  34293. You can register one of these objects for table events using TableHeaderComponent::addListener()
  34294. and TableHeaderComponent::removeListener().
  34295. @see TableHeaderComponent
  34296. */
  34297. class JUCE_API TableHeaderListener
  34298. {
  34299. public:
  34300. TableHeaderListener() {}
  34301. /** Destructor. */
  34302. virtual ~TableHeaderListener() {}
  34303. /** This is called when some of the table's columns are added, removed, hidden,
  34304. or rearranged.
  34305. */
  34306. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  34307. /** This is called when one or more of the table's columns are resized.
  34308. */
  34309. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  34310. /** This is called when the column by which the table should be sorted is changed.
  34311. */
  34312. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  34313. /** This is called when the user begins or ends dragging one of the columns around.
  34314. When the user starts dragging a column, this is called with the ID of that
  34315. column. When they finish dragging, it is called again with 0 as the ID.
  34316. */
  34317. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  34318. int columnIdNowBeingDragged);
  34319. };
  34320. /**
  34321. A component that displays a strip of column headings for a table, and allows these
  34322. to be resized, dragged around, etc.
  34323. This is just the component that goes at the top of a table. You can use it
  34324. directly for custom components, or to create a simple table, use the
  34325. TableListBox class.
  34326. To use one of these, create it and use addColumn() to add all the columns that you need.
  34327. Each column must be given a unique ID number that's used to refer to it.
  34328. @see TableListBox, TableHeaderListener
  34329. */
  34330. class JUCE_API TableHeaderComponent : public Component,
  34331. private AsyncUpdater
  34332. {
  34333. public:
  34334. /** Creates an empty table header.
  34335. */
  34336. TableHeaderComponent();
  34337. /** Destructor. */
  34338. ~TableHeaderComponent();
  34339. /** A combination of these flags are passed into the addColumn() method to specify
  34340. the properties of a column.
  34341. */
  34342. enum ColumnPropertyFlags
  34343. {
  34344. 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. */
  34345. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  34346. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  34347. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  34348. 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. */
  34349. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  34350. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  34351. /** This set of default flags is used as the default parameter value in addColumn(). */
  34352. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  34353. /** A quick way of combining flags for a column that's not resizable. */
  34354. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  34355. /** A quick way of combining flags for a column that's not resizable or sortable. */
  34356. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  34357. /** A quick way of combining flags for a column that's not sortable. */
  34358. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  34359. };
  34360. /** Adds a column to the table.
  34361. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  34362. registered listeners.
  34363. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  34364. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  34365. a unique ID. This is used to identify the column later on, after the user may have
  34366. changed the order that they appear in
  34367. @param width the initial width of the column, in pixels
  34368. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  34369. if the 'resizable' flag is specified for this column
  34370. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  34371. if the 'resizable' flag is specified for this column
  34372. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  34373. properties of this column
  34374. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  34375. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  34376. all columns, not just the index amongst those that are currently visible
  34377. */
  34378. void addColumn (const String& columnName,
  34379. int columnId,
  34380. int width,
  34381. int minimumWidth = 30,
  34382. int maximumWidth = -1,
  34383. int propertyFlags = defaultFlags,
  34384. int insertIndex = -1);
  34385. /** Removes a column with the given ID.
  34386. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  34387. registered listeners.
  34388. */
  34389. void removeColumn (int columnIdToRemove);
  34390. /** Deletes all columns from the table.
  34391. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  34392. registered listeners.
  34393. */
  34394. void removeAllColumns();
  34395. /** Returns the number of columns in the table.
  34396. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  34397. return the total number of columns, including hidden ones.
  34398. @see isColumnVisible
  34399. */
  34400. int getNumColumns (bool onlyCountVisibleColumns) const;
  34401. /** Returns the name for a column.
  34402. @see setColumnName
  34403. */
  34404. const String getColumnName (int columnId) const;
  34405. /** Changes the name of a column. */
  34406. void setColumnName (int columnId, const String& newName);
  34407. /** Moves a column to a different index in the table.
  34408. @param columnId the column to move
  34409. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  34410. */
  34411. void moveColumn (int columnId, int newVisibleIndex);
  34412. /** Returns the width of one of the columns.
  34413. */
  34414. int getColumnWidth (int columnId) const;
  34415. /** Changes the width of a column.
  34416. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  34417. */
  34418. void setColumnWidth (int columnId, int newWidth);
  34419. /** Shows or hides a column.
  34420. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  34421. @see isColumnVisible
  34422. */
  34423. void setColumnVisible (int columnId, bool shouldBeVisible);
  34424. /** Returns true if this column is currently visible.
  34425. @see setColumnVisible
  34426. */
  34427. bool isColumnVisible (int columnId) const;
  34428. /** Changes the column which is the sort column.
  34429. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  34430. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  34431. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  34432. @see getSortColumnId, isSortedForwards, reSortTable
  34433. */
  34434. void setSortColumnId (int columnId, bool sortForwards);
  34435. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  34436. @see setSortColumnId, isSortedForwards
  34437. */
  34438. int getSortColumnId() const;
  34439. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  34440. @see setSortColumnId
  34441. */
  34442. bool isSortedForwards() const;
  34443. /** Triggers a re-sort of the table according to the current sort-column.
  34444. If you modifiy the table's contents, you can call this to signal that the table needs
  34445. to be re-sorted.
  34446. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  34447. tableSortOrderChanged() method of any listeners).
  34448. */
  34449. void reSortTable();
  34450. /** Returns the total width of all the visible columns in the table.
  34451. */
  34452. int getTotalWidth() const;
  34453. /** Returns the index of a given column.
  34454. If there's no such column ID, this will return -1.
  34455. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  34456. otherwise it'll return the index amongst all the columns, including any hidden ones.
  34457. */
  34458. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  34459. /** Returns the ID of the column at a given index.
  34460. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  34461. otherwise it'll count it amongst all the columns, including any hidden ones.
  34462. If the index is out-of-range, it'll return 0.
  34463. */
  34464. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  34465. /** Returns the rectangle containing of one of the columns.
  34466. The index is an index from 0 to the number of columns that are currently visible (hidden
  34467. ones are not counted). It returns a rectangle showing the position of the column relative
  34468. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  34469. */
  34470. const Rectangle<int> getColumnPosition (int index) const;
  34471. /** Finds the column ID at a given x-position in the component.
  34472. If there is a column at this point this returns its ID, or if not, it will return 0.
  34473. */
  34474. int getColumnIdAtX (int xToFind) const;
  34475. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  34476. entire width of the component.
  34477. By default this is disabled. Turning it on also means that when resizing a column, those
  34478. on the right will be squashed to fit.
  34479. */
  34480. void setStretchToFitActive (bool shouldStretchToFit);
  34481. /** Returns true if stretch-to-fit has been enabled.
  34482. @see setStretchToFitActive
  34483. */
  34484. bool isStretchToFitActive() const;
  34485. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  34486. specified width, keeping their relative proportions the same.
  34487. If the minimum widths of the columns are too wide to fit into this space, it may
  34488. actually end up wider.
  34489. */
  34490. void resizeAllColumnsToFit (int targetTotalWidth);
  34491. /** Enables or disables the pop-up menu.
  34492. The default menu allows the user to show or hide columns. You can add custom
  34493. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  34494. By default the menu is enabled.
  34495. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  34496. */
  34497. void setPopupMenuActive (bool hasMenu);
  34498. /** Returns true if the pop-up menu is enabled.
  34499. @see setPopupMenuActive
  34500. */
  34501. bool isPopupMenuActive() const;
  34502. /** Returns a string that encapsulates the table's current layout.
  34503. This can be restored later using restoreFromString(). It saves the order of
  34504. the columns, the currently-sorted column, and the widths.
  34505. @see restoreFromString
  34506. */
  34507. const String toString() const;
  34508. /** Restores the state of the table, based on a string previously created with
  34509. toString().
  34510. @see toString
  34511. */
  34512. void restoreFromString (const String& storedVersion);
  34513. /** Adds a listener to be informed about things that happen to the header. */
  34514. void addListener (TableHeaderListener* newListener);
  34515. /** Removes a previously-registered listener. */
  34516. void removeListener (TableHeaderListener* listenerToRemove);
  34517. /** This can be overridden to handle a mouse-click on one of the column headers.
  34518. The default implementation will use this click to call getSortColumnId() and
  34519. change the sort order.
  34520. */
  34521. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  34522. /** This can be overridden to add custom items to the pop-up menu.
  34523. If you override this, you should call the superclass's method to add its
  34524. column show/hide items, if you want them on the menu as well.
  34525. Then to handle the result, override reactToMenuItem().
  34526. @see reactToMenuItem
  34527. */
  34528. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  34529. /** Override this to handle any custom items that you have added to the
  34530. pop-up menu with an addMenuItems() override.
  34531. If the menuReturnId isn't one of your own custom menu items, you'll need to
  34532. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  34533. handle the items that it had added.
  34534. @see addMenuItems
  34535. */
  34536. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  34537. /** @internal */
  34538. void paint (Graphics& g);
  34539. /** @internal */
  34540. void resized();
  34541. /** @internal */
  34542. void mouseMove (const MouseEvent&);
  34543. /** @internal */
  34544. void mouseEnter (const MouseEvent&);
  34545. /** @internal */
  34546. void mouseExit (const MouseEvent&);
  34547. /** @internal */
  34548. void mouseDown (const MouseEvent&);
  34549. /** @internal */
  34550. void mouseDrag (const MouseEvent&);
  34551. /** @internal */
  34552. void mouseUp (const MouseEvent&);
  34553. /** @internal */
  34554. const MouseCursor getMouseCursor();
  34555. /** Can be overridden for more control over the pop-up menu behaviour. */
  34556. virtual void showColumnChooserMenu (int columnIdClicked);
  34557. juce_UseDebuggingNewOperator
  34558. private:
  34559. struct ColumnInfo
  34560. {
  34561. String name;
  34562. int id, propertyFlags, width, minimumWidth, maximumWidth;
  34563. double lastDeliberateWidth;
  34564. bool isVisible() const;
  34565. };
  34566. OwnedArray <ColumnInfo> columns;
  34567. Array <TableHeaderListener*> listeners;
  34568. ScopedPointer <Component> dragOverlayComp;
  34569. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  34570. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  34571. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  34572. ColumnInfo* getInfoForId (int columnId) const;
  34573. int visibleIndexToTotalIndex (int visibleIndex) const;
  34574. void sendColumnsChanged();
  34575. void handleAsyncUpdate();
  34576. void beginDrag (const MouseEvent&);
  34577. void endDrag (int finalIndex);
  34578. int getResizeDraggerAt (int mouseX) const;
  34579. void updateColumnUnderMouse (int x, int y);
  34580. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  34581. TableHeaderComponent (const TableHeaderComponent&);
  34582. TableHeaderComponent operator= (const TableHeaderComponent&);
  34583. };
  34584. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  34585. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  34586. #endif
  34587. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34588. /*** Start of inlined file: juce_TableListBox.h ***/
  34589. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  34590. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  34591. /**
  34592. One of these is used by a TableListBox as the data model for the table's contents.
  34593. The virtual methods that you override in this class take care of drawing the
  34594. table cells, and reacting to events.
  34595. @see TableListBox
  34596. */
  34597. class JUCE_API TableListBoxModel
  34598. {
  34599. public:
  34600. TableListBoxModel() {}
  34601. /** Destructor. */
  34602. virtual ~TableListBoxModel() {}
  34603. /** This must return the number of rows currently in the table.
  34604. If the number of rows changes, you must call TableListBox::updateContent() to
  34605. cause it to refresh the list.
  34606. */
  34607. virtual int getNumRows() = 0;
  34608. /** This must draw the background behind one of the rows in the table.
  34609. The graphics context has its origin at the row's top-left, and your method
  34610. should fill the area specified by the width and height parameters.
  34611. */
  34612. virtual void paintRowBackground (Graphics& g,
  34613. int rowNumber,
  34614. int width, int height,
  34615. bool rowIsSelected) = 0;
  34616. /** This must draw one of the cells.
  34617. The graphics context's origin will already be set to the top-left of the cell,
  34618. whose size is specified by (width, height).
  34619. */
  34620. virtual void paintCell (Graphics& g,
  34621. int rowNumber,
  34622. int columnId,
  34623. int width, int height,
  34624. bool rowIsSelected) = 0;
  34625. /** This is used to create or update a custom component to go in a cell.
  34626. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  34627. and handle mouse clicks with cellClicked().
  34628. This method will be called whenever a custom component might need to be updated - e.g.
  34629. when the table is changed, or TableListBox::updateContent() is called.
  34630. If you don't need a custom component for the specified cell, then return 0.
  34631. If you do want a custom component, and the existingComponentToUpdate is null, then
  34632. this method must create a new component suitable for the cell, and return it.
  34633. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  34634. by this method. In this case, the method must either update it to make sure it's correctly representing
  34635. the given cell (which may be different from the one that the component was created for), or it can
  34636. delete this component and return a new one.
  34637. */
  34638. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  34639. Component* existingComponentToUpdate);
  34640. /** This callback is made when the user clicks on one of the cells in the table.
  34641. The mouse event's coordinates will be relative to the entire table row.
  34642. @see cellDoubleClicked, backgroundClicked
  34643. */
  34644. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  34645. /** This callback is made when the user clicks on one of the cells in the table.
  34646. The mouse event's coordinates will be relative to the entire table row.
  34647. @see cellClicked, backgroundClicked
  34648. */
  34649. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  34650. /** This can be overridden to react to the user double-clicking on a part of the list where
  34651. there are no rows.
  34652. @see cellClicked
  34653. */
  34654. virtual void backgroundClicked();
  34655. /** This callback is made when the table's sort order is changed.
  34656. This could be because the user has clicked a column header, or because the
  34657. TableHeaderComponent::setSortColumnId() method was called.
  34658. If you implement this, your method should re-sort the table using the given
  34659. column as the key.
  34660. */
  34661. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  34662. /** Returns the best width for one of the columns.
  34663. If you implement this method, you should measure the width of all the items
  34664. in this column, and return the best size.
  34665. Returning 0 means that the column shouldn't be changed.
  34666. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  34667. */
  34668. virtual int getColumnAutoSizeWidth (int columnId);
  34669. /** Returns a tooltip for a particular cell in the table.
  34670. */
  34671. virtual const String getCellTooltip (int rowNumber, int columnId);
  34672. /** Override this to be informed when rows are selected or deselected.
  34673. @see ListBox::selectedRowsChanged()
  34674. */
  34675. virtual void selectedRowsChanged (int lastRowSelected);
  34676. /** Override this to be informed when the delete key is pressed.
  34677. @see ListBox::deleteKeyPressed()
  34678. */
  34679. virtual void deleteKeyPressed (int lastRowSelected);
  34680. /** Override this to be informed when the return key is pressed.
  34681. @see ListBox::returnKeyPressed()
  34682. */
  34683. virtual void returnKeyPressed (int lastRowSelected);
  34684. /** Override this to be informed when the list is scrolled.
  34685. This might be caused by the user moving the scrollbar, or by programmatic changes
  34686. to the list position.
  34687. */
  34688. virtual void listWasScrolled();
  34689. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  34690. If this returns a non-empty name then when the user drags a row, the table will try to
  34691. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  34692. drag-and-drop operation, using this string as the source description, and the listbox
  34693. itself as the source component.
  34694. @see DragAndDropContainer::startDragging
  34695. */
  34696. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  34697. };
  34698. /**
  34699. A table of cells, using a TableHeaderComponent as its header.
  34700. This component makes it easy to create a table by providing a TableListBoxModel as
  34701. the data source.
  34702. @see TableListBoxModel, TableHeaderComponent
  34703. */
  34704. class JUCE_API TableListBox : public ListBox,
  34705. private ListBoxModel,
  34706. private TableHeaderListener
  34707. {
  34708. public:
  34709. /** Creates a TableListBox.
  34710. The model pointer passed-in can be null, in which case you can set it later
  34711. with setModel().
  34712. */
  34713. TableListBox (const String& componentName,
  34714. TableListBoxModel* model);
  34715. /** Destructor. */
  34716. ~TableListBox();
  34717. /** Changes the TableListBoxModel that is being used for this table.
  34718. */
  34719. void setModel (TableListBoxModel* newModel);
  34720. /** Returns the model currently in use. */
  34721. TableListBoxModel* getModel() const { return model; }
  34722. /** Returns the header component being used in this table. */
  34723. TableHeaderComponent* getHeader() const { return header; }
  34724. /** Changes the height of the table header component.
  34725. @see getHeaderHeight
  34726. */
  34727. void setHeaderHeight (int newHeight);
  34728. /** Returns the height of the table header.
  34729. @see setHeaderHeight
  34730. */
  34731. int getHeaderHeight() const;
  34732. /** Resizes a column to fit its contents.
  34733. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  34734. and applies that to the column.
  34735. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  34736. */
  34737. void autoSizeColumn (int columnId);
  34738. /** Calls autoSizeColumn() for all columns in the table. */
  34739. void autoSizeAllColumns();
  34740. /** Enables or disables the auto size options on the popup menu.
  34741. By default, these are enabled.
  34742. */
  34743. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  34744. /** True if the auto-size options should be shown on the menu.
  34745. @see setAutoSizeMenuOptionsShown
  34746. */
  34747. bool isAutoSizeMenuOptionShown() const;
  34748. /** Returns the position of one of the cells in the table.
  34749. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  34750. the table component's top-left. The row number isn't checked to see if it's
  34751. in-range, but the column ID must exist or this will return an empty rectangle.
  34752. If relativeToComponentTopLeft is false, the co-ords are relative to the
  34753. top-left of the table's top-left cell.
  34754. */
  34755. const Rectangle<int> getCellPosition (int columnId,
  34756. int rowNumber,
  34757. bool relativeToComponentTopLeft) const;
  34758. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  34759. @see ListBox::scrollToEnsureRowIsOnscreen
  34760. */
  34761. void scrollToEnsureColumnIsOnscreen (int columnId);
  34762. /** @internal */
  34763. int getNumRows();
  34764. /** @internal */
  34765. void paintListBoxItem (int, Graphics&, int, int, bool);
  34766. /** @internal */
  34767. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  34768. /** @internal */
  34769. void selectedRowsChanged (int lastRowSelected);
  34770. /** @internal */
  34771. void deleteKeyPressed (int currentSelectedRow);
  34772. /** @internal */
  34773. void returnKeyPressed (int currentSelectedRow);
  34774. /** @internal */
  34775. void backgroundClicked();
  34776. /** @internal */
  34777. void listWasScrolled();
  34778. /** @internal */
  34779. void tableColumnsChanged (TableHeaderComponent*);
  34780. /** @internal */
  34781. void tableColumnsResized (TableHeaderComponent*);
  34782. /** @internal */
  34783. void tableSortOrderChanged (TableHeaderComponent*);
  34784. /** @internal */
  34785. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  34786. /** @internal */
  34787. void resized();
  34788. juce_UseDebuggingNewOperator
  34789. private:
  34790. TableHeaderComponent* header;
  34791. TableListBoxModel* model;
  34792. int columnIdNowBeingDragged;
  34793. bool autoSizeOptionsShown;
  34794. void updateColumnComponents() const;
  34795. TableListBox (const TableListBox&);
  34796. TableListBox& operator= (const TableListBox&);
  34797. };
  34798. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  34799. /*** End of inlined file: juce_TableListBox.h ***/
  34800. #endif
  34801. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  34802. #endif
  34803. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  34804. #endif
  34805. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  34806. #endif
  34807. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34808. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  34809. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34810. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34811. /**
  34812. A factory object which can create ToolbarItemComponent objects.
  34813. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  34814. that it can create.
  34815. Each type of item is identified by a unique ID, and multiple instances of an
  34816. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  34817. bars).
  34818. @see Toolbar, ToolbarItemComponent, ToolbarButton
  34819. */
  34820. class JUCE_API ToolbarItemFactory
  34821. {
  34822. public:
  34823. ToolbarItemFactory();
  34824. /** Destructor. */
  34825. virtual ~ToolbarItemFactory();
  34826. /** A set of reserved item ID values, used for the built-in item types.
  34827. */
  34828. enum SpecialItemIds
  34829. {
  34830. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  34831. can be placed between sets of items to break them into groups. */
  34832. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  34833. items.*/
  34834. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  34835. either side of it, filling any available space. */
  34836. };
  34837. /** Must return a list of the IDs for all the item types that this factory can create.
  34838. The ids should be added to the array that is passed-in.
  34839. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  34840. and the predefined IDs in the SpecialItemIds enum.
  34841. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  34842. to this list if you want your toolbar to be able to contain those items.
  34843. The list returned here is used by the ToolbarItemPalette class to obtain its list
  34844. of available items, and their order on the palette will reflect the order in which
  34845. they appear on this list.
  34846. @see ToolbarItemPalette
  34847. */
  34848. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  34849. /** Must return the set of items that should be added to a toolbar as its default set.
  34850. This method is used by Toolbar::addDefaultItems() to determine which items to
  34851. create.
  34852. The items that your method adds to the array that is passed-in will be added to the
  34853. toolbar in the same order. Items can appear in the list more than once.
  34854. */
  34855. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  34856. /** Must create an instance of one of the items that the factory lists in its
  34857. getAllToolbarItemIds() method.
  34858. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  34859. method, except for the built-in item types from the SpecialItemIds enum, which
  34860. are created internally by the toolbar code.
  34861. Try not to keep a pointer to the object that is returned, as it will be deleted
  34862. automatically by the toolbar, and remember that multiple instances of the same
  34863. item type are likely to exist at the same time.
  34864. */
  34865. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  34866. };
  34867. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  34868. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  34869. #endif
  34870. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34871. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  34872. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34873. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34874. /**
  34875. A component containing a list of toolbar items, which the user can drag onto
  34876. a toolbar to add them.
  34877. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  34878. which automatically shows one of these in a dialog box with lots of extra controls.
  34879. @see Toolbar
  34880. */
  34881. class JUCE_API ToolbarItemPalette : public Component,
  34882. public DragAndDropContainer
  34883. {
  34884. public:
  34885. /** Creates a palette of items for a given factory, with the aim of adding them
  34886. to the specified toolbar.
  34887. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  34888. set of items that are shown in this palette.
  34889. The toolbar and factory must not be deleted while this object exists.
  34890. */
  34891. ToolbarItemPalette (ToolbarItemFactory& factory,
  34892. Toolbar* toolbar);
  34893. /** Destructor. */
  34894. ~ToolbarItemPalette();
  34895. /** @internal */
  34896. void resized();
  34897. juce_UseDebuggingNewOperator
  34898. private:
  34899. ToolbarItemFactory& factory;
  34900. Toolbar* toolbar;
  34901. Viewport* viewport;
  34902. friend class Toolbar;
  34903. void replaceComponent (ToolbarItemComponent* comp);
  34904. ToolbarItemPalette (const ToolbarItemPalette&);
  34905. ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  34906. };
  34907. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  34908. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  34909. #endif
  34910. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34911. /*** Start of inlined file: juce_TreeView.h ***/
  34912. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  34913. #define __JUCE_TREEVIEW_JUCEHEADER__
  34914. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  34915. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  34916. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  34917. /**
  34918. Components derived from this class can have files dropped onto them by an external application.
  34919. @see DragAndDropContainer
  34920. */
  34921. class JUCE_API FileDragAndDropTarget
  34922. {
  34923. public:
  34924. /** Destructor. */
  34925. virtual ~FileDragAndDropTarget() {}
  34926. /** Callback to check whether this target is interested in the set of files being offered.
  34927. Note that this will be called repeatedly when the user is dragging the mouse around over your
  34928. component, so don't do anything time-consuming in here, like opening the files to have a look
  34929. inside them!
  34930. @param files the set of (absolute) pathnames of the files that the user is dragging
  34931. @returns true if this component wants to receive the other callbacks regarging this
  34932. type of object; if it returns false, no other callbacks will be made.
  34933. */
  34934. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  34935. /** Callback to indicate that some files are being dragged over this component.
  34936. This gets called when the user moves the mouse into this component while dragging.
  34937. Use this callback as a trigger to make your component repaint itself to give the
  34938. user feedback about whether the files can be dropped here or not.
  34939. @param files the set of (absolute) pathnames of the files that the user is dragging
  34940. @param x the mouse x position, relative to this component
  34941. @param y the mouse y position, relative to this component
  34942. */
  34943. virtual void fileDragEnter (const StringArray& files, int x, int y);
  34944. /** Callback to indicate that the user is dragging some files over this component.
  34945. This gets called when the user moves the mouse over this component while dragging.
  34946. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  34947. this lets you know what happens in-between.
  34948. @param files the set of (absolute) pathnames of the files that the user is dragging
  34949. @param x the mouse x position, relative to this component
  34950. @param y the mouse y position, relative to this component
  34951. */
  34952. virtual void fileDragMove (const StringArray& files, int x, int y);
  34953. /** Callback to indicate that the mouse has moved away from this component.
  34954. This gets called when the user moves the mouse out of this component while dragging
  34955. the files.
  34956. If you've used fileDragEnter() to repaint your component and give feedback, use this
  34957. as a signal to repaint it in its normal state.
  34958. @param files the set of (absolute) pathnames of the files that the user is dragging
  34959. */
  34960. virtual void fileDragExit (const StringArray& files);
  34961. /** Callback to indicate that the user has dropped the files onto this component.
  34962. When the user drops the files, this get called, and you can use the files in whatever
  34963. way is appropriate.
  34964. Note that after this is called, the fileDragExit method may not be called, so you should
  34965. clean up in here if there's anything you need to do when the drag finishes.
  34966. @param files the set of (absolute) pathnames of the files that the user is dragging
  34967. @param x the mouse x position, relative to this component
  34968. @param y the mouse y position, relative to this component
  34969. */
  34970. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  34971. };
  34972. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  34973. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  34974. class TreeView;
  34975. /**
  34976. An item in a treeview.
  34977. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  34978. own sub-items.
  34979. To implement an item that contains sub-items, override the itemOpennessChanged()
  34980. method so that when it is opened, it adds the new sub-items to itself using the
  34981. addSubItem method. Depending on the nature of the item it might choose to only
  34982. do this the first time it's opened, or it might want to refresh itself each time.
  34983. It also has the option of deleting its sub-items when it is closed, or leaving them
  34984. in place.
  34985. */
  34986. class JUCE_API TreeViewItem
  34987. {
  34988. public:
  34989. /** Constructor. */
  34990. TreeViewItem();
  34991. /** Destructor. */
  34992. virtual ~TreeViewItem();
  34993. /** Returns the number of sub-items that have been added to this item.
  34994. Note that this doesn't mean much if the node isn't open.
  34995. @see getSubItem, mightContainSubItems, addSubItem
  34996. */
  34997. int getNumSubItems() const throw();
  34998. /** Returns one of the item's sub-items.
  34999. Remember that the object returned might get deleted at any time when its parent
  35000. item is closed or refreshed, depending on the nature of the items you're using.
  35001. @see getNumSubItems
  35002. */
  35003. TreeViewItem* getSubItem (int index) const throw();
  35004. /** Removes any sub-items. */
  35005. void clearSubItems();
  35006. /** Adds a sub-item.
  35007. @param newItem the object to add to the item's sub-item list. Once added, these can be
  35008. found using getSubItem(). When the items are later removed with
  35009. removeSubItem() (or when this item is deleted), they will be deleted.
  35010. @param insertPosition the index which the new item should have when it's added. If this
  35011. value is less than 0, the item will be added to the end of the list.
  35012. */
  35013. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  35014. /** Removes one of the sub-items.
  35015. @param index the item to remove
  35016. @param deleteItem if true, the item that is removed will also be deleted.
  35017. */
  35018. void removeSubItem (int index, bool deleteItem = true);
  35019. /** Returns the TreeView to which this item belongs. */
  35020. TreeView* getOwnerView() const throw() { return ownerView; }
  35021. /** Returns the item within which this item is contained. */
  35022. TreeViewItem* getParentItem() const throw() { return parentItem; }
  35023. /** True if this item is currently open in the treeview. */
  35024. bool isOpen() const throw();
  35025. /** Opens or closes the item.
  35026. When opened or closed, the item's itemOpennessChanged() method will be called,
  35027. and a subclass should use this callback to create and add any sub-items that
  35028. it needs to.
  35029. @see itemOpennessChanged, mightContainSubItems
  35030. */
  35031. void setOpen (bool shouldBeOpen);
  35032. /** True if this item is currently selected.
  35033. Use this when painting the node, to decide whether to draw it as selected or not.
  35034. */
  35035. bool isSelected() const throw();
  35036. /** Selects or deselects the item.
  35037. This will cause a callback to itemSelectionChanged()
  35038. */
  35039. void setSelected (bool shouldBeSelected,
  35040. bool deselectOtherItemsFirst);
  35041. /** Returns the rectangle that this item occupies.
  35042. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  35043. top-left of the TreeView comp, so this will depend on the scroll-position of
  35044. the tree. If false, it is relative to the top-left of the topmost item in the
  35045. tree (so this would be unaffected by scrolling the view).
  35046. */
  35047. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  35048. /** Sends a signal to the treeview to make it refresh itself.
  35049. Call this if your items have changed and you want the tree to update to reflect
  35050. this.
  35051. */
  35052. void treeHasChanged() const throw();
  35053. /** Sends a repaint message to redraw just this item.
  35054. Note that you should only call this if you want to repaint a superficial change. If
  35055. you're altering the tree's nodes, you should instead call treeHasChanged().
  35056. */
  35057. void repaintItem() const;
  35058. /** Returns the row number of this item in the tree.
  35059. The row number of an item will change according to which items are open.
  35060. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  35061. */
  35062. int getRowNumberInTree() const throw();
  35063. /** Returns true if all the item's parent nodes are open.
  35064. This is useful to check whether the item might actually be visible or not.
  35065. */
  35066. bool areAllParentsOpen() const throw();
  35067. /** Changes whether lines are drawn to connect any sub-items to this item.
  35068. By default, line-drawing is turned on.
  35069. */
  35070. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  35071. /** Tells the tree whether this item can potentially be opened.
  35072. If your item could contain sub-items, this should return true; if it returns
  35073. false then the tree will not try to open the item. This determines whether or
  35074. not the item will be drawn with a 'plus' button next to it.
  35075. */
  35076. virtual bool mightContainSubItems() = 0;
  35077. /** Returns a string to uniquely identify this item.
  35078. If you're planning on using the TreeView::getOpennessState() method, then
  35079. these strings will be used to identify which nodes are open. The string
  35080. should be unique amongst the item's sibling items, but it's ok for there
  35081. to be duplicates at other levels of the tree.
  35082. If you're not going to store the state, then it's ok not to bother implementing
  35083. this method.
  35084. */
  35085. virtual const String getUniqueName() const;
  35086. /** Called when an item is opened or closed.
  35087. When setOpen() is called and the item has specified that it might
  35088. have sub-items with the mightContainSubItems() method, this method
  35089. is called to let the item create or manage its sub-items.
  35090. So when this is called with isNowOpen set to true (i.e. when the item is being
  35091. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  35092. refresh its sub-item list.
  35093. When this is called with isNowOpen set to false, the subclass might want
  35094. to use clearSubItems() to save on space, or it might choose to leave them,
  35095. depending on the nature of the tree.
  35096. You could also use this callback as a trigger to start a background process
  35097. which asynchronously creates sub-items and adds them, if that's more
  35098. appropriate for the task in hand.
  35099. @see mightContainSubItems
  35100. */
  35101. virtual void itemOpennessChanged (bool isNowOpen);
  35102. /** Must return the width required by this item.
  35103. If your item needs to have a particular width in pixels, return that value; if
  35104. you'd rather have it just fill whatever space is available in the treeview,
  35105. return -1.
  35106. If all your items return -1, no horizontal scrollbar will be shown, but if any
  35107. items have fixed widths and extend beyond the width of the treeview, a
  35108. scrollbar will appear.
  35109. Each item can be a different width, but if they change width, you should call
  35110. treeHasChanged() to update the tree.
  35111. */
  35112. virtual int getItemWidth() const { return -1; }
  35113. /** Must return the height required by this item.
  35114. This is the height in pixels that the item will take up. Items in the tree
  35115. can be different heights, but if they change height, you should call
  35116. treeHasChanged() to update the tree.
  35117. */
  35118. virtual int getItemHeight() const { return 20; }
  35119. /** You can override this method to return false if you don't want to allow the
  35120. user to select this item.
  35121. */
  35122. virtual bool canBeSelected() const { return true; }
  35123. /** Creates a component that will be used to represent this item.
  35124. You don't have to implement this method - if it returns 0 then no component
  35125. will be used for the item, and you can just draw it using the paintItem()
  35126. callback. But if you do return a component, it will be positioned in the
  35127. treeview so that it can be used to represent this item.
  35128. The component returned will be managed by the treeview, so always return
  35129. a new component, and don't keep a reference to it, as the treeview will
  35130. delete it later when it goes off the screen or is no longer needed. Also
  35131. bear in mind that if the component keeps a reference to the item that
  35132. created it, that item could be deleted before the component. Its position
  35133. and size will be completely managed by the tree, so don't attempt to move it
  35134. around.
  35135. Something you may want to do with your component is to give it a pointer to
  35136. the TreeView that created it. This is perfectly safe, and there's no danger
  35137. of it becoming a dangling pointer because the TreeView will always delete
  35138. the component before it is itself deleted.
  35139. As long as you stick to these rules you can return whatever kind of
  35140. component you like. It's most useful if you're doing things like drag-and-drop
  35141. of items, or want to use a Label component to edit item names, etc.
  35142. */
  35143. virtual Component* createItemComponent() { return 0; }
  35144. /** Draws the item's contents.
  35145. You can choose to either implement this method and draw each item, or you
  35146. can use createItemComponent() to create a component that will represent the
  35147. item.
  35148. If all you need in your tree is to be able to draw the items and detect when
  35149. the user selects or double-clicks one of them, it's probably enough to
  35150. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  35151. complicated interactions, you may need to use createItemComponent() instead.
  35152. @param g the graphics context to draw into
  35153. @param width the width of the area available for drawing
  35154. @param height the height of the area available for drawing
  35155. */
  35156. virtual void paintItem (Graphics& g, int width, int height);
  35157. /** Draws the item's open/close button.
  35158. If you don't implement this method, the default behaviour is to
  35159. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  35160. it for custom effects.
  35161. */
  35162. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  35163. /** Called when the user clicks on this item.
  35164. If you're using createItemComponent() to create a custom component for the
  35165. item, the mouse-clicks might not make it through to the treeview, but this
  35166. is how you find out about clicks when just drawing each item individually.
  35167. The associated mouse-event details are passed in, so you can find out about
  35168. which button, where it was, etc.
  35169. @see itemDoubleClicked
  35170. */
  35171. virtual void itemClicked (const MouseEvent& e);
  35172. /** Called when the user double-clicks on this item.
  35173. If you're using createItemComponent() to create a custom component for the
  35174. item, the mouse-clicks might not make it through to the treeview, but this
  35175. is how you find out about clicks when just drawing each item individually.
  35176. The associated mouse-event details are passed in, so you can find out about
  35177. which button, where it was, etc.
  35178. If not overridden, the base class method here will open or close the item as
  35179. if the 'plus' button had been clicked.
  35180. @see itemClicked
  35181. */
  35182. virtual void itemDoubleClicked (const MouseEvent& e);
  35183. /** Called when the item is selected or deselected.
  35184. Use this if you want to do something special when the item's selectedness
  35185. changes. By default it'll get repainted when this happens.
  35186. */
  35187. virtual void itemSelectionChanged (bool isNowSelected);
  35188. /** The item can return a tool tip string here if it wants to.
  35189. @see TooltipClient
  35190. */
  35191. virtual const String getTooltip();
  35192. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  35193. If this returns a non-empty name then when the user drags an item, the treeview will
  35194. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  35195. a drag-and-drop operation, using this string as the source description, with the treeview
  35196. itself as the source component.
  35197. If you need more complex drag-and-drop behaviour, you can use custom components for
  35198. the items, and use those to trigger the drag.
  35199. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  35200. isInterestedInFileDrag(), etc.
  35201. @see DragAndDropContainer::startDragging
  35202. */
  35203. virtual const String getDragSourceDescription();
  35204. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  35205. method and return true.
  35206. If you return true and allow some files to be dropped, you'll also need to implement the
  35207. filesDropped() method to do something with them.
  35208. Note that this will be called often, so make your implementation very quick! There's
  35209. certainly no time to try opening the files and having a think about what's inside them!
  35210. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  35211. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  35212. */
  35213. virtual bool isInterestedInFileDrag (const StringArray& files);
  35214. /** When files are dropped into this item, this callback is invoked.
  35215. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  35216. The insertIndex value indicates where in the list of sub-items the files were dropped.
  35217. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  35218. */
  35219. virtual void filesDropped (const StringArray& files, int insertIndex);
  35220. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  35221. If you implement this method, you'll also need to implement itemDropped() in order to handle
  35222. the items when they are dropped.
  35223. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  35224. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  35225. */
  35226. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  35227. /** When a things are dropped into this item, this callback is invoked.
  35228. For this to work, you need to have also implemented isInterestedInDragSource().
  35229. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  35230. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  35231. */
  35232. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  35233. /** Sets a flag to indicate that the item wants to be allowed
  35234. to draw all the way across to the left edge of the treeview.
  35235. By default this is false, which means that when the paintItem()
  35236. method is called, its graphics context is clipped to only allow
  35237. drawing within the item's rectangle. If this flag is set to true,
  35238. then the graphics context isn't clipped on its left side, so it
  35239. can draw all the way across to the left margin. Note that the
  35240. context will still have its origin in the same place though, so
  35241. the coordinates of anything to its left will be negative. It's
  35242. mostly useful if you want to draw a wider bar behind the
  35243. highlighted item.
  35244. */
  35245. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  35246. /** Saves the current state of open/closed nodes so it can be restored later.
  35247. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  35248. and records it as XML. To identify node objects it uses the
  35249. TreeViewItem::getUniqueName() method to create named paths. This
  35250. means that the same state of open/closed nodes can be restored to a
  35251. completely different instance of the tree, as long as it contains nodes
  35252. whose unique names are the same.
  35253. You'd normally want to use TreeView::getOpennessState() rather than call it
  35254. for a specific item, but this can be handy if you need to briefly save the state
  35255. for a section of the tree.
  35256. The caller is responsible for deleting the object that is returned.
  35257. @see TreeView::getOpennessState, restoreOpennessState
  35258. */
  35259. XmlElement* getOpennessState() const throw();
  35260. /** Restores the openness of this item and all its sub-items from a saved state.
  35261. See TreeView::restoreOpennessState for more details.
  35262. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  35263. for a specific item, but this can be handy if you need to briefly save the state
  35264. for a section of the tree.
  35265. @see TreeView::restoreOpennessState, getOpennessState
  35266. */
  35267. void restoreOpennessState (const XmlElement& xml) throw();
  35268. /** Returns the index of this item in its parent's sub-items. */
  35269. int getIndexInParent() const throw();
  35270. /** Returns true if this item is the last of its parent's sub-itens. */
  35271. bool isLastOfSiblings() const throw();
  35272. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  35273. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  35274. The string takes the form of a path, constructed from the getUniqueName() of this
  35275. item and all its parents, so these must all be correctly implemented for it to work.
  35276. @see TreeView::findItemFromIdentifierString, getUniqueName
  35277. */
  35278. const String getItemIdentifierString() const;
  35279. juce_UseDebuggingNewOperator
  35280. private:
  35281. TreeView* ownerView;
  35282. TreeViewItem* parentItem;
  35283. OwnedArray <TreeViewItem> subItems;
  35284. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  35285. int uid;
  35286. bool selected : 1;
  35287. bool redrawNeeded : 1;
  35288. bool drawLinesInside : 1;
  35289. bool drawsInLeftMargin : 1;
  35290. unsigned int openness : 2;
  35291. friend class TreeView;
  35292. friend class TreeViewContentComponent;
  35293. void updatePositions (int newY);
  35294. int getIndentX() const throw();
  35295. void setOwnerView (TreeView* newOwner) throw();
  35296. void paintRecursively (Graphics& g, int width);
  35297. TreeViewItem* getTopLevelItem() throw();
  35298. TreeViewItem* findItemRecursively (int y) throw();
  35299. TreeViewItem* getDeepestOpenParentItem() throw();
  35300. int getNumRows() const throw();
  35301. TreeViewItem* getItemOnRow (int index) throw();
  35302. void deselectAllRecursively();
  35303. int countSelectedItemsRecursively() const throw();
  35304. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  35305. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  35306. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  35307. TreeViewItem (const TreeViewItem&);
  35308. TreeViewItem& operator= (const TreeViewItem&);
  35309. };
  35310. /**
  35311. A tree-view component.
  35312. Use one of these to hold and display a structure of TreeViewItem objects.
  35313. */
  35314. class JUCE_API TreeView : public Component,
  35315. public SettableTooltipClient,
  35316. public FileDragAndDropTarget,
  35317. public DragAndDropTarget,
  35318. private AsyncUpdater
  35319. {
  35320. public:
  35321. /** Creates an empty treeview.
  35322. Once you've got a treeview component, you'll need to give it something to
  35323. display, using the setRootItem() method.
  35324. */
  35325. TreeView (const String& componentName = String::empty);
  35326. /** Destructor. */
  35327. ~TreeView();
  35328. /** Sets the item that is displayed in the treeview.
  35329. A tree has a single root item which contains as many sub-items as it needs. If
  35330. you want the tree to contain a number of root items, you should still use a single
  35331. root item above these, but hide it using setRootItemVisible().
  35332. You can pass in 0 to this method to clear the tree and remove its current root item.
  35333. The object passed in will not be deleted by the treeview, it's up to the caller
  35334. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  35335. this item until you've removed it from the tree, either by calling setRootItem (0),
  35336. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  35337. to delete it.
  35338. */
  35339. void setRootItem (TreeViewItem* newRootItem);
  35340. /** Returns the tree's root item.
  35341. This will be the last object passed to setRootItem(), or 0 if none has been set.
  35342. */
  35343. TreeViewItem* getRootItem() const throw() { return rootItem; }
  35344. /** This will remove and delete the current root item.
  35345. It's a convenient way of deleting the item and calling setRootItem (0).
  35346. */
  35347. void deleteRootItem();
  35348. /** Changes whether the tree's root item is shown or not.
  35349. If the root item is hidden, only its sub-items will be shown in the treeview - this
  35350. lets you make the tree look as if it's got many root items. If it's hidden, this call
  35351. will also make sure the root item is open (otherwise the treeview would look empty).
  35352. */
  35353. void setRootItemVisible (bool shouldBeVisible);
  35354. /** Returns true if the root item is visible.
  35355. @see setRootItemVisible
  35356. */
  35357. bool isRootItemVisible() const throw() { return rootItemVisible; }
  35358. /** Sets whether items are open or closed by default.
  35359. Normally, items are closed until the user opens them, but you can use this
  35360. to make them default to being open until explicitly closed.
  35361. @see areItemsOpenByDefault
  35362. */
  35363. void setDefaultOpenness (bool isOpenByDefault);
  35364. /** Returns true if the tree's items default to being open.
  35365. @see setDefaultOpenness
  35366. */
  35367. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  35368. /** This sets a flag to indicate that the tree can be used for multi-selection.
  35369. You can always select multiple items internally by calling the
  35370. TreeViewItem::setSelected() method, but this flag indicates whether the user
  35371. is allowed to multi-select by clicking on the tree.
  35372. By default it is disabled.
  35373. @see isMultiSelectEnabled
  35374. */
  35375. void setMultiSelectEnabled (bool canMultiSelect);
  35376. /** Returns whether multi-select has been enabled for the tree.
  35377. @see setMultiSelectEnabled
  35378. */
  35379. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  35380. /** Sets a flag to indicate whether to hide the open/close buttons.
  35381. @see areOpenCloseButtonsVisible
  35382. */
  35383. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  35384. /** Returns whether open/close buttons are shown.
  35385. @see setOpenCloseButtonsVisible
  35386. */
  35387. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  35388. /** Deselects any items that are currently selected. */
  35389. void clearSelectedItems();
  35390. /** Returns the number of items that are currently selected.
  35391. @see getSelectedItem, clearSelectedItems
  35392. */
  35393. int getNumSelectedItems() const throw();
  35394. /** Returns one of the selected items in the tree.
  35395. @param index the index, 0 to (getNumSelectedItems() - 1)
  35396. */
  35397. TreeViewItem* getSelectedItem (int index) const throw();
  35398. /** Returns the number of rows the tree is using.
  35399. This will depend on which items are open.
  35400. @see TreeViewItem::getRowNumberInTree()
  35401. */
  35402. int getNumRowsInTree() const;
  35403. /** Returns the item on a particular row of the tree.
  35404. If the index is out of range, this will return 0.
  35405. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  35406. */
  35407. TreeViewItem* getItemOnRow (int index) const;
  35408. /** Returns the item that contains a given y position.
  35409. The y is relative to the top of the TreeView component.
  35410. */
  35411. TreeViewItem* getItemAt (int yPosition) const throw();
  35412. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  35413. void scrollToKeepItemVisible (TreeViewItem* item);
  35414. /** Returns the treeview's Viewport object. */
  35415. Viewport* getViewport() const throw();
  35416. /** Returns the number of pixels by which each nested level of the tree is indented.
  35417. @see setIndentSize
  35418. */
  35419. int getIndentSize() const throw() { return indentSize; }
  35420. /** Changes the distance by which each nested level of the tree is indented.
  35421. @see getIndentSize
  35422. */
  35423. void setIndentSize (int newIndentSize);
  35424. /** Searches the tree for an item with the specified identifier.
  35425. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  35426. If no such item exists, this will return false. If the item is found, all of its items
  35427. will be automatically opened.
  35428. */
  35429. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  35430. /** Saves the current state of open/closed nodes so it can be restored later.
  35431. This takes a snapshot of which nodes have been explicitly opened or closed,
  35432. and records it as XML. To identify node objects it uses the
  35433. TreeViewItem::getUniqueName() method to create named paths. This
  35434. means that the same state of open/closed nodes can be restored to a
  35435. completely different instance of the tree, as long as it contains nodes
  35436. whose unique names are the same.
  35437. The caller is responsible for deleting the object that is returned.
  35438. @param alsoIncludeScrollPosition if this is true, the state will also
  35439. include information about where the
  35440. tree has been scrolled to vertically,
  35441. so this can also be restored
  35442. @see restoreOpennessState
  35443. */
  35444. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  35445. /** Restores a previously saved arrangement of open/closed nodes.
  35446. This will try to restore a snapshot of the tree's state that was created by
  35447. the getOpennessState() method. If any of the nodes named in the original
  35448. XML aren't present in this tree, they will be ignored.
  35449. @see getOpennessState
  35450. */
  35451. void restoreOpennessState (const XmlElement& newState);
  35452. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  35453. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35454. methods.
  35455. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35456. */
  35457. enum ColourIds
  35458. {
  35459. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  35460. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  35461. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  35462. };
  35463. /** @internal */
  35464. void paint (Graphics& g);
  35465. /** @internal */
  35466. void resized();
  35467. /** @internal */
  35468. bool keyPressed (const KeyPress& key);
  35469. /** @internal */
  35470. void colourChanged();
  35471. /** @internal */
  35472. void enablementChanged();
  35473. /** @internal */
  35474. bool isInterestedInFileDrag (const StringArray& files);
  35475. /** @internal */
  35476. void fileDragEnter (const StringArray& files, int x, int y);
  35477. /** @internal */
  35478. void fileDragMove (const StringArray& files, int x, int y);
  35479. /** @internal */
  35480. void fileDragExit (const StringArray& files);
  35481. /** @internal */
  35482. void filesDropped (const StringArray& files, int x, int y);
  35483. /** @internal */
  35484. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  35485. /** @internal */
  35486. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35487. /** @internal */
  35488. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35489. /** @internal */
  35490. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  35491. /** @internal */
  35492. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  35493. juce_UseDebuggingNewOperator
  35494. private:
  35495. friend class TreeViewItem;
  35496. friend class TreeViewContentComponent;
  35497. class TreeViewport;
  35498. TreeViewport* viewport;
  35499. CriticalSection nodeAlterationLock;
  35500. TreeViewItem* rootItem;
  35501. class InsertPointHighlight;
  35502. class TargetGroupHighlight;
  35503. InsertPointHighlight* dragInsertPointHighlight;
  35504. TargetGroupHighlight* dragTargetGroupHighlight;
  35505. int indentSize;
  35506. bool defaultOpenness : 1;
  35507. bool needsRecalculating : 1;
  35508. bool rootItemVisible : 1;
  35509. bool multiSelectEnabled : 1;
  35510. bool openCloseButtonsVisible : 1;
  35511. void itemsChanged() throw();
  35512. void handleAsyncUpdate();
  35513. void moveSelectedRow (int delta);
  35514. void updateButtonUnderMouse (const MouseEvent& e);
  35515. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  35516. void hideDragHighlight() throw();
  35517. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  35518. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  35519. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  35520. const StringArray& files, const String& sourceDescription,
  35521. Component* sourceComponent) const throw();
  35522. TreeView (const TreeView&);
  35523. TreeView& operator= (const TreeView&);
  35524. };
  35525. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  35526. /*** End of inlined file: juce_TreeView.h ***/
  35527. #endif
  35528. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35529. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  35530. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35531. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35532. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  35533. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  35534. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  35535. /*** Start of inlined file: juce_FileFilter.h ***/
  35536. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  35537. #define __JUCE_FILEFILTER_JUCEHEADER__
  35538. /**
  35539. Interface for deciding which files are suitable for something.
  35540. For example, this is used by DirectoryContentsList to select which files
  35541. go into the list.
  35542. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  35543. */
  35544. class JUCE_API FileFilter
  35545. {
  35546. public:
  35547. /** Creates a filter with the given description.
  35548. The description can be returned later with the getDescription() method.
  35549. */
  35550. FileFilter (const String& filterDescription);
  35551. /** Destructor. */
  35552. virtual ~FileFilter();
  35553. /** Returns the description that the filter was created with. */
  35554. const String& getDescription() const throw();
  35555. /** Should return true if this file is suitable for inclusion in whatever context
  35556. the object is being used.
  35557. */
  35558. virtual bool isFileSuitable (const File& file) const = 0;
  35559. /** Should return true if this directory is suitable for inclusion in whatever context
  35560. the object is being used.
  35561. */
  35562. virtual bool isDirectorySuitable (const File& file) const = 0;
  35563. protected:
  35564. String description;
  35565. };
  35566. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  35567. /*** End of inlined file: juce_FileFilter.h ***/
  35568. /*** Start of inlined file: juce_Image.h ***/
  35569. #ifndef __JUCE_IMAGE_JUCEHEADER__
  35570. #define __JUCE_IMAGE_JUCEHEADER__
  35571. /**
  35572. Holds a fixed-size bitmap.
  35573. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  35574. To draw into an image, create a Graphics object for it.
  35575. e.g. @code
  35576. // create a transparent 500x500 image..
  35577. Image myImage (Image::RGB, 500, 500, true);
  35578. Graphics g (myImage);
  35579. g.setColour (Colours::red);
  35580. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  35581. @endcode
  35582. Other useful ways to create an image are with the ImageCache class, or the
  35583. ImageFileFormat, which provides a way to load common image files.
  35584. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  35585. */
  35586. class JUCE_API Image
  35587. {
  35588. public:
  35589. enum PixelFormat
  35590. {
  35591. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  35592. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  35593. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  35594. };
  35595. /** Creates an in-memory image with a specified size and format.
  35596. To create an image that can use native OS rendering methods, see createNativeImage().
  35597. @param format the number of colour channels in the image
  35598. @param imageWidth the desired width of the image, in pixels - this value must be
  35599. greater than zero (otherwise a width of 1 will be used)
  35600. @param imageHeight the desired width of the image, in pixels - this value must be
  35601. greater than zero (otherwise a height of 1 will be used)
  35602. @param clearImage if true, the image will initially be cleared to black or transparent
  35603. black. If false, the image may contain random data, and the
  35604. user will have to deal with this
  35605. */
  35606. Image (PixelFormat format,
  35607. int imageWidth,
  35608. int imageHeight,
  35609. bool clearImage);
  35610. /** Creates a copy of another image.
  35611. @see createCopy
  35612. */
  35613. Image (const Image& other);
  35614. /** Destructor. */
  35615. virtual ~Image();
  35616. /** Tries to create an image that is uses native drawing methods when you render
  35617. onto it.
  35618. On some platforms this will just return a normal software-based image.
  35619. */
  35620. static Image* createNativeImage (PixelFormat format,
  35621. int imageWidth,
  35622. int imageHeight,
  35623. bool clearImage);
  35624. /** Returns the image's width (in pixels). */
  35625. int getWidth() const throw() { return imageWidth; }
  35626. /** Returns the image's height (in pixels). */
  35627. int getHeight() const throw() { return imageHeight; }
  35628. /** Returns a rectangle with the same size as this image.
  35629. The rectangle is always at position (0, 0).
  35630. */
  35631. const Rectangle<int> getBounds() const throw() { return Rectangle<int> (0, 0, imageWidth, imageHeight); }
  35632. /** Returns the image's pixel format. */
  35633. PixelFormat getFormat() const throw() { return format; }
  35634. /** True if the image's format is ARGB. */
  35635. bool isARGB() const throw() { return format == ARGB; }
  35636. /** True if the image's format is RGB. */
  35637. bool isRGB() const throw() { return format == RGB; }
  35638. /** True if the image contains an alpha-channel. */
  35639. bool hasAlphaChannel() const throw() { return format != RGB; }
  35640. /** Clears a section of the image with a given colour.
  35641. This won't do any alpha-blending - it just sets all pixels in the image to
  35642. the given colour (which may be non-opaque if the image has an alpha channel).
  35643. */
  35644. virtual void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  35645. /** Returns a new image that's a copy of this one.
  35646. A new size for the copied image can be specified, or values less than
  35647. zero can be passed-in to use the image's existing dimensions.
  35648. It's up to the caller to delete the image when no longer needed.
  35649. */
  35650. virtual Image* createCopy (int newWidth = -1,
  35651. int newHeight = -1,
  35652. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  35653. /** Returns a new single-channel image which is a copy of the alpha-channel of this image.
  35654. */
  35655. virtual Image* createCopyOfAlphaChannel() const;
  35656. /** Returns the colour of one of the pixels in the image.
  35657. If the co-ordinates given are beyond the image's boundaries, this will
  35658. return Colours::transparentBlack.
  35659. (0, 0) is the image's top-left corner.
  35660. @see getAlphaAt, setPixelAt, blendPixelAt
  35661. */
  35662. virtual const Colour getPixelAt (int x, int y) const;
  35663. /** Sets the colour of one of the image's pixels.
  35664. If the co-ordinates are beyond the image's boundaries, then nothing will
  35665. happen.
  35666. Note that unlike blendPixelAt(), this won't do any alpha-blending, it'll
  35667. just replace the existing pixel with the given one. The colour's opacity
  35668. will be ignored if this image doesn't have an alpha-channel.
  35669. (0, 0) is the image's top-left corner.
  35670. @see blendPixelAt
  35671. */
  35672. virtual void setPixelAt (int x, int y, const Colour& colour);
  35673. /** Changes the opacity of a pixel.
  35674. This only has an effect if the image has an alpha channel and if the
  35675. given co-ordinates are inside the image's boundary.
  35676. The multiplier must be in the range 0 to 1.0, and the current alpha
  35677. at the given co-ordinates will be multiplied by this value.
  35678. @see getAlphaAt, setPixelAt
  35679. */
  35680. virtual void multiplyAlphaAt (int x, int y, float multiplier);
  35681. /** Changes the overall opacity of the image.
  35682. This will multiply the alpha value of each pixel in the image by the given
  35683. amount (limiting the resulting alpha values between 0 and 255). This allows
  35684. you to make an image more or less transparent.
  35685. If the image doesn't have an alpha channel, this won't have any effect.
  35686. */
  35687. virtual void multiplyAllAlphas (float amountToMultiplyBy);
  35688. /** Changes all the colours to be shades of grey, based on their current luminosity.
  35689. */
  35690. virtual void desaturate();
  35691. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  35692. You should only use this class as a last resort - messing about with the internals of
  35693. an image is only recommended for people who really know what they're doing!
  35694. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  35695. hanging around while the image is being used elsewhere.
  35696. Depending on the way the image class is implemented, this may create a temporary buffer
  35697. which is copied back to the image when the object is deleted, or it may just get a pointer
  35698. directly into the image's raw data.
  35699. You can use the stride and data values in this class directly, but don't alter them!
  35700. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  35701. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  35702. */
  35703. class BitmapData
  35704. {
  35705. public:
  35706. BitmapData (Image& image, int x, int y, int w, int h, bool needsToBeWritable);
  35707. BitmapData (const Image& image, int x, int y, int w, int h);
  35708. ~BitmapData();
  35709. /** Returns a pointer to the start of a line in the image.
  35710. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  35711. sure it's not out-of-range.
  35712. */
  35713. inline uint8* getLinePointer (int y) const { return data + y * lineStride; }
  35714. /** Returns a pointer to a pixel in the image.
  35715. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  35716. not out-of-range.
  35717. */
  35718. inline uint8* getPixelPointer (int x, int y) const { return data + y * lineStride + x * pixelStride; }
  35719. uint8* data;
  35720. const PixelFormat pixelFormat;
  35721. int lineStride, pixelStride, width, height;
  35722. private:
  35723. BitmapData (const BitmapData&);
  35724. BitmapData& operator= (const BitmapData&);
  35725. };
  35726. /** Copies some pixel values to a rectangle of the image.
  35727. The format of the pixel data must match that of the image itself, and the
  35728. rectangle supplied must be within the image's bounds.
  35729. */
  35730. virtual void setPixelData (int destX, int destY, int destW, int destH,
  35731. const uint8* sourcePixelData, int sourceLineStride);
  35732. /** Copies a section of the image to somewhere else within itself.
  35733. */
  35734. virtual void moveImageSection (int destX, int destY,
  35735. int sourceX, int sourceY,
  35736. int width, int height);
  35737. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  35738. of the image.
  35739. @param result the list that will have the area added to it
  35740. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  35741. above this level will be considered opaque
  35742. */
  35743. void createSolidAreaMask (RectangleList& result,
  35744. float alphaThreshold = 0.5f) const;
  35745. juce_UseDebuggingNewOperator
  35746. /** Creates a context suitable for drawing onto this image.
  35747. Don't call this method directly! It's used internally by the Graphics class.
  35748. */
  35749. virtual LowLevelGraphicsContext* createLowLevelContext();
  35750. protected:
  35751. friend class BitmapData;
  35752. const PixelFormat format;
  35753. const int imageWidth, imageHeight;
  35754. /** Used internally so that subclasses can call a constructor that doesn't allocate memory */
  35755. Image (PixelFormat format,
  35756. int imageWidth,
  35757. int imageHeight);
  35758. int pixelStride, lineStride;
  35759. HeapBlock <uint8> imageDataAllocated;
  35760. uint8* imageData;
  35761. private:
  35762. Image& operator= (const Image&);
  35763. };
  35764. #endif // __JUCE_IMAGE_JUCEHEADER__
  35765. /*** End of inlined file: juce_Image.h ***/
  35766. /**
  35767. A class to asynchronously scan for details about the files in a directory.
  35768. This keeps a list of files and some information about them, using a background
  35769. thread to scan for more files. As files are found, it broadcasts change messages
  35770. to tell any listeners.
  35771. @see FileListComponent, FileBrowserComponent
  35772. */
  35773. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  35774. public TimeSliceClient
  35775. {
  35776. public:
  35777. /** Creates a directory list.
  35778. To set the directory it should point to, use setDirectory(), which will
  35779. also start it scanning for files on the background thread.
  35780. When the background thread finds and adds new files to this list, the
  35781. ChangeBroadcaster class will send a change message, so you can register
  35782. listeners and update them when the list changes.
  35783. @param fileFilter an optional filter to select which files are
  35784. included in the list. If this is 0, then all files
  35785. and directories are included. Make sure that the
  35786. filter doesn't get deleted during the lifetime of this
  35787. object
  35788. @param threadToUse a thread object that this list can use
  35789. to scan for files as a background task. Make sure
  35790. that the thread you give it has been started, or you
  35791. won't get any files!
  35792. */
  35793. DirectoryContentsList (const FileFilter* fileFilter,
  35794. TimeSliceThread& threadToUse);
  35795. /** Destructor. */
  35796. ~DirectoryContentsList();
  35797. /** Sets the directory to look in for files.
  35798. If the directory that's passed in is different to the current one, this will
  35799. also start the background thread scanning it for files.
  35800. */
  35801. void setDirectory (const File& directory,
  35802. bool includeDirectories,
  35803. bool includeFiles);
  35804. /** Returns the directory that's currently being used. */
  35805. const File& getDirectory() const;
  35806. /** Clears the list, and stops the thread scanning for files. */
  35807. void clear();
  35808. /** Clears the list and restarts scanning the directory for files. */
  35809. void refresh();
  35810. /** True if the background thread hasn't yet finished scanning for files. */
  35811. bool isStillLoading() const;
  35812. /** Tells the list whether or not to ignore hidden files.
  35813. By default these are ignored.
  35814. */
  35815. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  35816. /** Returns true if hidden files are ignored.
  35817. @see setIgnoresHiddenFiles
  35818. */
  35819. bool ignoresHiddenFiles() const;
  35820. /** Contains cached information about one of the files in a DirectoryContentsList.
  35821. */
  35822. struct FileInfo
  35823. {
  35824. /** The filename.
  35825. This isn't a full pathname, it's just the last part of the path, same as you'd
  35826. get from File::getFileName().
  35827. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  35828. */
  35829. String filename;
  35830. /** File size in bytes. */
  35831. int64 fileSize;
  35832. /** File modification time.
  35833. As supplied by File::getLastModificationTime().
  35834. */
  35835. Time modificationTime;
  35836. /** File creation time.
  35837. As supplied by File::getCreationTime().
  35838. */
  35839. Time creationTime;
  35840. /** True if the file is a directory. */
  35841. bool isDirectory;
  35842. /** True if the file is read-only. */
  35843. bool isReadOnly;
  35844. };
  35845. /** Returns the number of files currently available in the list.
  35846. The info about one of these files can be retrieved with getFileInfo() or
  35847. getFile().
  35848. Obviously as the background thread runs and scans the directory for files, this
  35849. number will change.
  35850. @see getFileInfo, getFile
  35851. */
  35852. int getNumFiles() const;
  35853. /** Returns the cached information about one of the files in the list.
  35854. If the index is in-range, this will return true and will copy the file's details
  35855. to the structure that is passed-in.
  35856. If it returns false, then the index wasn't in range, and the structure won't
  35857. be affected.
  35858. @see getNumFiles, getFile
  35859. */
  35860. bool getFileInfo (int index, FileInfo& resultInfo) const;
  35861. /** Returns one of the files in the list.
  35862. @param index should be less than getNumFiles(). If this is out-of-range, the
  35863. return value will be File::nonexistent
  35864. @see getNumFiles, getFileInfo
  35865. */
  35866. const File getFile (int index) const;
  35867. /** Returns the file filter being used.
  35868. The filter is specified in the constructor.
  35869. */
  35870. const FileFilter* getFilter() const { return fileFilter; }
  35871. /** @internal */
  35872. bool useTimeSlice();
  35873. /** @internal */
  35874. TimeSliceThread& getTimeSliceThread() { return thread; }
  35875. /** @internal */
  35876. static int compareElements (const DirectoryContentsList::FileInfo* first,
  35877. const DirectoryContentsList::FileInfo* second);
  35878. juce_UseDebuggingNewOperator
  35879. private:
  35880. File root;
  35881. const FileFilter* fileFilter;
  35882. TimeSliceThread& thread;
  35883. int fileTypeFlags;
  35884. CriticalSection fileListLock;
  35885. OwnedArray <FileInfo> files;
  35886. ScopedPointer <DirectoryIterator> fileFindHandle;
  35887. bool volatile shouldStop;
  35888. void changed();
  35889. bool checkNextFile (bool& hasChanged);
  35890. bool addFile (const File& file, bool isDir,
  35891. const int64 fileSize, const Time& modTime,
  35892. const Time& creationTime, bool isReadOnly);
  35893. void setTypeFlags (int newFlags);
  35894. DirectoryContentsList (const DirectoryContentsList&);
  35895. DirectoryContentsList& operator= (const DirectoryContentsList&);
  35896. };
  35897. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  35898. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  35899. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  35900. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  35901. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  35902. /**
  35903. A listener for user selection events in a file browser.
  35904. This is used by a FileBrowserComponent or FileListComponent.
  35905. */
  35906. class JUCE_API FileBrowserListener
  35907. {
  35908. public:
  35909. /** Destructor. */
  35910. virtual ~FileBrowserListener();
  35911. /** Callback when the user selects a different file in the browser. */
  35912. virtual void selectionChanged() = 0;
  35913. /** Callback when the user clicks on a file in the browser. */
  35914. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  35915. /** Callback when the user double-clicks on a file in the browser. */
  35916. virtual void fileDoubleClicked (const File& file) = 0;
  35917. };
  35918. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  35919. /*** End of inlined file: juce_FileBrowserListener.h ***/
  35920. /**
  35921. A base class for components that display a list of the files in a directory.
  35922. @see DirectoryContentsList
  35923. */
  35924. class JUCE_API DirectoryContentsDisplayComponent
  35925. {
  35926. public:
  35927. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  35928. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  35929. /** Destructor. */
  35930. virtual ~DirectoryContentsDisplayComponent();
  35931. /** Returns the number of files the user has got selected.
  35932. @see getSelectedFile
  35933. */
  35934. virtual int getNumSelectedFiles() const = 0;
  35935. /** Returns one of the files that the user has currently selected.
  35936. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  35937. @see getNumSelectedFiles
  35938. */
  35939. virtual const File getSelectedFile (int index) const = 0;
  35940. /** Deselects any selected files. */
  35941. virtual void deselectAllFiles() = 0;
  35942. /** Scrolls this view to the top. */
  35943. virtual void scrollToTop() = 0;
  35944. /** Adds a listener to be told when files are selected or clicked.
  35945. @see removeListener
  35946. */
  35947. void addListener (FileBrowserListener* listener);
  35948. /** Removes a listener.
  35949. @see addListener
  35950. */
  35951. void removeListener (FileBrowserListener* listener);
  35952. /** A set of colour IDs to use to change the colour of various aspects of the list.
  35953. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  35954. methods.
  35955. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  35956. */
  35957. enum ColourIds
  35958. {
  35959. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  35960. textColourId = 0x1000541, /**< The colour for the text. */
  35961. };
  35962. /** @internal */
  35963. void sendSelectionChangeMessage();
  35964. /** @internal */
  35965. void sendDoubleClickMessage (const File& file);
  35966. /** @internal */
  35967. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  35968. juce_UseDebuggingNewOperator
  35969. protected:
  35970. DirectoryContentsList& fileList;
  35971. ListenerList <FileBrowserListener> listeners;
  35972. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  35973. DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  35974. };
  35975. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  35976. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  35977. #endif
  35978. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  35979. #endif
  35980. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  35981. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  35982. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  35983. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  35984. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  35985. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  35986. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  35987. /**
  35988. Base class for components that live inside a file chooser dialog box and
  35989. show previews of the files that get selected.
  35990. One of these allows special extra information to be displayed for files
  35991. in a dialog box as the user selects them. Each time the current file or
  35992. directory is changed, the selectedFileChanged() method will be called
  35993. to allow it to update itself appropriately.
  35994. @see FileChooser, ImagePreviewComponent
  35995. */
  35996. class JUCE_API FilePreviewComponent : public Component
  35997. {
  35998. public:
  35999. /** Creates a FilePreviewComponent. */
  36000. FilePreviewComponent();
  36001. /** Destructor. */
  36002. ~FilePreviewComponent();
  36003. /** Called to indicate that the user's currently selected file has changed.
  36004. @param newSelectedFile the newly selected file or directory, which may be
  36005. File::nonexistent if none is selected.
  36006. */
  36007. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36008. juce_UseDebuggingNewOperator
  36009. private:
  36010. FilePreviewComponent (const FilePreviewComponent&);
  36011. FilePreviewComponent& operator= (const FilePreviewComponent&);
  36012. };
  36013. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36014. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  36015. /**
  36016. A component for browsing and selecting a file or directory to open or save.
  36017. This contains a FileListComponent and adds various boxes and controls for
  36018. navigating and selecting a file. It can work in different modes so that it can
  36019. be used for loading or saving a file, or for choosing a directory.
  36020. @see FileChooserDialogBox, FileChooser, FileListComponent
  36021. */
  36022. class JUCE_API FileBrowserComponent : public Component,
  36023. public ChangeBroadcaster,
  36024. private FileBrowserListener,
  36025. private TextEditorListener,
  36026. private ButtonListener,
  36027. private ComboBoxListener,
  36028. private FileFilter
  36029. {
  36030. public:
  36031. /** Various options for the browser.
  36032. A combination of these is passed into the FileBrowserComponent constructor.
  36033. */
  36034. enum FileChooserFlags
  36035. {
  36036. openMode = 1, /**< specifies that the component should allow the user to
  36037. choose an existing file with the intention of opening it. */
  36038. saveMode = 2, /**< specifies that the component should allow the user to specify
  36039. the name of a file that will be used to save something. */
  36040. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  36041. conjunction with canSelectDirectories). */
  36042. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  36043. conjuction with canSelectFiles). */
  36044. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  36045. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  36046. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  36047. };
  36048. /** Creates a FileBrowserComponent.
  36049. @param flags A combination of flags from the FileChooserFlags enumeration,
  36050. used to specify the component's behaviour. The flags must contain
  36051. either openMode or saveMode, and canSelectFiles and/or
  36052. canSelectDirectories.
  36053. @param initialFileOrDirectory The file or directory that should be selected when
  36054. the component begins. If this is File::nonexistent,
  36055. a default directory will be chosen.
  36056. @param fileFilter an optional filter to use to determine which files
  36057. are shown. If this is 0 then all files are displayed. Note
  36058. that a pointer is kept internally to this object, so
  36059. make sure that it is not deleted before the browser object
  36060. is deleted.
  36061. @param previewComp an optional preview component that will be used to
  36062. show previews of files that the user selects
  36063. */
  36064. FileBrowserComponent (int flags,
  36065. const File& initialFileOrDirectory,
  36066. const FileFilter* fileFilter,
  36067. FilePreviewComponent* previewComp);
  36068. /** Destructor. */
  36069. ~FileBrowserComponent();
  36070. /** Returns the number of files that the user has got selected.
  36071. If multiple select isn't active, this will only be 0 or 1. To get the complete
  36072. list of files they've chosen, pass an index to getCurrentFile().
  36073. */
  36074. int getNumSelectedFiles() const throw();
  36075. /** Returns one of the files that the user has chosen.
  36076. If the box has multi-select enabled, the index lets you specify which of the files
  36077. to get - see getNumSelectedFiles() to find out how many files were chosen.
  36078. @see getHighlightedFile
  36079. */
  36080. const File getSelectedFile (int index) const throw();
  36081. /** Deselects any files that are currently selected.
  36082. */
  36083. void deselectAllFiles();
  36084. /** Returns true if the currently selected file(s) are usable.
  36085. This can be used to decide whether the user can press "ok" for the
  36086. current file. What it does depends on the mode, so for example in an "open"
  36087. mode, this only returns true if a file has been selected and if it exists.
  36088. In a "save" mode, a non-existent file would also be valid.
  36089. */
  36090. bool currentFileIsValid() const;
  36091. /** This returns the last item in the view that the user has highlighted.
  36092. This may be different from getCurrentFile(), which returns the value
  36093. that is shown in the filename box, and if there are multiple selections,
  36094. this will only return one of them.
  36095. @see getSelectedFile
  36096. */
  36097. const File getHighlightedFile() const throw();
  36098. /** Returns the directory whose contents are currently being shown in the listbox. */
  36099. const File getRoot() const;
  36100. /** Changes the directory that's being shown in the listbox. */
  36101. void setRoot (const File& newRootDirectory);
  36102. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36103. void goUp();
  36104. /** Refreshes the directory that's currently being listed. */
  36105. void refresh();
  36106. /** Returns a verb to describe what should happen when the file is accepted.
  36107. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36108. mode, it'll be "Save", etc.
  36109. */
  36110. virtual const String getActionVerb() const;
  36111. /** Returns true if the saveMode flag was set when this component was created.
  36112. */
  36113. bool isSaveMode() const throw();
  36114. /** Adds a listener to be told when the user selects and clicks on files.
  36115. @see removeListener
  36116. */
  36117. void addListener (FileBrowserListener* listener);
  36118. /** Removes a listener.
  36119. @see addListener
  36120. */
  36121. void removeListener (FileBrowserListener* listener);
  36122. /** @internal */
  36123. void resized();
  36124. /** @internal */
  36125. void buttonClicked (Button* b);
  36126. /** @internal */
  36127. void comboBoxChanged (ComboBox*);
  36128. /** @internal */
  36129. void textEditorTextChanged (TextEditor& editor);
  36130. /** @internal */
  36131. void textEditorReturnKeyPressed (TextEditor& editor);
  36132. /** @internal */
  36133. void textEditorEscapeKeyPressed (TextEditor& editor);
  36134. /** @internal */
  36135. void textEditorFocusLost (TextEditor& editor);
  36136. /** @internal */
  36137. bool keyPressed (const KeyPress& key);
  36138. /** @internal */
  36139. void selectionChanged();
  36140. /** @internal */
  36141. void fileClicked (const File& f, const MouseEvent& e);
  36142. /** @internal */
  36143. void fileDoubleClicked (const File& f);
  36144. /** @internal */
  36145. bool isFileSuitable (const File& file) const;
  36146. /** @internal */
  36147. bool isDirectorySuitable (const File&) const;
  36148. /** @internal */
  36149. FilePreviewComponent* getPreviewComponent() const throw();
  36150. juce_UseDebuggingNewOperator
  36151. protected:
  36152. virtual const BigInteger getRoots (StringArray& rootNames, StringArray& rootPaths);
  36153. private:
  36154. ScopedPointer <DirectoryContentsList> fileList;
  36155. const FileFilter* fileFilter;
  36156. int flags;
  36157. File currentRoot;
  36158. Array<File> chosenFiles;
  36159. ListenerList <FileBrowserListener> listeners;
  36160. DirectoryContentsDisplayComponent* fileListComponent;
  36161. FilePreviewComponent* previewComp;
  36162. ComboBox* currentPathBox;
  36163. TextEditor* filenameBox;
  36164. Button* goUpButton;
  36165. TimeSliceThread thread;
  36166. void sendListenerChangeMessage();
  36167. bool isFileOrDirSuitable (const File& f) const;
  36168. FileBrowserComponent (const FileBrowserComponent&);
  36169. FileBrowserComponent& operator= (const FileBrowserComponent&);
  36170. };
  36171. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36172. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  36173. #endif
  36174. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36175. #endif
  36176. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36177. /*** Start of inlined file: juce_FileChooser.h ***/
  36178. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36179. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36180. /**
  36181. Creates a dialog box to choose a file or directory to load or save.
  36182. To use a FileChooser:
  36183. - create one (as a local stack variable is the neatest way)
  36184. - call one of its browseFor.. methods
  36185. - if this returns true, the user has selected a file, so you can retrieve it
  36186. with the getResult() method.
  36187. e.g. @code
  36188. void loadMooseFile()
  36189. {
  36190. FileChooser myChooser ("Please select the moose you want to load...",
  36191. File::getSpecialLocation (File::userHomeDirectory),
  36192. "*.moose");
  36193. if (myChooser.browseForFileToOpen())
  36194. {
  36195. File mooseFile (myChooser.getResult());
  36196. loadMoose (mooseFile);
  36197. }
  36198. }
  36199. @endcode
  36200. */
  36201. class JUCE_API FileChooser
  36202. {
  36203. public:
  36204. /** Creates a FileChooser.
  36205. After creating one of these, use one of the browseFor... methods to display it.
  36206. @param dialogBoxTitle a text string to display in the dialog box to
  36207. tell the user what's going on
  36208. @param initialFileOrDirectory the file or directory that should be selected when
  36209. the dialog box opens. If this parameter is set to
  36210. File::nonexistent, a sensible default directory
  36211. will be used instead.
  36212. @param filePatternsAllowed a set of file patterns to specify which files can be
  36213. selected - each pattern should be separated by a
  36214. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36215. empty string means that all files are allowed
  36216. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36217. possible; if false, then a Juce-based browser dialog
  36218. box will always be used
  36219. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36220. */
  36221. FileChooser (const String& dialogBoxTitle,
  36222. const File& initialFileOrDirectory = File::nonexistent,
  36223. const String& filePatternsAllowed = String::empty,
  36224. bool useOSNativeDialogBox = true);
  36225. /** Destructor. */
  36226. ~FileChooser();
  36227. /** Shows a dialog box to choose a file to open.
  36228. This will display the dialog box modally, using an "open file" mode, so that
  36229. it won't allow non-existent files or directories to be chosen.
  36230. @param previewComponent an optional component to display inside the dialog
  36231. box to show special info about the files that the user
  36232. is browsing. The component will not be deleted by this
  36233. object, so the caller must take care of it.
  36234. @returns true if the user selected a file, in which case, use the getResult()
  36235. method to find out what it was. Returns false if they cancelled instead.
  36236. @see browseForFileToSave, browseForDirectory
  36237. */
  36238. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36239. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36240. The files that are returned can be obtained by calling getResults(). See
  36241. browseForFileToOpen() for more info about the behaviour of this method.
  36242. */
  36243. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36244. /** Shows a dialog box to choose a file to save.
  36245. This will display the dialog box modally, using an "save file" mode, so it
  36246. will allow non-existent files to be chosen, but not directories.
  36247. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36248. the user if they're sure they want to overwrite a file that already
  36249. exists
  36250. @returns true if the user chose a file and pressed 'ok', in which case, use
  36251. the getResult() method to find out what the file was. Returns false
  36252. if they cancelled instead.
  36253. @see browseForFileToOpen, browseForDirectory
  36254. */
  36255. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  36256. /** Shows a dialog box to choose a directory.
  36257. This will display the dialog box modally, using an "open directory" mode, so it
  36258. will only allow directories to be returned, not files.
  36259. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36260. the getResult() method to find out what they chose. Returns false
  36261. if they cancelled instead.
  36262. @see browseForFileToOpen, browseForFileToSave
  36263. */
  36264. bool browseForDirectory();
  36265. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  36266. The files that are returned can be obtained by calling getResults(). See
  36267. browseForFileToOpen() for more info about the behaviour of this method.
  36268. */
  36269. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  36270. /** Returns the last file that was chosen by one of the browseFor methods.
  36271. After calling the appropriate browseFor... method, this method lets you
  36272. find out what file or directory they chose.
  36273. Note that the file returned is only valid if the browse method returned true (i.e.
  36274. if the user pressed 'ok' rather than cancelling).
  36275. If you're using a multiple-file select, then use the getResults() method instead,
  36276. to obtain the list of all files chosen.
  36277. @see getResults
  36278. */
  36279. const File getResult() const;
  36280. /** Returns a list of all the files that were chosen during the last call to a
  36281. browse method.
  36282. This array may be empty if no files were chosen, or can contain multiple entries
  36283. if multiple files were chosen.
  36284. @see getResult
  36285. */
  36286. const Array<File>& getResults() const;
  36287. juce_UseDebuggingNewOperator
  36288. private:
  36289. String title, filters;
  36290. File startingFile;
  36291. Array<File> results;
  36292. bool useNativeDialogBox;
  36293. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  36294. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36295. FilePreviewComponent* previewComponent);
  36296. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  36297. const String& filters, bool selectsDirectories, bool selectsFiles,
  36298. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36299. FilePreviewComponent* previewComponent);
  36300. };
  36301. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36302. /*** End of inlined file: juce_FileChooser.h ***/
  36303. #endif
  36304. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36305. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  36306. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36307. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36308. /*** Start of inlined file: juce_ResizableWindow.h ***/
  36309. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36310. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36311. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  36312. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36313. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36314. /*** Start of inlined file: juce_DropShadower.h ***/
  36315. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36316. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36317. /**
  36318. Adds a drop-shadow to a component.
  36319. This object creates and manages a set of components which sit around a
  36320. component, creating a gaussian shadow around it. The components will track
  36321. the position of the component and if it's brought to the front they'll also
  36322. follow this.
  36323. For desktop windows you don't need to use this class directly - just
  36324. set the Component::windowHasDropShadow flag when calling
  36325. Component::addToDesktop(), and the system will create one of these if it's
  36326. needed (which it obviously isn't on the Mac, for example).
  36327. */
  36328. class JUCE_API DropShadower : public ComponentListener
  36329. {
  36330. public:
  36331. /** Creates a DropShadower.
  36332. @param alpha the opacity of the shadows, from 0 to 1.0
  36333. @param xOffset the horizontal displacement of the shadow, in pixels
  36334. @param yOffset the vertical displacement of the shadow, in pixels
  36335. @param blurRadius the radius of the blur to use for creating the shadow
  36336. */
  36337. DropShadower (float alpha = 0.5f,
  36338. int xOffset = 1,
  36339. int yOffset = 5,
  36340. float blurRadius = 10.0f);
  36341. /** Destructor. */
  36342. virtual ~DropShadower();
  36343. /** Attaches the DropShadower to the component you want to shadow. */
  36344. void setOwner (Component* componentToFollow);
  36345. /** @internal */
  36346. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36347. /** @internal */
  36348. void componentBroughtToFront (Component& component);
  36349. /** @internal */
  36350. void componentChildrenChanged (Component& component);
  36351. /** @internal */
  36352. void componentParentHierarchyChanged (Component& component);
  36353. /** @internal */
  36354. void componentVisibilityChanged (Component& component);
  36355. juce_UseDebuggingNewOperator
  36356. private:
  36357. Component* owner;
  36358. int numShadows;
  36359. Component* shadowWindows[4];
  36360. Image* shadowImageSections[12];
  36361. const int shadowEdge, xOffset, yOffset;
  36362. const float alpha, blurRadius;
  36363. bool inDestructor, reentrant;
  36364. void updateShadows();
  36365. void setShadowImage (Image* const src,
  36366. const int num,
  36367. const int w, const int h,
  36368. const int sx, const int sy);
  36369. void bringShadowWindowsToFront();
  36370. void deleteShadowWindows();
  36371. DropShadower (const DropShadower&);
  36372. DropShadower& operator= (const DropShadower&);
  36373. };
  36374. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  36375. /*** End of inlined file: juce_DropShadower.h ***/
  36376. /**
  36377. A base class for top-level windows.
  36378. This class is used for components that are considered a major part of your
  36379. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  36380. etc. Things like menus that pop up briefly aren't derived from it.
  36381. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  36382. could itself be the child of another component.
  36383. The class manages a list of all instances of top-level windows that are in use,
  36384. and each one is also given the concept of being "active". The active window is
  36385. one that is actively being used by the user. This isn't quite the same as the
  36386. component with the keyboard focus, because there may be a popup menu or other
  36387. temporary window which gets keyboard focus while the active top level window is
  36388. unchanged.
  36389. A top-level window also has an optional drop-shadow.
  36390. @see ResizableWindow, DocumentWindow, DialogWindow
  36391. */
  36392. class JUCE_API TopLevelWindow : public Component
  36393. {
  36394. public:
  36395. /** Creates a TopLevelWindow.
  36396. @param name the name to give the component
  36397. @param addToDesktop if true, the window will be automatically added to the
  36398. desktop; if false, you can use it as a child component
  36399. */
  36400. TopLevelWindow (const String& name, bool addToDesktop);
  36401. /** Destructor. */
  36402. ~TopLevelWindow();
  36403. /** True if this is currently the TopLevelWindow that is actively being used.
  36404. This isn't quite the same as having keyboard focus, because the focus may be
  36405. on a child component or a temporary pop-up menu, etc, while this window is
  36406. still considered to be active.
  36407. @see activeWindowStatusChanged
  36408. */
  36409. bool isActiveWindow() const throw() { return windowIsActive_; }
  36410. /** This will set the bounds of the window so that it's centred in front of another
  36411. window.
  36412. If your app has a few windows open and want to pop up a dialog box for one of
  36413. them, you can use this to show it in front of the relevent parent window, which
  36414. is a bit neater than just having it appear in the middle of the screen.
  36415. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  36416. be used instead. If no window is focused, it'll just default to the middle of the
  36417. screen.
  36418. */
  36419. void centreAroundComponent (Component* componentToCentreAround,
  36420. int width, int height);
  36421. /** Turns the drop-shadow on and off. */
  36422. void setDropShadowEnabled (bool useShadow);
  36423. /** Sets whether an OS-native title bar will be used, or a Juce one.
  36424. @see isUsingNativeTitleBar
  36425. */
  36426. void setUsingNativeTitleBar (bool useNativeTitleBar);
  36427. /** Returns true if the window is currently using an OS-native title bar.
  36428. @see setUsingNativeTitleBar
  36429. */
  36430. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  36431. /** Returns the number of TopLevelWindow objects currently in use.
  36432. @see getTopLevelWindow
  36433. */
  36434. static int getNumTopLevelWindows() throw();
  36435. /** Returns one of the TopLevelWindow objects currently in use.
  36436. The index is 0 to (getNumTopLevelWindows() - 1).
  36437. */
  36438. static TopLevelWindow* getTopLevelWindow (int index) throw();
  36439. /** Returns the currently-active top level window.
  36440. There might not be one, of course, so this can return 0.
  36441. */
  36442. static TopLevelWindow* getActiveTopLevelWindow() throw();
  36443. juce_UseDebuggingNewOperator
  36444. /** @internal */
  36445. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  36446. protected:
  36447. /** This callback happens when this window becomes active or inactive.
  36448. @see isActiveWindow
  36449. */
  36450. virtual void activeWindowStatusChanged();
  36451. /** @internal */
  36452. void focusOfChildComponentChanged (FocusChangeType cause);
  36453. /** @internal */
  36454. void parentHierarchyChanged();
  36455. /** @internal */
  36456. void visibilityChanged();
  36457. /** @internal */
  36458. virtual int getDesktopWindowStyleFlags() const;
  36459. /** @internal */
  36460. void recreateDesktopWindow();
  36461. private:
  36462. friend class TopLevelWindowManager;
  36463. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  36464. ScopedPointer <DropShadower> shadower;
  36465. void setWindowActive (bool isNowActive);
  36466. TopLevelWindow (const TopLevelWindow&);
  36467. TopLevelWindow& operator= (const TopLevelWindow&);
  36468. };
  36469. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36470. /*** End of inlined file: juce_TopLevelWindow.h ***/
  36471. /*** Start of inlined file: juce_ComponentDragger.h ***/
  36472. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36473. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36474. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  36475. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36476. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36477. /**
  36478. A class that imposes restrictions on a Component's size or position.
  36479. This is used by classes such as ResizableCornerComponent,
  36480. ResizableBorderComponent and ResizableWindow.
  36481. The base class can impose some basic size and position limits, but you can
  36482. also subclass this for custom uses.
  36483. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  36484. */
  36485. class JUCE_API ComponentBoundsConstrainer
  36486. {
  36487. public:
  36488. /** When first created, the object will not impose any restrictions on the components. */
  36489. ComponentBoundsConstrainer() throw();
  36490. /** Destructor. */
  36491. virtual ~ComponentBoundsConstrainer();
  36492. /** Imposes a minimum width limit. */
  36493. void setMinimumWidth (int minimumWidth) throw();
  36494. /** Returns the current minimum width. */
  36495. int getMinimumWidth() const throw() { return minW; }
  36496. /** Imposes a maximum width limit. */
  36497. void setMaximumWidth (int maximumWidth) throw();
  36498. /** Returns the current maximum width. */
  36499. int getMaximumWidth() const throw() { return maxW; }
  36500. /** Imposes a minimum height limit. */
  36501. void setMinimumHeight (int minimumHeight) throw();
  36502. /** Returns the current minimum height. */
  36503. int getMinimumHeight() const throw() { return minH; }
  36504. /** Imposes a maximum height limit. */
  36505. void setMaximumHeight (int maximumHeight) throw();
  36506. /** Returns the current maximum height. */
  36507. int getMaximumHeight() const throw() { return maxH; }
  36508. /** Imposes a minimum width and height limit. */
  36509. void setMinimumSize (int minimumWidth,
  36510. int minimumHeight) throw();
  36511. /** Imposes a maximum width and height limit. */
  36512. void setMaximumSize (int maximumWidth,
  36513. int maximumHeight) throw();
  36514. /** Set all the maximum and minimum dimensions. */
  36515. void setSizeLimits (int minimumWidth,
  36516. int minimumHeight,
  36517. int maximumWidth,
  36518. int maximumHeight) throw();
  36519. /** Sets the amount by which the component is allowed to go off-screen.
  36520. The values indicate how many pixels must remain on-screen when dragged off
  36521. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  36522. when the component goes off the top of the screen, its y-position will be
  36523. clipped so that there are always at least 10 pixels on-screen. In other words,
  36524. the lowest y-position it can take would be (10 - the component's height).
  36525. If you pass 0 or less for one of these amounts, the component is allowed
  36526. to move beyond that edge completely, with no restrictions at all.
  36527. If you pass a very large number (i.e. larger that the dimensions of the
  36528. component itself), then the component won't be allowed to overlap that
  36529. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  36530. the component will bump into the left side of the screen and go no further.
  36531. */
  36532. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  36533. int minimumWhenOffTheLeft,
  36534. int minimumWhenOffTheBottom,
  36535. int minimumWhenOffTheRight) throw();
  36536. /** Specifies a width-to-height ratio that the resizer should always maintain.
  36537. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  36538. will always be maintained as this multiple of the height.
  36539. @see setResizeLimits
  36540. */
  36541. void setFixedAspectRatio (double widthOverHeight) throw();
  36542. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  36543. If no aspect ratio is being enforced, this will return 0.
  36544. */
  36545. double getFixedAspectRatio() const throw();
  36546. /** This callback changes the given co-ordinates to impose whatever the current
  36547. constraints are set to be.
  36548. @param bounds the target position that should be examined and adjusted
  36549. @param previousBounds the component's current size
  36550. @param limits the region in which the component can be positioned
  36551. @param isStretchingTop whether the top edge of the component is being resized
  36552. @param isStretchingLeft whether the left edge of the component is being resized
  36553. @param isStretchingBottom whether the bottom edge of the component is being resized
  36554. @param isStretchingRight whether the right edge of the component is being resized
  36555. */
  36556. virtual void checkBounds (Rectangle<int>& bounds,
  36557. const Rectangle<int>& previousBounds,
  36558. const Rectangle<int>& limits,
  36559. bool isStretchingTop,
  36560. bool isStretchingLeft,
  36561. bool isStretchingBottom,
  36562. bool isStretchingRight);
  36563. /** This callback happens when the resizer is about to start dragging. */
  36564. virtual void resizeStart();
  36565. /** This callback happens when the resizer has finished dragging. */
  36566. virtual void resizeEnd();
  36567. /** Checks the given bounds, and then sets the component to the corrected size. */
  36568. void setBoundsForComponent (Component* const component,
  36569. const Rectangle<int>& bounds,
  36570. bool isStretchingTop,
  36571. bool isStretchingLeft,
  36572. bool isStretchingBottom,
  36573. bool isStretchingRight);
  36574. /** Performs a check on the current size of a component, and moves or resizes
  36575. it if it fails the constraints.
  36576. */
  36577. void checkComponentBounds (Component* component);
  36578. /** Called by setBoundsForComponent() to apply a new constrained size to a
  36579. component.
  36580. By default this just calls setBounds(), but it virtual in case it's needed for
  36581. extremely cunning purposes.
  36582. */
  36583. virtual void applyBoundsToComponent (Component* component,
  36584. const Rectangle<int>& bounds);
  36585. juce_UseDebuggingNewOperator
  36586. private:
  36587. int minW, maxW, minH, maxH;
  36588. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  36589. double aspectRatio;
  36590. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  36591. ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  36592. };
  36593. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  36594. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  36595. /**
  36596. An object to take care of the logic for dragging components around with the mouse.
  36597. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  36598. then in your mouseDrag() callback, call dragComponent().
  36599. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  36600. to limit the component's position and keep it on-screen.
  36601. e.g. @code
  36602. class MyDraggableComp
  36603. {
  36604. ComponentDragger myDragger;
  36605. void mouseDown (const MouseEvent& e)
  36606. {
  36607. myDragger.startDraggingComponent (this, 0);
  36608. }
  36609. void mouseDrag (const MouseEvent& e)
  36610. {
  36611. myDragger.dragComponent (this, e);
  36612. }
  36613. };
  36614. @endcode
  36615. */
  36616. class JUCE_API ComponentDragger
  36617. {
  36618. public:
  36619. /** Creates a ComponentDragger. */
  36620. ComponentDragger();
  36621. /** Destructor. */
  36622. virtual ~ComponentDragger();
  36623. /** Call this from your component's mouseDown() method, to prepare for dragging.
  36624. @param componentToDrag the component that you want to drag
  36625. @param constrainer a constrainer object to use to keep the component
  36626. from going offscreen
  36627. @see dragComponent
  36628. */
  36629. void startDraggingComponent (Component* const componentToDrag,
  36630. ComponentBoundsConstrainer* constrainer);
  36631. /** Call this from your mouseDrag() callback to move the component.
  36632. This will move the component, but will first check the validity of the
  36633. component's new position using the checkPosition() method, which you
  36634. can override if you need to enforce special positioning limits on the
  36635. component.
  36636. @param componentToDrag the component that you want to drag
  36637. @param e the current mouse-drag event
  36638. @see dragComponent
  36639. */
  36640. void dragComponent (Component* const componentToDrag,
  36641. const MouseEvent& e);
  36642. juce_UseDebuggingNewOperator
  36643. private:
  36644. ComponentBoundsConstrainer* constrainer;
  36645. Point<int> originalPos;
  36646. ComponentDragger (const ComponentDragger&);
  36647. ComponentDragger& operator= (const ComponentDragger&);
  36648. };
  36649. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  36650. /*** End of inlined file: juce_ComponentDragger.h ***/
  36651. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  36652. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36653. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36654. /**
  36655. A component that resizes its parent window when dragged.
  36656. This component forms a frame around the edge of a component, allowing it to
  36657. be dragged by the edges or corners to resize it - like the way windows are
  36658. resized in MSWindows or Linux.
  36659. To use it, just add it to your component, making it fill the entire parent component
  36660. (there's a mouse hit-test that only traps mouse-events which land around the
  36661. edge of the component, so it's even ok to put it on top of any other components
  36662. you're using). Make sure you rescale the resizer component to fill the parent
  36663. each time the parent's size changes.
  36664. @see ResizableCornerComponent
  36665. */
  36666. class JUCE_API ResizableBorderComponent : public Component
  36667. {
  36668. public:
  36669. /** Creates a resizer.
  36670. Pass in the target component which you want to be resized when this one is
  36671. dragged.
  36672. The target component will usually be a parent of the resizer component, but this
  36673. isn't mandatory.
  36674. Remember that when the target component is resized, it'll need to move and
  36675. resize this component to keep it in place, as this won't happen automatically.
  36676. If the constrainer parameter is non-zero, then this object will be used to enforce
  36677. limits on the size and position that the component can be stretched to. Make sure
  36678. that the constrainer isn't deleted while still in use by this object.
  36679. @see ComponentBoundsConstrainer
  36680. */
  36681. ResizableBorderComponent (Component* componentToResize,
  36682. ComponentBoundsConstrainer* constrainer);
  36683. /** Destructor. */
  36684. ~ResizableBorderComponent();
  36685. /** Specifies how many pixels wide the draggable edges of this component are.
  36686. @see getBorderThickness
  36687. */
  36688. void setBorderThickness (const BorderSize& newBorderSize);
  36689. /** Returns the number of pixels wide that the draggable edges of this component are.
  36690. @see setBorderThickness
  36691. */
  36692. const BorderSize getBorderThickness() const;
  36693. /** Represents the different sections of a resizable border, which allow it to
  36694. resized in different ways.
  36695. */
  36696. class Zone
  36697. {
  36698. public:
  36699. enum Zones
  36700. {
  36701. centre = 0,
  36702. left = 1,
  36703. top = 2,
  36704. right = 4,
  36705. bottom = 8
  36706. };
  36707. /** Creates a Zone from a combination of the flags in \enum Zones. */
  36708. explicit Zone (int zoneFlags = 0) throw();
  36709. Zone (const Zone& other) throw();
  36710. Zone& operator= (const Zone& other) throw();
  36711. bool operator== (const Zone& other) const throw();
  36712. bool operator!= (const Zone& other) const throw();
  36713. /** Given a point within a rectangle with a resizable border, this returns the
  36714. zone that the point lies within.
  36715. */
  36716. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  36717. const BorderSize& border,
  36718. const Point<int>& position);
  36719. /** Returns an appropriate mouse-cursor for this resize zone. */
  36720. const MouseCursor getMouseCursor() const throw();
  36721. /** Returns true if dragging this zone will move the enire object without resizing it. */
  36722. bool isDraggingWholeObject() const throw() { return zone == centre; }
  36723. /** Returns true if dragging this zone will move the object's left edge. */
  36724. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  36725. /** Returns true if dragging this zone will move the object's right edge. */
  36726. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  36727. /** Returns true if dragging this zone will move the object's top edge. */
  36728. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  36729. /** Returns true if dragging this zone will move the object's bottom edge. */
  36730. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  36731. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  36732. applies to.
  36733. */
  36734. const Rectangle<int> resizeRectangleBy (Rectangle<int> original,
  36735. const Point<int>& distance) const throw();
  36736. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  36737. applies to.
  36738. */
  36739. const Rectangle<float> resizeRectangleBy (Rectangle<float> original,
  36740. const Point<float>& distance) const throw();
  36741. /** Returns the raw flags for this zone. */
  36742. int getZoneFlags() const throw() { return zone; }
  36743. private:
  36744. int zone;
  36745. };
  36746. juce_UseDebuggingNewOperator
  36747. protected:
  36748. /** @internal */
  36749. void paint (Graphics& g);
  36750. /** @internal */
  36751. void mouseEnter (const MouseEvent& e);
  36752. /** @internal */
  36753. void mouseMove (const MouseEvent& e);
  36754. /** @internal */
  36755. void mouseDown (const MouseEvent& e);
  36756. /** @internal */
  36757. void mouseDrag (const MouseEvent& e);
  36758. /** @internal */
  36759. void mouseUp (const MouseEvent& e);
  36760. /** @internal */
  36761. bool hitTest (int x, int y);
  36762. private:
  36763. Component::SafePointer<Component> component;
  36764. ComponentBoundsConstrainer* constrainer;
  36765. BorderSize borderSize;
  36766. Rectangle<int> originalBounds;
  36767. Zone mouseZone;
  36768. void updateMouseZone (const MouseEvent& e);
  36769. ResizableBorderComponent (const ResizableBorderComponent&);
  36770. ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  36771. };
  36772. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  36773. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  36774. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  36775. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36776. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36777. /** A component that resizes a parent window when dragged.
  36778. This is the small triangular stripey resizer component you get in the bottom-right
  36779. of windows (more commonly on the Mac than Windows). Put one in the corner of
  36780. a larger component and it will automatically resize its parent when it gets dragged
  36781. around.
  36782. @see ResizableFrameComponent
  36783. */
  36784. class JUCE_API ResizableCornerComponent : public Component
  36785. {
  36786. public:
  36787. /** Creates a resizer.
  36788. Pass in the target component which you want to be resized when this one is
  36789. dragged.
  36790. The target component will usually be a parent of the resizer component, but this
  36791. isn't mandatory.
  36792. Remember that when the target component is resized, it'll need to move and
  36793. resize this component to keep it in place, as this won't happen automatically.
  36794. If the constrainer parameter is non-zero, then this object will be used to enforce
  36795. limits on the size and position that the component can be stretched to. Make sure
  36796. that the constrainer isn't deleted while still in use by this object. If you
  36797. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  36798. @see ComponentBoundsConstrainer
  36799. */
  36800. ResizableCornerComponent (Component* componentToResize,
  36801. ComponentBoundsConstrainer* constrainer);
  36802. /** Destructor. */
  36803. ~ResizableCornerComponent();
  36804. juce_UseDebuggingNewOperator
  36805. protected:
  36806. /** @internal */
  36807. void paint (Graphics& g);
  36808. /** @internal */
  36809. void mouseDown (const MouseEvent& e);
  36810. /** @internal */
  36811. void mouseDrag (const MouseEvent& e);
  36812. /** @internal */
  36813. void mouseUp (const MouseEvent& e);
  36814. /** @internal */
  36815. bool hitTest (int x, int y);
  36816. private:
  36817. Component::SafePointer<Component> component;
  36818. ComponentBoundsConstrainer* constrainer;
  36819. Rectangle<int> originalBounds;
  36820. ResizableCornerComponent (const ResizableCornerComponent&);
  36821. ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  36822. };
  36823. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  36824. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  36825. /**
  36826. A base class for top-level windows that can be dragged around and resized.
  36827. To add content to the window, use its setContentComponent() method to
  36828. give it a component that will remain positioned inside it (leaving a gap around
  36829. the edges for a border).
  36830. It's not advisable to add child components directly to a ResizableWindow: put them
  36831. inside your content component instead. And overriding methods like resized(), moved(), etc
  36832. is also not recommended - instead override these methods for your content component.
  36833. (If for some obscure reason you do need to override these methods, always remember to
  36834. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  36835. decorations correctly).
  36836. By default resizing isn't enabled - use the setResizable() method to enable it and
  36837. to choose the style of resizing to use.
  36838. @see TopLevelWindow
  36839. */
  36840. class JUCE_API ResizableWindow : public TopLevelWindow
  36841. {
  36842. public:
  36843. /** Creates a ResizableWindow.
  36844. This constructor doesn't specify a background colour, so the LookAndFeel's default
  36845. background colour will be used.
  36846. @param name the name to give the component
  36847. @param addToDesktop if true, the window will be automatically added to the
  36848. desktop; if false, you can use it as a child component
  36849. */
  36850. ResizableWindow (const String& name,
  36851. bool addToDesktop);
  36852. /** Creates a ResizableWindow.
  36853. @param name the name to give the component
  36854. @param backgroundColour the colour to use for filling the window's background.
  36855. @param addToDesktop if true, the window will be automatically added to the
  36856. desktop; if false, you can use it as a child component
  36857. */
  36858. ResizableWindow (const String& name,
  36859. const Colour& backgroundColour,
  36860. bool addToDesktop);
  36861. /** Destructor.
  36862. If a content component has been set with setContentComponent(), it
  36863. will be deleted.
  36864. */
  36865. ~ResizableWindow();
  36866. /** Returns the colour currently being used for the window's background.
  36867. As a convenience the window will fill itself with this colour, but you
  36868. can override the paint() method if you need more customised behaviour.
  36869. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  36870. @see setBackgroundColour
  36871. */
  36872. const Colour getBackgroundColour() const throw();
  36873. /** Changes the colour currently being used for the window's background.
  36874. As a convenience the window will fill itself with this colour, but you
  36875. can override the paint() method if you need more customised behaviour.
  36876. Note that the opaque state of this window is altered by this call to reflect
  36877. the opacity of the colour passed-in. On window systems which can't support
  36878. semi-transparent windows this might cause problems, (though it's unlikely you'll
  36879. be using this class as a base for a semi-transparent component anyway).
  36880. You can also use the ResizableWindow::backgroundColourId colour id to set
  36881. this colour.
  36882. @see getBackgroundColour
  36883. */
  36884. void setBackgroundColour (const Colour& newColour);
  36885. /** Make the window resizable or fixed.
  36886. @param shouldBeResizable whether it's resizable at all
  36887. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  36888. bottom-right; if false, it'll use a ResizableBorderComponent
  36889. around the edge
  36890. @see setResizeLimits, isResizable
  36891. */
  36892. void setResizable (bool shouldBeResizable,
  36893. bool useBottomRightCornerResizer);
  36894. /** True if resizing is enabled.
  36895. @see setResizable
  36896. */
  36897. bool isResizable() const throw();
  36898. /** This sets the maximum and minimum sizes for the window.
  36899. If the window's current size is outside these limits, it will be resized to
  36900. make sure it's within them.
  36901. Calling setBounds() on the component will bypass any size checking - it's only when
  36902. the window is being resized by the user that these values are enforced.
  36903. @see setResizable, setFixedAspectRatio
  36904. */
  36905. void setResizeLimits (int newMinimumWidth,
  36906. int newMinimumHeight,
  36907. int newMaximumWidth,
  36908. int newMaximumHeight) throw();
  36909. /** Returns the bounds constrainer object that this window is using.
  36910. You can access this to change its properties.
  36911. */
  36912. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  36913. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  36914. A pointer to the object you pass in will be kept, but it won't be deleted
  36915. by this object, so it's the caller's responsiblity to manage it.
  36916. If you pass 0, then no contraints will be placed on the positioning of the window.
  36917. */
  36918. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  36919. /** Calls the window's setBounds method, after first checking these bounds
  36920. with the current constrainer.
  36921. @see setConstrainer
  36922. */
  36923. void setBoundsConstrained (const Rectangle<int>& bounds);
  36924. /** Returns true if the window is currently in full-screen mode.
  36925. @see setFullScreen
  36926. */
  36927. bool isFullScreen() const;
  36928. /** Puts the window into full-screen mode, or restores it to its normal size.
  36929. If true, the window will become full-screen; if false, it will return to the
  36930. last size it was before being made full-screen.
  36931. @see isFullScreen
  36932. */
  36933. void setFullScreen (bool shouldBeFullScreen);
  36934. /** Returns true if the window is currently minimised.
  36935. @see setMinimised
  36936. */
  36937. bool isMinimised() const;
  36938. /** Minimises the window, or restores it to its previous position and size.
  36939. When being un-minimised, it'll return to the last position and size it
  36940. was in before being minimised.
  36941. @see isMinimised
  36942. */
  36943. void setMinimised (bool shouldMinimise);
  36944. /** Returns a string which encodes the window's current size and position.
  36945. This string will encapsulate the window's size, position, and whether it's
  36946. in full-screen mode. It's intended for letting your application save and
  36947. restore a window's position.
  36948. Use the restoreWindowStateFromString() to restore from a saved state.
  36949. @see restoreWindowStateFromString
  36950. */
  36951. const String getWindowStateAsString();
  36952. /** Restores the window to a previously-saved size and position.
  36953. This restores the window's size, positon and full-screen status from an
  36954. string that was previously created with the getWindowStateAsString()
  36955. method.
  36956. @returns false if the string wasn't a valid window state
  36957. @see getWindowStateAsString
  36958. */
  36959. bool restoreWindowStateFromString (const String& previousState);
  36960. /** Returns the current content component.
  36961. This will be the component set by setContentComponent(), or 0 if none
  36962. has yet been specified.
  36963. @see setContentComponent
  36964. */
  36965. Component* getContentComponent() const throw() { return contentComponent; }
  36966. /** Changes the current content component.
  36967. This sets a component that will be placed in the centre of the ResizableWindow,
  36968. (leaving a space around the edge for the border).
  36969. You should never add components directly to a ResizableWindow (or any of its subclasses)
  36970. with addChildComponent(). Instead, add them to the content component.
  36971. @param newContentComponent the new component to use (or null to not use one) - this
  36972. component will be deleted either when replaced by another call
  36973. to this method, or when the ResizableWindow is deleted.
  36974. To remove a content component without deleting it, use
  36975. setContentComponent (0, false).
  36976. @param deleteOldOne if true, the previous content component will be deleted; if
  36977. false, the previous component will just be removed without
  36978. deleting it.
  36979. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  36980. it always fits around the size of the content component. If false, the
  36981. new content will be resized to fit the current space available.
  36982. */
  36983. void setContentComponent (Component* newContentComponent,
  36984. bool deleteOldOne = true,
  36985. bool resizeToFit = false);
  36986. /** Changes the window so that the content component ends up with the specified size.
  36987. This is basically a setSize call on the window, but which adds on the borders,
  36988. so you can specify the content component's target size.
  36989. */
  36990. void setContentComponentSize (int width, int height);
  36991. /** A set of colour IDs to use to change the colour of various aspects of the window.
  36992. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36993. methods.
  36994. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36995. */
  36996. enum ColourIds
  36997. {
  36998. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  36999. };
  37000. juce_UseDebuggingNewOperator
  37001. protected:
  37002. /** @internal */
  37003. void paint (Graphics& g);
  37004. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37005. void moved();
  37006. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37007. void resized();
  37008. /** @internal */
  37009. void mouseDown (const MouseEvent& e);
  37010. /** @internal */
  37011. void mouseDrag (const MouseEvent& e);
  37012. /** @internal */
  37013. void lookAndFeelChanged();
  37014. /** @internal */
  37015. void childBoundsChanged (Component* child);
  37016. /** @internal */
  37017. void parentSizeChanged();
  37018. /** @internal */
  37019. void visibilityChanged();
  37020. /** @internal */
  37021. void activeWindowStatusChanged();
  37022. /** @internal */
  37023. int getDesktopWindowStyleFlags() const;
  37024. /** Returns the width of the border to use around the window.
  37025. @see getContentComponentBorder
  37026. */
  37027. virtual const BorderSize getBorderThickness();
  37028. /** Returns the insets to use when positioning the content component.
  37029. @see getBorderThickness
  37030. */
  37031. virtual const BorderSize getContentComponentBorder();
  37032. #if JUCE_DEBUG
  37033. /** Overridden to warn people about adding components directly to this component
  37034. instead of using setContentComponent().
  37035. If you know what you're doing and are sure you really want to add a component, specify
  37036. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37037. */
  37038. void addChildComponent (Component* child, int zOrder = -1);
  37039. /** Overridden to warn people about adding components directly to this component
  37040. instead of using setContentComponent().
  37041. If you know what you're doing and are sure you really want to add a component, specify
  37042. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37043. */
  37044. void addAndMakeVisible (Component* child, int zOrder = -1);
  37045. #endif
  37046. ScopedPointer <ResizableCornerComponent> resizableCorner;
  37047. ScopedPointer <ResizableBorderComponent> resizableBorder;
  37048. private:
  37049. ScopedPointer <Component> contentComponent;
  37050. bool resizeToFitContent, fullscreen;
  37051. ComponentDragger dragger;
  37052. Rectangle<int> lastNonFullScreenPos;
  37053. ComponentBoundsConstrainer defaultConstrainer;
  37054. ComponentBoundsConstrainer* constrainer;
  37055. #if JUCE_DEBUG
  37056. bool hasBeenResized;
  37057. #endif
  37058. void updateLastPos();
  37059. ResizableWindow (const ResizableWindow&);
  37060. ResizableWindow& operator= (const ResizableWindow&);
  37061. // (xxx remove these eventually)
  37062. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37063. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  37064. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37065. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  37066. };
  37067. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37068. /*** End of inlined file: juce_ResizableWindow.h ***/
  37069. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  37070. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37071. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37072. /**
  37073. A glyph from a particular font, with a particular size, style,
  37074. typeface and position.
  37075. @see GlyphArrangement, Font
  37076. */
  37077. class JUCE_API PositionedGlyph
  37078. {
  37079. public:
  37080. /** Returns the character the glyph represents. */
  37081. juce_wchar getCharacter() const { return character; }
  37082. /** Checks whether the glyph is actually empty. */
  37083. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  37084. /** Returns the position of the glyph's left-hand edge. */
  37085. float getLeft() const { return x; }
  37086. /** Returns the position of the glyph's right-hand edge. */
  37087. float getRight() const { return x + w; }
  37088. /** Returns the y position of the glyph's baseline. */
  37089. float getBaselineY() const { return y; }
  37090. /** Returns the y position of the top of the glyph. */
  37091. float getTop() const { return y - font.getAscent(); }
  37092. /** Returns the y position of the bottom of the glyph. */
  37093. float getBottom() const { return y + font.getDescent(); }
  37094. /** Returns the bounds of the glyph. */
  37095. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  37096. /** Shifts the glyph's position by a relative amount. */
  37097. void moveBy (float deltaX, float deltaY);
  37098. /** Draws the glyph into a graphics context. */
  37099. void draw (const Graphics& g) const;
  37100. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  37101. void draw (const Graphics& g, const AffineTransform& transform) const;
  37102. /** Returns the path for this glyph.
  37103. @param path the glyph's outline will be appended to this path
  37104. */
  37105. void createPath (Path& path) const;
  37106. /** Checks to see if a point lies within this glyph. */
  37107. bool hitTest (float x, float y) const;
  37108. juce_UseDebuggingNewOperator
  37109. private:
  37110. friend class GlyphArrangement;
  37111. float x, y, w;
  37112. Font font;
  37113. juce_wchar character;
  37114. int glyph;
  37115. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  37116. PositionedGlyph (const PositionedGlyph& other);
  37117. };
  37118. /**
  37119. A set of glyphs, each with a position.
  37120. You can create a GlyphArrangement, text to it and then draw it onto a
  37121. graphics context. It's used internally by the text methods in the
  37122. Graphics class, but can be used directly if more control is needed.
  37123. @see Font, PositionedGlyph
  37124. */
  37125. class JUCE_API GlyphArrangement
  37126. {
  37127. public:
  37128. /** Creates an empty arrangement. */
  37129. GlyphArrangement();
  37130. /** Takes a copy of another arrangement. */
  37131. GlyphArrangement (const GlyphArrangement& other);
  37132. /** Copies another arrangement onto this one.
  37133. To add another arrangement without clearing this one, use addGlyphArrangement().
  37134. */
  37135. GlyphArrangement& operator= (const GlyphArrangement& other);
  37136. /** Destructor. */
  37137. ~GlyphArrangement();
  37138. /** Returns the total number of glyphs in the arrangement. */
  37139. int getNumGlyphs() const throw() { return glyphs.size(); }
  37140. /** Returns one of the glyphs from the arrangement.
  37141. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  37142. careful not to pass an out-of-range index here, as it
  37143. doesn't do any bounds-checking.
  37144. */
  37145. PositionedGlyph& getGlyph (int index) const;
  37146. /** Clears all text from the arrangement and resets it.
  37147. */
  37148. void clear();
  37149. /** Appends a line of text to the arrangement.
  37150. This will add the text as a single line, where x is the left-hand edge of the
  37151. first character, and y is the position for the text's baseline.
  37152. If the text contains new-lines or carriage-returns, this will ignore them - use
  37153. addJustifiedText() to add multi-line arrangements.
  37154. */
  37155. void addLineOfText (const Font& font,
  37156. const String& text,
  37157. float x, float y);
  37158. /** Adds a line of text, truncating it if it's wider than a specified size.
  37159. This is the same as addLineOfText(), but if the line's width exceeds the value
  37160. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  37161. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  37162. */
  37163. void addCurtailedLineOfText (const Font& font,
  37164. const String& text,
  37165. float x, float y,
  37166. float maxWidthPixels,
  37167. bool useEllipsis);
  37168. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  37169. This will add text to the arrangement, breaking it into new lines either where there
  37170. is a new-line or carriage-return character in the text, or where a line's width
  37171. exceeds the value set in maxLineWidth.
  37172. Each line that is added will be laid out using the flags set in horizontalLayout, so
  37173. the lines can be left- or right-justified, or centred horizontally in the space
  37174. between x and (x + maxLineWidth).
  37175. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  37176. lines will be placed below it, separated by a distance of font.getHeight().
  37177. */
  37178. void addJustifiedText (const Font& font,
  37179. const String& text,
  37180. float x, float y,
  37181. float maxLineWidth,
  37182. const Justification& horizontalLayout);
  37183. /** Tries to fit some text withing a given space.
  37184. This does its best to make the given text readable within the specified rectangle,
  37185. so it useful for labelling things.
  37186. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  37187. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  37188. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  37189. it's been truncated.
  37190. A Justification parameter lets you specify how the text is laid out within the rectangle,
  37191. both horizontally and vertically.
  37192. @see Graphics::drawFittedText
  37193. */
  37194. void addFittedText (const Font& font,
  37195. const String& text,
  37196. float x, float y, float width, float height,
  37197. const Justification& layout,
  37198. int maximumLinesToUse,
  37199. float minimumHorizontalScale = 0.7f);
  37200. /** Appends another glyph arrangement to this one. */
  37201. void addGlyphArrangement (const GlyphArrangement& other);
  37202. /** Draws this glyph arrangement to a graphics context.
  37203. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  37204. method, which renders the glyphs as filled vectors.
  37205. */
  37206. void draw (const Graphics& g) const;
  37207. /** Draws this glyph arrangement to a graphics context.
  37208. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  37209. method for non-transformed arrangements.
  37210. */
  37211. void draw (const Graphics& g, const AffineTransform& transform) const;
  37212. /** Converts the set of glyphs into a path.
  37213. @param path the glyphs' outlines will be appended to this path
  37214. */
  37215. void createPath (Path& path) const;
  37216. /** Looks for a glyph that contains the given co-ordinate.
  37217. @returns the index of the glyph, or -1 if none were found.
  37218. */
  37219. int findGlyphIndexAt (float x, float y) const;
  37220. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  37221. @param startIndex the first glyph to test
  37222. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  37223. startIndex will be included
  37224. @param includeWhitespace if true, the extent of any whitespace characters will also
  37225. be taken into account
  37226. */
  37227. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  37228. /** Shifts a set of glyphs by a given amount.
  37229. @param startIndex the first glyph to transform
  37230. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  37231. startIndex will be used
  37232. @param deltaX the amount to add to their x-positions
  37233. @param deltaY the amount to add to their y-positions
  37234. */
  37235. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  37236. float deltaX, float deltaY);
  37237. /** Removes a set of glyphs from the arrangement.
  37238. @param startIndex the first glyph to remove
  37239. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  37240. startIndex will be deleted
  37241. */
  37242. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  37243. /** Expands or compresses a set of glyphs horizontally.
  37244. @param startIndex the first glyph to transform
  37245. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  37246. startIndex will be used
  37247. @param horizontalScaleFactor how much to scale their horizontal width by
  37248. */
  37249. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  37250. float horizontalScaleFactor);
  37251. /** Justifies a set of glyphs within a given space.
  37252. This moves the glyphs as a block so that the whole thing is located within the
  37253. given rectangle with the specified layout.
  37254. If the Justification::horizontallyJustified flag is specified, each line will
  37255. be stretched out to fill the specified width.
  37256. */
  37257. void justifyGlyphs (int startIndex, int numGlyphs,
  37258. float x, float y, float width, float height,
  37259. const Justification& justification);
  37260. juce_UseDebuggingNewOperator
  37261. private:
  37262. OwnedArray <PositionedGlyph> glyphs;
  37263. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  37264. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  37265. const Justification& justification, float minimumHorizontalScale);
  37266. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  37267. };
  37268. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37269. /*** End of inlined file: juce_GlyphArrangement.h ***/
  37270. /**
  37271. A file open/save dialog box.
  37272. This is a Juce-based file dialog box; to use a native file chooser, see the
  37273. FileChooser class.
  37274. To use one of these, create it and call its show() method. e.g.
  37275. @code
  37276. {
  37277. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  37278. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37279. File::nonexistent,
  37280. &wildcardFilter,
  37281. 0);
  37282. FileChooserDialogBox dialogBox ("Open some kind of file",
  37283. "Please choose some kind of file that you want to open...",
  37284. browser,
  37285. getLookAndFeel().alertWindowBackground);
  37286. if (dialogBox.show())
  37287. {
  37288. File selectedFile = browser.getCurrentFile();
  37289. ...
  37290. }
  37291. }
  37292. @endcode
  37293. @see FileChooser
  37294. */
  37295. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37296. public ButtonListener,
  37297. public FileBrowserListener
  37298. {
  37299. public:
  37300. /** Creates a file chooser box.
  37301. @param title the main title to show at the top of the box
  37302. @param instructions an optional longer piece of text to show below the title in
  37303. a smaller font, describing in more detail what's required.
  37304. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37305. box. Make sure you delete this after (but not before!) the
  37306. dialog box has been deleted.
  37307. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37308. if they try to select a file that already exists. (This
  37309. flag is only used when saving files)
  37310. @param backgroundColour the background colour for the top level window
  37311. @see FileBrowserComponent, FilePreviewComponent
  37312. */
  37313. FileChooserDialogBox (const String& title,
  37314. const String& instructions,
  37315. FileBrowserComponent& browserComponent,
  37316. bool warnAboutOverwritingExistingFiles,
  37317. const Colour& backgroundColour);
  37318. /** Destructor. */
  37319. ~FileChooserDialogBox();
  37320. /** Displays and runs the dialog box modally.
  37321. This will show the box with the specified size, returning true if the user
  37322. pressed 'ok', or false if they cancelled.
  37323. Leave the width or height as 0 to use the default size
  37324. */
  37325. bool show (int width = 0,int height = 0);
  37326. /** A set of colour IDs to use to change the colour of various aspects of the box.
  37327. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37328. methods.
  37329. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37330. */
  37331. enum ColourIds
  37332. {
  37333. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  37334. };
  37335. /** @internal */
  37336. void buttonClicked (Button* button);
  37337. /** @internal */
  37338. void closeButtonPressed();
  37339. /** @internal */
  37340. void selectionChanged();
  37341. /** @internal */
  37342. void fileClicked (const File& file, const MouseEvent& e);
  37343. /** @internal */
  37344. void fileDoubleClicked (const File& file);
  37345. juce_UseDebuggingNewOperator
  37346. private:
  37347. class ContentComponent : public Component
  37348. {
  37349. public:
  37350. ContentComponent();
  37351. ~ContentComponent();
  37352. void paint (Graphics& g);
  37353. void resized();
  37354. String instructions;
  37355. GlyphArrangement text;
  37356. FileBrowserComponent* chooserComponent;
  37357. FilePreviewComponent* previewComponent;
  37358. TextButton* okButton;
  37359. TextButton* cancelButton;
  37360. };
  37361. ContentComponent* content;
  37362. const bool warnAboutOverwritingExistingFiles;
  37363. FileChooserDialogBox (const FileChooserDialogBox&);
  37364. FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37365. };
  37366. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37367. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  37368. #endif
  37369. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37370. #endif
  37371. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37372. /*** Start of inlined file: juce_FileListComponent.h ***/
  37373. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37374. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37375. /**
  37376. A component that displays the files in a directory as a listbox.
  37377. This implements the DirectoryContentsDisplayComponent base class so that
  37378. it can be used in a FileBrowserComponent.
  37379. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37380. class and the FileBrowserListener class.
  37381. @see DirectoryContentsList, FileTreeComponent
  37382. */
  37383. class JUCE_API FileListComponent : public ListBox,
  37384. public DirectoryContentsDisplayComponent,
  37385. private ListBoxModel,
  37386. private ChangeListener
  37387. {
  37388. public:
  37389. /** Creates a listbox to show the contents of a specified directory.
  37390. */
  37391. FileListComponent (DirectoryContentsList& listToShow);
  37392. /** Destructor. */
  37393. ~FileListComponent();
  37394. /** Returns the number of files the user has got selected.
  37395. @see getSelectedFile
  37396. */
  37397. int getNumSelectedFiles() const;
  37398. /** Returns one of the files that the user has currently selected.
  37399. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  37400. @see getNumSelectedFiles
  37401. */
  37402. const File getSelectedFile (int index = 0) const;
  37403. /** Deselects any files that are currently selected. */
  37404. void deselectAllFiles();
  37405. /** Scrolls to the top of the list. */
  37406. void scrollToTop();
  37407. /** @internal */
  37408. void changeListenerCallback (void*);
  37409. /** @internal */
  37410. int getNumRows();
  37411. /** @internal */
  37412. void paintListBoxItem (int, Graphics&, int, int, bool);
  37413. /** @internal */
  37414. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  37415. /** @internal */
  37416. void selectedRowsChanged (int lastRowSelected);
  37417. /** @internal */
  37418. void deleteKeyPressed (int currentSelectedRow);
  37419. /** @internal */
  37420. void returnKeyPressed (int currentSelectedRow);
  37421. juce_UseDebuggingNewOperator
  37422. private:
  37423. FileListComponent (const FileListComponent&);
  37424. FileListComponent& operator= (const FileListComponent&);
  37425. File lastDirectory;
  37426. };
  37427. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37428. /*** End of inlined file: juce_FileListComponent.h ***/
  37429. #endif
  37430. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37431. /*** Start of inlined file: juce_FilenameComponent.h ***/
  37432. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37433. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37434. class FilenameComponent;
  37435. /**
  37436. Listens for events happening to a FilenameComponent.
  37437. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  37438. register one of these objects for event callbacks when the filename is changed.
  37439. @see FilenameComponent
  37440. */
  37441. class JUCE_API FilenameComponentListener
  37442. {
  37443. public:
  37444. /** Destructor. */
  37445. virtual ~FilenameComponentListener() {}
  37446. /** This method is called after the FilenameComponent's file has been changed. */
  37447. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  37448. };
  37449. /**
  37450. Shows a filename as an editable text box, with a 'browse' button and a
  37451. drop-down list for recently selected files.
  37452. A handy component for dialogue boxes where you want the user to be able to
  37453. select a file or directory.
  37454. Attach an FilenameComponentListener using the addListener() method, and it will
  37455. get called each time the user changes the filename, either by browsing for a file
  37456. and clicking 'ok', or by typing a new filename into the box and pressing return.
  37457. @see FileChooser, ComboBox
  37458. */
  37459. class JUCE_API FilenameComponent : public Component,
  37460. public SettableTooltipClient,
  37461. public FileDragAndDropTarget,
  37462. private AsyncUpdater,
  37463. private ButtonListener,
  37464. private ComboBoxListener
  37465. {
  37466. public:
  37467. /** Creates a FilenameComponent.
  37468. @param name the name for this component.
  37469. @param currentFile the file to initially show in the box
  37470. @param canEditFilename if true, the user can manually edit the filename; if false,
  37471. they can only change it by browsing for a new file
  37472. @param isDirectory if true, the file will be treated as a directory, and
  37473. an appropriate directory browser used
  37474. @param isForSaving if true, the file browser will allow non-existent files to
  37475. be picked, as the file is assumed to be used for saving rather
  37476. than loading
  37477. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  37478. If an empty string is passed in, then the pattern is assumed to be "*"
  37479. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  37480. to any filenames that are entered or chosen
  37481. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  37482. will only appear if the initial file isn't valid)
  37483. */
  37484. FilenameComponent (const String& name,
  37485. const File& currentFile,
  37486. bool canEditFilename,
  37487. bool isDirectory,
  37488. bool isForSaving,
  37489. const String& fileBrowserWildcard,
  37490. const String& enforcedSuffix,
  37491. const String& textWhenNothingSelected);
  37492. /** Destructor. */
  37493. ~FilenameComponent();
  37494. /** Returns the currently displayed filename. */
  37495. const File getCurrentFile() const;
  37496. /** Changes the current filename.
  37497. If addToRecentlyUsedList is true, the filename will also be added to the
  37498. drop-down list of recent files.
  37499. If sendChangeNotification is false, then the listeners won't be told of the
  37500. change.
  37501. */
  37502. void setCurrentFile (File newFile,
  37503. bool addToRecentlyUsedList,
  37504. bool sendChangeNotification = true);
  37505. /** Changes whether the use can type into the filename box.
  37506. */
  37507. void setFilenameIsEditable (bool shouldBeEditable);
  37508. /** Sets a file or directory to be the default starting point for the browser to show.
  37509. This is only used if the current file hasn't been set.
  37510. */
  37511. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  37512. /** Returns all the entries on the recent files list.
  37513. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  37514. state of this list.
  37515. @see setRecentlyUsedFilenames
  37516. */
  37517. const StringArray getRecentlyUsedFilenames() const;
  37518. /** Sets all the entries on the recent files list.
  37519. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  37520. state of this list.
  37521. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  37522. */
  37523. void setRecentlyUsedFilenames (const StringArray& filenames);
  37524. /** Adds an entry to the recently-used files dropdown list.
  37525. If the file is already in the list, it will be moved to the top. A limit
  37526. is also placed on the number of items that are kept in the list.
  37527. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  37528. */
  37529. void addRecentlyUsedFile (const File& file);
  37530. /** Changes the limit for the number of files that will be stored in the recent-file list.
  37531. */
  37532. void setMaxNumberOfRecentFiles (int newMaximum);
  37533. /** Changes the text shown on the 'browse' button.
  37534. By default this button just says "..." but you can change it. The button itself
  37535. can be changed using the look-and-feel classes, so it might not actually have any
  37536. text on it.
  37537. */
  37538. void setBrowseButtonText (const String& browseButtonText);
  37539. /** Adds a listener that will be called when the selected file is changed. */
  37540. void addListener (FilenameComponentListener* listener);
  37541. /** Removes a previously-registered listener. */
  37542. void removeListener (FilenameComponentListener* listener);
  37543. /** Gives the component a tooltip. */
  37544. void setTooltip (const String& newTooltip);
  37545. /** @internal */
  37546. void paintOverChildren (Graphics& g);
  37547. /** @internal */
  37548. void resized();
  37549. /** @internal */
  37550. void lookAndFeelChanged();
  37551. /** @internal */
  37552. bool isInterestedInFileDrag (const StringArray& files);
  37553. /** @internal */
  37554. void filesDropped (const StringArray& files, int, int);
  37555. /** @internal */
  37556. void fileDragEnter (const StringArray& files, int, int);
  37557. /** @internal */
  37558. void fileDragExit (const StringArray& files);
  37559. juce_UseDebuggingNewOperator
  37560. private:
  37561. ComboBox* filenameBox;
  37562. String lastFilename;
  37563. Button* browseButton;
  37564. int maxRecentFiles;
  37565. bool isDir, isSaving, isFileDragOver;
  37566. String wildcard, enforcedSuffix, browseButtonText;
  37567. ListenerList <FilenameComponentListener> listeners;
  37568. File defaultBrowseFile;
  37569. void comboBoxChanged (ComboBox*);
  37570. void buttonClicked (Button* button);
  37571. void handleAsyncUpdate();
  37572. FilenameComponent (const FilenameComponent&);
  37573. FilenameComponent& operator= (const FilenameComponent&);
  37574. };
  37575. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  37576. /*** End of inlined file: juce_FilenameComponent.h ***/
  37577. #endif
  37578. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  37579. #endif
  37580. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37581. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  37582. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37583. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37584. /**
  37585. Shows a set of file paths in a list, allowing them to be added, removed or
  37586. re-ordered.
  37587. @see FileSearchPath
  37588. */
  37589. class JUCE_API FileSearchPathListComponent : public Component,
  37590. public SettableTooltipClient,
  37591. public FileDragAndDropTarget,
  37592. private ButtonListener,
  37593. private ListBoxModel
  37594. {
  37595. public:
  37596. /** Creates an empty FileSearchPathListComponent.
  37597. */
  37598. FileSearchPathListComponent();
  37599. /** Destructor. */
  37600. ~FileSearchPathListComponent();
  37601. /** Returns the path as it is currently shown. */
  37602. const FileSearchPath& getPath() const throw() { return path; }
  37603. /** Changes the current path. */
  37604. void setPath (const FileSearchPath& newPath);
  37605. /** Sets a file or directory to be the default starting point for the browser to show.
  37606. This is only used if the current file hasn't been set.
  37607. */
  37608. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  37609. /** A set of colour IDs to use to change the colour of various aspects of the label.
  37610. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37611. methods.
  37612. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37613. */
  37614. enum ColourIds
  37615. {
  37616. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  37617. Make this transparent if you don't want the background to be filled. */
  37618. };
  37619. /** @internal */
  37620. int getNumRows();
  37621. /** @internal */
  37622. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  37623. /** @internal */
  37624. void deleteKeyPressed (int lastRowSelected);
  37625. /** @internal */
  37626. void returnKeyPressed (int lastRowSelected);
  37627. /** @internal */
  37628. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  37629. /** @internal */
  37630. void selectedRowsChanged (int lastRowSelected);
  37631. /** @internal */
  37632. void resized();
  37633. /** @internal */
  37634. void paint (Graphics& g);
  37635. /** @internal */
  37636. bool isInterestedInFileDrag (const StringArray& files);
  37637. /** @internal */
  37638. void filesDropped (const StringArray& files, int, int);
  37639. /** @internal */
  37640. void buttonClicked (Button* button);
  37641. juce_UseDebuggingNewOperator
  37642. private:
  37643. FileSearchPath path;
  37644. File defaultBrowseTarget;
  37645. ListBox* listBox;
  37646. Button* addButton;
  37647. Button* removeButton;
  37648. TextButton* changeButton;
  37649. DrawableButton* upButton;
  37650. DrawableButton* downButton;
  37651. void changed();
  37652. void updateButtons();
  37653. FileSearchPathListComponent (const FileSearchPathListComponent&);
  37654. FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  37655. };
  37656. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  37657. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  37658. #endif
  37659. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37660. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  37661. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37662. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37663. /**
  37664. A component that displays the files in a directory as a treeview.
  37665. This implements the DirectoryContentsDisplayComponent base class so that
  37666. it can be used in a FileBrowserComponent.
  37667. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37668. class and the FileBrowserListener class.
  37669. @see DirectoryContentsList, FileListComponent
  37670. */
  37671. class JUCE_API FileTreeComponent : public TreeView,
  37672. public DirectoryContentsDisplayComponent
  37673. {
  37674. public:
  37675. /** Creates a listbox to show the contents of a specified directory.
  37676. */
  37677. FileTreeComponent (DirectoryContentsList& listToShow);
  37678. /** Destructor. */
  37679. ~FileTreeComponent();
  37680. /** Returns the number of files the user has got selected.
  37681. @see getSelectedFile
  37682. */
  37683. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  37684. /** Returns one of the files that the user has currently selected.
  37685. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  37686. @see getNumSelectedFiles
  37687. */
  37688. const File getSelectedFile (int index = 0) const;
  37689. /** Deselects any files that are currently selected. */
  37690. void deselectAllFiles();
  37691. /** Scrolls the list to the top. */
  37692. void scrollToTop();
  37693. /** Setting a name for this allows tree items to be dragged.
  37694. The string that you pass in here will be returned by the getDragSourceDescription()
  37695. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  37696. */
  37697. void setDragAndDropDescription (const String& description);
  37698. /** Returns the last value that was set by setDragAndDropDescription().
  37699. */
  37700. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  37701. juce_UseDebuggingNewOperator
  37702. private:
  37703. String dragAndDropDescription;
  37704. FileTreeComponent (const FileTreeComponent&);
  37705. FileTreeComponent& operator= (const FileTreeComponent&);
  37706. };
  37707. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  37708. /*** End of inlined file: juce_FileTreeComponent.h ***/
  37709. #endif
  37710. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37711. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  37712. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37713. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37714. /**
  37715. A simple preview component that shows thumbnails of image files.
  37716. @see FileChooserDialogBox, FilePreviewComponent
  37717. */
  37718. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  37719. private Timer
  37720. {
  37721. public:
  37722. /** Creates an ImagePreviewComponent. */
  37723. ImagePreviewComponent();
  37724. /** Destructor. */
  37725. ~ImagePreviewComponent();
  37726. /** @internal */
  37727. void selectedFileChanged (const File& newSelectedFile);
  37728. /** @internal */
  37729. void paint (Graphics& g);
  37730. /** @internal */
  37731. void timerCallback();
  37732. juce_UseDebuggingNewOperator
  37733. private:
  37734. File fileToLoad;
  37735. ScopedPointer <Image> currentThumbnail;
  37736. String currentDetails;
  37737. void getThumbSize (int& w, int& h) const;
  37738. ImagePreviewComponent (const ImagePreviewComponent&);
  37739. ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  37740. };
  37741. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  37742. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  37743. #endif
  37744. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37745. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  37746. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37747. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37748. /**
  37749. A type of FileFilter that works by wildcard pattern matching.
  37750. This filter only allows files that match one of the specified patterns, but
  37751. allows all directories through.
  37752. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  37753. */
  37754. class JUCE_API WildcardFileFilter : public FileFilter
  37755. {
  37756. public:
  37757. /**
  37758. Creates a wildcard filter for one or more patterns.
  37759. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  37760. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  37761. or .aiff.
  37762. The description is a name to show the user in a list of possible patterns, so
  37763. for the wav/aiff example, your description might be "audio files".
  37764. */
  37765. WildcardFileFilter (const String& fileWildcardPatterns,
  37766. const String& directoryWildcardPatterns,
  37767. const String& description);
  37768. /** Destructor. */
  37769. ~WildcardFileFilter();
  37770. /** Returns true if the filename matches one of the patterns specified. */
  37771. bool isFileSuitable (const File& file) const;
  37772. /** This always returns true. */
  37773. bool isDirectorySuitable (const File& file) const;
  37774. juce_UseDebuggingNewOperator
  37775. private:
  37776. StringArray fileWildcards, directoryWildcards;
  37777. static void parse (const String& pattern, StringArray& result);
  37778. static bool match (const File& file, const StringArray& wildcards);
  37779. };
  37780. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  37781. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  37782. #endif
  37783. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  37784. #endif
  37785. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  37786. #endif
  37787. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  37788. #endif
  37789. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  37790. #endif
  37791. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  37792. #endif
  37793. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  37794. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  37795. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  37796. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  37797. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  37798. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  37799. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  37800. /**
  37801. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  37802. command in a ApplicationCommandManager.
  37803. Normally, you won't actually create a KeyPressMappingSet directly, because
  37804. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  37805. you'd create yourself an ApplicationCommandManager, and call its
  37806. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  37807. KeyPressMappingSet.
  37808. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  37809. to the top-level component for which you want to handle keystrokes. So for example:
  37810. @code
  37811. class MyMainWindow : public Component
  37812. {
  37813. ApplicationCommandManager* myCommandManager;
  37814. public:
  37815. MyMainWindow()
  37816. {
  37817. myCommandManager = new ApplicationCommandManager();
  37818. // first, make sure the command manager has registered all the commands that its
  37819. // targets can perform..
  37820. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  37821. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  37822. // this will use the command manager to initialise the KeyPressMappingSet with
  37823. // the default keypresses that were specified when the targets added their commands
  37824. // to the manager.
  37825. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  37826. // having set up the default key-mappings, you might now want to load the last set
  37827. // of mappings that the user configured.
  37828. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  37829. // Now tell our top-level window to send any keypresses that arrive to the
  37830. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  37831. addKeyListener (myCommandManager->getKeyMappings());
  37832. }
  37833. ...
  37834. }
  37835. @endcode
  37836. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  37837. register to be told when a command or mapping is added, removed, etc.
  37838. There's also a UI component called KeyMappingEditorComponent that can be used
  37839. to easily edit the key mappings.
  37840. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  37841. */
  37842. class JUCE_API KeyPressMappingSet : public KeyListener,
  37843. public ChangeBroadcaster,
  37844. public FocusChangeListener
  37845. {
  37846. public:
  37847. /** Creates a KeyPressMappingSet for a given command manager.
  37848. Normally, you won't actually create a KeyPressMappingSet directly, because
  37849. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  37850. best thing to do is to create your ApplicationCommandManager, and use the
  37851. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  37852. When a suitable keypress happens, the manager's invoke() method will be
  37853. used to invoke the appropriate command.
  37854. @see ApplicationCommandManager
  37855. */
  37856. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  37857. /** Creates an copy of a KeyPressMappingSet. */
  37858. KeyPressMappingSet (const KeyPressMappingSet& other);
  37859. /** Destructor. */
  37860. ~KeyPressMappingSet();
  37861. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  37862. /** Returns a list of keypresses that are assigned to a particular command.
  37863. @param commandID the command's ID
  37864. */
  37865. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  37866. /** Assigns a keypress to a command.
  37867. If the keypress is already assigned to a different command, it will first be
  37868. removed from that command, to avoid it triggering multiple functions.
  37869. @param commandID the ID of the command that you want to add a keypress to. If
  37870. this is 0, the keypress will be removed from anything that it
  37871. was previously assigned to, but not re-assigned
  37872. @param newKeyPress the new key-press
  37873. @param insertIndex if this is less than zero, the key will be appended to the
  37874. end of the list of keypresses; otherwise the new keypress will
  37875. be inserted into the existing list at this index
  37876. */
  37877. void addKeyPress (CommandID commandID,
  37878. const KeyPress& newKeyPress,
  37879. int insertIndex = -1);
  37880. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  37881. @see resetToDefaultMapping
  37882. */
  37883. void resetToDefaultMappings();
  37884. /** Resets all key-mappings to the defaults for a particular command.
  37885. @see resetToDefaultMappings
  37886. */
  37887. void resetToDefaultMapping (CommandID commandID);
  37888. /** Removes all keypresses that are assigned to any commands. */
  37889. void clearAllKeyPresses();
  37890. /** Removes all keypresses that are assigned to a particular command. */
  37891. void clearAllKeyPresses (CommandID commandID);
  37892. /** Removes one of the keypresses that are assigned to a command.
  37893. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  37894. which the keyPressIndex refers.
  37895. */
  37896. void removeKeyPress (CommandID commandID, int keyPressIndex);
  37897. /** Removes a keypress from any command that it may be assigned to.
  37898. */
  37899. void removeKeyPress (const KeyPress& keypress);
  37900. /** Returns true if the given command is linked to this key. */
  37901. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  37902. /** Looks for a command that corresponds to a keypress.
  37903. @returns the UID of the command or 0 if none was found
  37904. */
  37905. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  37906. /** Tries to recreate the mappings from a previously stored state.
  37907. The XML passed in must have been created by the createXml() method.
  37908. If the stored state makes any reference to commands that aren't
  37909. currently available, these will be ignored.
  37910. If the set of mappings being loaded was a set of differences (using createXml (true)),
  37911. then this will call resetToDefaultMappings() and then merge the saved mappings
  37912. on top. If the saved set was created with createXml (false), then this method
  37913. will first clear all existing mappings and load the saved ones as a complete set.
  37914. @returns true if it manages to load the XML correctly
  37915. @see createXml
  37916. */
  37917. bool restoreFromXml (const XmlElement& xmlVersion);
  37918. /** Creates an XML representation of the current mappings.
  37919. This will produce a lump of XML that can be later reloaded using
  37920. restoreFromXml() to recreate the current mapping state.
  37921. The object that is returned must be deleted by the caller.
  37922. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  37923. will be saved into the XML. If it's true, then the XML will
  37924. only store the differences between the current mappings and
  37925. the default mappings you'd get from calling resetToDefaultMappings().
  37926. The advantage of saving a set of differences from the default is that
  37927. if you change the default mappings (in a new version of your app, for
  37928. example), then these will be merged into a user's saved preferences.
  37929. @see restoreFromXml
  37930. */
  37931. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  37932. /** @internal */
  37933. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  37934. /** @internal */
  37935. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  37936. /** @internal */
  37937. void globalFocusChanged (Component* focusedComponent);
  37938. juce_UseDebuggingNewOperator
  37939. private:
  37940. ApplicationCommandManager* commandManager;
  37941. struct CommandMapping
  37942. {
  37943. CommandID commandID;
  37944. Array <KeyPress> keypresses;
  37945. bool wantsKeyUpDownCallbacks;
  37946. };
  37947. OwnedArray <CommandMapping> mappings;
  37948. struct KeyPressTime
  37949. {
  37950. KeyPress key;
  37951. uint32 timeWhenPressed;
  37952. };
  37953. OwnedArray <KeyPressTime> keysDown;
  37954. void handleMessage (const Message& message);
  37955. void invokeCommand (const CommandID commandID,
  37956. const KeyPress& keyPress,
  37957. const bool isKeyDown,
  37958. const int millisecsSinceKeyPressed,
  37959. Component* const originatingComponent) const;
  37960. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  37961. };
  37962. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  37963. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  37964. /**
  37965. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  37966. object.
  37967. @see KeyPressMappingSet
  37968. */
  37969. class JUCE_API KeyMappingEditorComponent : public Component,
  37970. public TreeViewItem,
  37971. public ChangeListener,
  37972. private ButtonListener
  37973. {
  37974. public:
  37975. /** Creates a KeyMappingEditorComponent.
  37976. @param mappingSet this is the set of mappings to display and
  37977. edit. Make sure the mappings object is not
  37978. deleted before this component!
  37979. @param showResetToDefaultButton if true, then at the bottom of the
  37980. list, the component will include a 'reset to
  37981. defaults' button.
  37982. */
  37983. KeyMappingEditorComponent (KeyPressMappingSet* mappingSet,
  37984. bool showResetToDefaultButton);
  37985. /** Destructor. */
  37986. virtual ~KeyMappingEditorComponent();
  37987. /** Sets up the colours to use for parts of the component.
  37988. @param mainBackground colour to use for most of the background
  37989. @param textColour colour to use for the text
  37990. */
  37991. void setColours (const Colour& mainBackground,
  37992. const Colour& textColour);
  37993. /** Returns the KeyPressMappingSet that this component is acting upon.
  37994. */
  37995. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  37996. /** Can be overridden if some commands need to be excluded from the list.
  37997. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  37998. method to decide what to return, but you can override it to handle special cases.
  37999. */
  38000. virtual bool shouldCommandBeIncluded (CommandID commandID);
  38001. /** Can be overridden to indicate that some commands are shown as read-only.
  38002. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  38003. method to decide what to return, but you can override it to handle special cases.
  38004. */
  38005. virtual bool isCommandReadOnly (CommandID commandID);
  38006. /** This can be overridden to let you change the format of the string used
  38007. to describe a keypress.
  38008. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  38009. keys that are triggered by something else externally. If you override the
  38010. method, be sure to let the base class's method handle keys you're not
  38011. interested in.
  38012. */
  38013. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  38014. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38015. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38016. methods.
  38017. To change the colours of the menu that pops up
  38018. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38019. */
  38020. enum ColourIds
  38021. {
  38022. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  38023. textColourId = 0x100ad01, /**< The colour for the text. */
  38024. };
  38025. /** @internal */
  38026. void parentHierarchyChanged();
  38027. /** @internal */
  38028. void resized();
  38029. /** @internal */
  38030. void changeListenerCallback (void*);
  38031. /** @internal */
  38032. bool mightContainSubItems();
  38033. /** @internal */
  38034. const String getUniqueName() const;
  38035. /** @internal */
  38036. void buttonClicked (Button* button);
  38037. juce_UseDebuggingNewOperator
  38038. private:
  38039. KeyPressMappingSet* mappings;
  38040. TreeView* tree;
  38041. friend class KeyMappingTreeViewItem;
  38042. friend class KeyCategoryTreeViewItem;
  38043. friend class KeyMappingItemComponent;
  38044. friend class KeyMappingChangeButton;
  38045. TextButton* resetButton;
  38046. void assignNewKey (CommandID commandID, int index);
  38047. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  38048. KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  38049. };
  38050. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38051. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  38052. #endif
  38053. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  38054. #endif
  38055. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38056. #endif
  38057. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  38058. #endif
  38059. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38060. #endif
  38061. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  38062. #endif
  38063. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  38064. #endif
  38065. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38066. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  38067. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38068. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38069. /** An object that watches for any movement of a component or any of its parent components.
  38070. This makes it easy to check when a component is moved relative to its top-level
  38071. peer window. The normal Component::moved() method is only called when a component
  38072. moves relative to its immediate parent, and sometimes you want to know if any of
  38073. components higher up the tree have moved (which of course will affect the overall
  38074. position of all their sub-components).
  38075. It also includes a callback that lets you know when the top-level peer is changed.
  38076. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  38077. because they need to keep their custom windows in the right place and respond to
  38078. changes in the peer.
  38079. */
  38080. class JUCE_API ComponentMovementWatcher : public ComponentListener
  38081. {
  38082. public:
  38083. /** Creates a ComponentMovementWatcher to watch a given target component. */
  38084. ComponentMovementWatcher (Component* component);
  38085. /** Destructor. */
  38086. ~ComponentMovementWatcher();
  38087. /** This callback happens when the component that is being watched is moved
  38088. relative to its top-level peer window, or when it is resized.
  38089. */
  38090. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  38091. /** This callback happens when the component's top-level peer is changed.
  38092. */
  38093. virtual void componentPeerChanged() = 0;
  38094. juce_UseDebuggingNewOperator
  38095. /** @internal */
  38096. void componentParentHierarchyChanged (Component& component);
  38097. /** @internal */
  38098. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  38099. private:
  38100. Component::SafePointer<Component> component;
  38101. ComponentPeer* lastPeer;
  38102. Array <Component*> registeredParentComps;
  38103. bool reentrant;
  38104. Rectangle<int> lastBounds;
  38105. void unregister() throw();
  38106. void registerWithParentComps() throw();
  38107. ComponentMovementWatcher (const ComponentMovementWatcher&);
  38108. ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  38109. };
  38110. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38111. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  38112. #endif
  38113. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38114. /*** Start of inlined file: juce_GroupComponent.h ***/
  38115. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38116. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38117. /**
  38118. A component that draws an outline around itself and has an optional title at
  38119. the top, for drawing an outline around a group of controls.
  38120. */
  38121. class JUCE_API GroupComponent : public Component
  38122. {
  38123. public:
  38124. /** Creates a GroupComponent.
  38125. @param componentName the name to give the component
  38126. @param labelText the text to show at the top of the outline
  38127. */
  38128. GroupComponent (const String& componentName = String::empty,
  38129. const String& labelText = String::empty);
  38130. /** Destructor. */
  38131. ~GroupComponent();
  38132. /** Changes the text that's shown at the top of the component. */
  38133. void setText (const String& newText);
  38134. /** Returns the currently displayed text label. */
  38135. const String getText() const;
  38136. /** Sets the positioning of the text label.
  38137. (The default is Justification::left)
  38138. @see getTextLabelPosition
  38139. */
  38140. void setTextLabelPosition (const Justification& justification);
  38141. /** Returns the current text label position.
  38142. @see setTextLabelPosition
  38143. */
  38144. const Justification getTextLabelPosition() const throw() { return justification; }
  38145. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38146. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38147. methods.
  38148. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38149. */
  38150. enum ColourIds
  38151. {
  38152. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  38153. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  38154. };
  38155. /** @internal */
  38156. void paint (Graphics& g);
  38157. /** @internal */
  38158. void enablementChanged();
  38159. /** @internal */
  38160. void colourChanged();
  38161. private:
  38162. String text;
  38163. Justification justification;
  38164. GroupComponent (const GroupComponent&);
  38165. GroupComponent& operator= (const GroupComponent&);
  38166. };
  38167. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38168. /*** End of inlined file: juce_GroupComponent.h ***/
  38169. #endif
  38170. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38171. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  38172. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38173. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38174. /*** Start of inlined file: juce_TabbedComponent.h ***/
  38175. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38176. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38177. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  38178. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38179. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38180. class TabbedButtonBar;
  38181. /** In a TabbedButtonBar, this component is used for each of the buttons.
  38182. If you want to create a TabbedButtonBar with custom tab components, derive
  38183. your component from this class, and override the TabbedButtonBar::createTabButton()
  38184. method to create it instead of the default one.
  38185. @see TabbedButtonBar
  38186. */
  38187. class JUCE_API TabBarButton : public Button
  38188. {
  38189. public:
  38190. /** Creates the tab button. */
  38191. TabBarButton (const String& name,
  38192. TabbedButtonBar* ownerBar,
  38193. int tabIndex);
  38194. /** Destructor. */
  38195. ~TabBarButton();
  38196. /** Chooses the best length for the tab, given the specified depth.
  38197. If the tab is horizontal, this should return its width, and the depth
  38198. specifies its height. If it's vertical, it should return the height, and
  38199. the depth is actually its width.
  38200. */
  38201. virtual int getBestTabLength (int depth);
  38202. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  38203. void clicked (const ModifierKeys& mods);
  38204. bool hitTest (int x, int y);
  38205. juce_UseDebuggingNewOperator
  38206. protected:
  38207. friend class TabbedButtonBar;
  38208. TabbedButtonBar* const owner;
  38209. int tabIndex, overlapPixels;
  38210. DropShadowEffect shadow;
  38211. /** Returns an area of the component that's safe to draw in.
  38212. This deals with the orientation of the tabs, which affects which side is
  38213. touching the tabbed box's content component.
  38214. */
  38215. void getActiveArea (int& x, int& y, int& w, int& h);
  38216. private:
  38217. TabBarButton (const TabBarButton&);
  38218. TabBarButton& operator= (const TabBarButton&);
  38219. };
  38220. /**
  38221. A vertical or horizontal bar containing tabs that you can select.
  38222. You can use one of these to generate things like a dialog box that has
  38223. tabbed pages you can flip between. Attach a ChangeListener to the
  38224. button bar to be told when the user changes the page.
  38225. An easier method than doing this is to use a TabbedComponent, which
  38226. contains its own TabbedButtonBar and which takes care of the layout
  38227. and other housekeeping.
  38228. @see TabbedComponent
  38229. */
  38230. class JUCE_API TabbedButtonBar : public Component,
  38231. public ChangeBroadcaster,
  38232. public ButtonListener
  38233. {
  38234. public:
  38235. /** The placement of the tab-bar
  38236. @see setOrientation, getOrientation
  38237. */
  38238. enum Orientation
  38239. {
  38240. TabsAtTop,
  38241. TabsAtBottom,
  38242. TabsAtLeft,
  38243. TabsAtRight
  38244. };
  38245. /** Creates a TabbedButtonBar with a given placement.
  38246. You can change the orientation later if you need to.
  38247. */
  38248. TabbedButtonBar (Orientation orientation);
  38249. /** Destructor. */
  38250. ~TabbedButtonBar();
  38251. /** Changes the bar's orientation.
  38252. This won't change the bar's actual size - you'll need to do that yourself,
  38253. but this determines which direction the tabs go in, and which side they're
  38254. stuck to.
  38255. */
  38256. void setOrientation (Orientation orientation);
  38257. /** Returns the current orientation.
  38258. @see setOrientation
  38259. */
  38260. Orientation getOrientation() const throw() { return orientation; }
  38261. /** Deletes all the tabs from the bar.
  38262. @see addTab
  38263. */
  38264. void clearTabs();
  38265. /** Adds a tab to the bar.
  38266. Tabs are added in left-to-right reading order.
  38267. If this is the first tab added, it'll also be automatically selected.
  38268. */
  38269. void addTab (const String& tabName,
  38270. const Colour& tabBackgroundColour,
  38271. int insertIndex = -1);
  38272. /** Changes the name of one of the tabs. */
  38273. void setTabName (int tabIndex,
  38274. const String& newName);
  38275. /** Gets rid of one of the tabs. */
  38276. void removeTab (int tabIndex);
  38277. /** Moves a tab to a new index in the list.
  38278. Pass -1 as the index to move it to the end of the list.
  38279. */
  38280. void moveTab (int currentIndex, int newIndex);
  38281. /** Returns the number of tabs in the bar. */
  38282. int getNumTabs() const;
  38283. /** Returns a list of all the tab names in the bar. */
  38284. const StringArray getTabNames() const;
  38285. /** Changes the currently selected tab.
  38286. This will send a change message and cause a synchronous callback to
  38287. the currentTabChanged() method. (But if the given tab is already selected,
  38288. nothing will be done).
  38289. To deselect all the tabs, use an index of -1.
  38290. */
  38291. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38292. /** Returns the name of the currently selected tab.
  38293. This could be an empty string if none are selected.
  38294. */
  38295. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  38296. /** Returns the index of the currently selected tab.
  38297. This could return -1 if none are selected.
  38298. */
  38299. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  38300. /** Returns the button for a specific tab.
  38301. The button that is returned may be deleted later by this component, so don't hang
  38302. on to the pointer that is returned. A null pointer may be returned if the index is
  38303. out of range.
  38304. */
  38305. TabBarButton* getTabButton (int index) const;
  38306. /** Callback method to indicate the selected tab has been changed.
  38307. @see setCurrentTabIndex
  38308. */
  38309. virtual void currentTabChanged (int newCurrentTabIndex,
  38310. const String& newCurrentTabName);
  38311. /** Callback method to indicate that the user has right-clicked on a tab.
  38312. (Or ctrl-clicked on the Mac)
  38313. */
  38314. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  38315. /** Returns the colour of a tab.
  38316. This is the colour that was specified in addTab().
  38317. */
  38318. const Colour getTabBackgroundColour (int tabIndex);
  38319. /** Changes the background colour of a tab.
  38320. @see addTab, getTabBackgroundColour
  38321. */
  38322. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38323. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38324. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38325. methods.
  38326. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38327. */
  38328. enum ColourIds
  38329. {
  38330. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  38331. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  38332. the look and feel will choose an appropriate colour. */
  38333. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  38334. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  38335. this isn't specified, the look and feel will choose an appropriate
  38336. colour. */
  38337. };
  38338. /** @internal */
  38339. void resized();
  38340. /** @internal */
  38341. void buttonClicked (Button* button);
  38342. /** @internal */
  38343. void lookAndFeelChanged();
  38344. juce_UseDebuggingNewOperator
  38345. protected:
  38346. /** This creates one of the tabs.
  38347. If you need to use custom tab components, you can override this method and
  38348. return your own class instead of the default.
  38349. */
  38350. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  38351. private:
  38352. Orientation orientation;
  38353. StringArray tabs;
  38354. Array <Colour> tabColours;
  38355. int currentTabIndex;
  38356. Component* behindFrontTab;
  38357. Button* extraTabsButton;
  38358. TabbedButtonBar (const TabbedButtonBar&);
  38359. TabbedButtonBar& operator= (const TabbedButtonBar&);
  38360. };
  38361. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38362. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  38363. /**
  38364. A component with a TabbedButtonBar along one of its sides.
  38365. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  38366. with addTab(), and this will take care of showing the pages for you when the
  38367. user clicks on a different tab.
  38368. @see TabbedButtonBar
  38369. */
  38370. class JUCE_API TabbedComponent : public Component
  38371. {
  38372. public:
  38373. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  38374. Once created, add some tabs with the addTab() method.
  38375. */
  38376. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  38377. /** Destructor. */
  38378. ~TabbedComponent();
  38379. /** Changes the placement of the tabs.
  38380. This will rearrange the layout to place the tabs along the appropriate
  38381. side of this component, and will shift the content component accordingly.
  38382. @see TabbedButtonBar::setOrientation
  38383. */
  38384. void setOrientation (TabbedButtonBar::Orientation orientation);
  38385. /** Returns the current tab placement.
  38386. @see setOrientation, TabbedButtonBar::getOrientation
  38387. */
  38388. TabbedButtonBar::Orientation getOrientation() const throw();
  38389. /** Specifies how many pixels wide or high the tab-bar should be.
  38390. If the tabs are placed along the top or bottom, this specified the height
  38391. of the bar; if they're along the left or right edges, it'll be the width
  38392. of the bar.
  38393. */
  38394. void setTabBarDepth (int newDepth);
  38395. /** Returns the current thickness of the tab bar.
  38396. @see setTabBarDepth
  38397. */
  38398. int getTabBarDepth() const throw() { return tabDepth; }
  38399. /** Specifies the thickness of an outline that should be drawn around the content component.
  38400. If this thickness is > 0, a line will be drawn around the three sides of the content
  38401. component which don't touch the tab-bar, and the content component will be inset by this amount.
  38402. To set the colour of the line, use setColour (outlineColourId, ...).
  38403. */
  38404. void setOutline (int newThickness);
  38405. /** Specifies a gap to leave around the edge of the content component.
  38406. Each edge of the content component will be indented by the given number of pixels.
  38407. */
  38408. void setIndent (int indentThickness);
  38409. /** Removes all the tabs from the bar.
  38410. @see TabbedButtonBar::clearTabs
  38411. */
  38412. void clearTabs();
  38413. /** Adds a tab to the tab-bar.
  38414. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  38415. is true, it will be deleted when the tab is removed or when this object is
  38416. deleted.
  38417. @see TabbedButtonBar::addTab
  38418. */
  38419. void addTab (const String& tabName,
  38420. const Colour& tabBackgroundColour,
  38421. Component* contentComponent,
  38422. bool deleteComponentWhenNotNeeded,
  38423. int insertIndex = -1);
  38424. /** Changes the name of one of the tabs. */
  38425. void setTabName (int tabIndex, const String& newName);
  38426. /** Gets rid of one of the tabs. */
  38427. void removeTab (int tabIndex);
  38428. /** Returns the number of tabs in the bar. */
  38429. int getNumTabs() const;
  38430. /** Returns a list of all the tab names in the bar. */
  38431. const StringArray getTabNames() const;
  38432. /** Returns the content component that was added for the given index.
  38433. Be sure not to use or delete the components that are returned, as this may interfere
  38434. with the TabbedComponent's use of them.
  38435. */
  38436. Component* getTabContentComponent (int tabIndex) const throw();
  38437. /** Returns the colour of one of the tabs. */
  38438. const Colour getTabBackgroundColour (int tabIndex) const throw();
  38439. /** Changes the background colour of one of the tabs. */
  38440. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38441. /** Changes the currently-selected tab.
  38442. To deselect all the tabs, pass -1 as the index.
  38443. @see TabbedButtonBar::setCurrentTabIndex
  38444. */
  38445. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38446. /** Returns the index of the currently selected tab.
  38447. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  38448. */
  38449. int getCurrentTabIndex() const;
  38450. /** Returns the name of the currently selected tab.
  38451. @see addTab, TabbedButtonBar::getCurrentTabName()
  38452. */
  38453. const String& getCurrentTabName() const;
  38454. /** Returns the current component that's filling the panel.
  38455. This will return 0 if there isn't one.
  38456. */
  38457. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  38458. /** Callback method to indicate the selected tab has been changed.
  38459. @see setCurrentTabIndex
  38460. */
  38461. virtual void currentTabChanged (int newCurrentTabIndex,
  38462. const String& newCurrentTabName);
  38463. /** Callback method to indicate that the user has right-clicked on a tab.
  38464. (Or ctrl-clicked on the Mac)
  38465. */
  38466. virtual void popupMenuClickOnTab (int tabIndex,
  38467. const String& tabName);
  38468. /** Returns the tab button bar component that is being used.
  38469. */
  38470. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  38471. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38472. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38473. methods.
  38474. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38475. */
  38476. enum ColourIds
  38477. {
  38478. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  38479. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  38480. (See setOutline) */
  38481. };
  38482. /** @internal */
  38483. void paint (Graphics& g);
  38484. /** @internal */
  38485. void resized();
  38486. /** @internal */
  38487. void lookAndFeelChanged();
  38488. juce_UseDebuggingNewOperator
  38489. protected:
  38490. TabbedButtonBar* tabs;
  38491. /** This creates one of the tab buttons.
  38492. If you need to use custom tab components, you can override this method and
  38493. return your own class instead of the default.
  38494. */
  38495. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  38496. private:
  38497. Array <Component*> contentComponents;
  38498. Component* panelComponent;
  38499. int tabDepth;
  38500. int outlineThickness, edgeIndent;
  38501. static const Identifier deleteComponentId;
  38502. friend class TabCompButtonBar;
  38503. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  38504. TabbedComponent (const TabbedComponent&);
  38505. TabbedComponent& operator= (const TabbedComponent&);
  38506. };
  38507. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38508. /*** End of inlined file: juce_TabbedComponent.h ***/
  38509. /*** Start of inlined file: juce_DocumentWindow.h ***/
  38510. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38511. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38512. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  38513. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38514. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38515. /*** Start of inlined file: juce_MenuBarModel.h ***/
  38516. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  38517. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  38518. class MenuBarModel;
  38519. /**
  38520. A class to receive callbacks when a MenuBarModel changes.
  38521. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  38522. */
  38523. class JUCE_API MenuBarModelListener
  38524. {
  38525. public:
  38526. /** Destructor. */
  38527. virtual ~MenuBarModelListener() {}
  38528. /** This callback is made when items are changed in the menu bar model.
  38529. */
  38530. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  38531. /** This callback is made when an application command is invoked that
  38532. is represented by one of the items in the menu bar model.
  38533. */
  38534. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  38535. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  38536. };
  38537. /**
  38538. A class for controlling MenuBar components.
  38539. This class is used to tell a MenuBar what menus to show, and to respond
  38540. to a menu being selected.
  38541. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  38542. */
  38543. class JUCE_API MenuBarModel : private AsyncUpdater,
  38544. private ApplicationCommandManagerListener
  38545. {
  38546. public:
  38547. MenuBarModel() throw();
  38548. /** Destructor. */
  38549. virtual ~MenuBarModel();
  38550. /** Call this when some of your menu items have changed.
  38551. This method will cause a callback to any MenuBarListener objects that
  38552. are registered with this model.
  38553. If this model is displaying items from an ApplicationCommandManager, you
  38554. can use the setApplicationCommandManagerToWatch() method to cause
  38555. change messages to be sent automatically when the ApplicationCommandManager
  38556. is changed.
  38557. @see addListener, removeListener, MenuBarListener
  38558. */
  38559. void menuItemsChanged();
  38560. /** Tells the menu bar to listen to the specified command manager, and to update
  38561. itself when the commands change.
  38562. This will also allow it to flash a menu name when a command from that menu
  38563. is invoked using a keystroke.
  38564. */
  38565. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  38566. /** Registers a listener for callbacks when the menu items in this model change.
  38567. The listener object will get callbacks when this object's menuItemsChanged()
  38568. method is called.
  38569. @see removeListener
  38570. */
  38571. void addListener (MenuBarModelListener* listenerToAdd) throw();
  38572. /** Removes a listener.
  38573. @see addListener
  38574. */
  38575. void removeListener (MenuBarModelListener* listenerToRemove) throw();
  38576. /** This method must return a list of the names of the menus. */
  38577. virtual const StringArray getMenuBarNames() = 0;
  38578. /** This should return the popup menu to display for a given top-level menu.
  38579. @param topLevelMenuIndex the index of the top-level menu to show
  38580. @param menuName the name of the top-level menu item to show
  38581. */
  38582. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  38583. const String& menuName) = 0;
  38584. /** This is called when a menu item has been clicked on.
  38585. @param menuItemID the item ID of the PopupMenu item that was selected
  38586. @param topLevelMenuIndex the index of the top-level menu from which the item was
  38587. chosen (just in case you've used duplicate ID numbers
  38588. on more than one of the popup menus)
  38589. */
  38590. virtual void menuItemSelected (int menuItemID,
  38591. int topLevelMenuIndex) = 0;
  38592. #if JUCE_MAC || DOXYGEN
  38593. /** MAC ONLY - Sets the model that is currently being shown as the main
  38594. menu bar at the top of the screen on the Mac.
  38595. You can pass 0 to stop the current model being displayed. Be careful
  38596. not to delete a model while it is being used.
  38597. An optional extra menu can be specified, containing items to add to the top of
  38598. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  38599. an apple, it's the one next to it, with your application's name at the top
  38600. and the services menu etc on it). When one of these items is selected, the
  38601. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  38602. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  38603. object then newMenuBarModel must be non-null.
  38604. */
  38605. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  38606. const PopupMenu* extraAppleMenuItems = 0);
  38607. /** MAC ONLY - Returns the menu model that is currently being shown as
  38608. the main menu bar.
  38609. */
  38610. static MenuBarModel* getMacMainMenu();
  38611. #endif
  38612. /** @internal */
  38613. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  38614. /** @internal */
  38615. void applicationCommandListChanged();
  38616. /** @internal */
  38617. void handleAsyncUpdate();
  38618. juce_UseDebuggingNewOperator
  38619. private:
  38620. ApplicationCommandManager* manager;
  38621. ListenerList <MenuBarModelListener> listeners;
  38622. MenuBarModel (const MenuBarModel&);
  38623. MenuBarModel& operator= (const MenuBarModel&);
  38624. };
  38625. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  38626. /*** End of inlined file: juce_MenuBarModel.h ***/
  38627. /**
  38628. A menu bar component.
  38629. @see MenuBarModel
  38630. */
  38631. class JUCE_API MenuBarComponent : public Component,
  38632. private MenuBarModelListener,
  38633. private Timer
  38634. {
  38635. public:
  38636. /** Creates a menu bar.
  38637. @param model the model object to use to control this bar. You can
  38638. pass 0 into this if you like, and set the model later
  38639. using the setModel() method
  38640. */
  38641. MenuBarComponent (MenuBarModel* model);
  38642. /** Destructor. */
  38643. ~MenuBarComponent();
  38644. /** Changes the model object to use to control the bar.
  38645. This can be 0, in which case the bar will be empty. Don't delete the object
  38646. that is passed-in while it's still being used by this MenuBar.
  38647. */
  38648. void setModel (MenuBarModel* newModel);
  38649. /** Pops up one of the menu items.
  38650. This lets you manually open one of the menus - it could be triggered by a
  38651. key shortcut, for example.
  38652. */
  38653. void showMenu (int menuIndex);
  38654. /** @internal */
  38655. void paint (Graphics& g);
  38656. /** @internal */
  38657. void resized();
  38658. /** @internal */
  38659. void mouseEnter (const MouseEvent& e);
  38660. /** @internal */
  38661. void mouseExit (const MouseEvent& e);
  38662. /** @internal */
  38663. void mouseDown (const MouseEvent& e);
  38664. /** @internal */
  38665. void mouseDrag (const MouseEvent& e);
  38666. /** @internal */
  38667. void mouseUp (const MouseEvent& e);
  38668. /** @internal */
  38669. void mouseMove (const MouseEvent& e);
  38670. /** @internal */
  38671. void inputAttemptWhenModal();
  38672. /** @internal */
  38673. void handleCommandMessage (int commandId);
  38674. /** @internal */
  38675. bool keyPressed (const KeyPress& key);
  38676. /** @internal */
  38677. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  38678. /** @internal */
  38679. void menuCommandInvoked (MenuBarModel* menuBarModel,
  38680. const ApplicationCommandTarget::InvocationInfo& info);
  38681. juce_UseDebuggingNewOperator
  38682. private:
  38683. MenuBarModel* model;
  38684. StringArray menuNames;
  38685. Array <int> xPositions;
  38686. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked, indexToShowAgain;
  38687. int lastMouseX, lastMouseY;
  38688. bool inModalState;
  38689. ScopedPointer <Component> currentPopup;
  38690. int getItemAt (int x, int y);
  38691. void updateItemUnderMouse (int x, int y);
  38692. void hideCurrentMenu();
  38693. void timerCallback();
  38694. void repaintMenuItem (int index);
  38695. MenuBarComponent (const MenuBarComponent&);
  38696. MenuBarComponent& operator= (const MenuBarComponent&);
  38697. };
  38698. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  38699. /*** End of inlined file: juce_MenuBarComponent.h ***/
  38700. /**
  38701. A resizable window with a title bar and maximise, minimise and close buttons.
  38702. This subclass of ResizableWindow creates a fairly standard type of window with
  38703. a title bar and various buttons. The name of the component is shown in the
  38704. title bar, and an icon can optionally be specified with setIcon().
  38705. All the methods available to a ResizableWindow are also available to this,
  38706. so it can easily be made resizable, minimised, maximised, etc.
  38707. It's not advisable to add child components directly to a DocumentWindow: put them
  38708. inside your content component instead. And overriding methods like resized(), moved(), etc
  38709. is also not recommended - instead override these methods for your content component.
  38710. (If for some obscure reason you do need to override these methods, always remember to
  38711. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  38712. decorations correctly).
  38713. You can also automatically add a menu bar to the window, using the setMenuBar()
  38714. method.
  38715. @see ResizableWindow, DialogWindow
  38716. */
  38717. class JUCE_API DocumentWindow : public ResizableWindow
  38718. {
  38719. public:
  38720. /** The set of available button-types that can be put on the title bar.
  38721. @see setTitleBarButtonsRequired
  38722. */
  38723. enum TitleBarButtons
  38724. {
  38725. minimiseButton = 1,
  38726. maximiseButton = 2,
  38727. closeButton = 4,
  38728. /** A combination of all the buttons above. */
  38729. allButtons = 7
  38730. };
  38731. /** Creates a DocumentWindow.
  38732. @param name the name to give the component - this is also
  38733. the title shown at the top of the window. To change
  38734. this later, use setName()
  38735. @param backgroundColour the colour to use for filling the window's background.
  38736. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  38737. should be shown on the title bar. This value is a bitwise
  38738. combination of values from the TitleBarButtons enum. Note
  38739. that it can be "allButtons" to get them all. You
  38740. can change this later with the setTitleBarButtonsRequired()
  38741. method, which can also specify where they are positioned.
  38742. @param addToDesktop if true, the window will be automatically added to the
  38743. desktop; if false, you can use it as a child component
  38744. @see TitleBarButtons
  38745. */
  38746. DocumentWindow (const String& name,
  38747. const Colour& backgroundColour,
  38748. int requiredButtons,
  38749. bool addToDesktop = true);
  38750. /** Destructor.
  38751. If a content component has been set with setContentComponent(), it
  38752. will be deleted.
  38753. */
  38754. ~DocumentWindow();
  38755. /** Changes the component's name.
  38756. (This is overridden from Component::setName() to cause a repaint, as
  38757. the name is what gets drawn across the window's title bar).
  38758. */
  38759. void setName (const String& newName);
  38760. /** Sets an icon to show in the title bar, next to the title.
  38761. A copy is made internally of the image, so the caller can delete the
  38762. image after calling this. If 0 is passed-in, any existing icon will be
  38763. removed.
  38764. */
  38765. void setIcon (const Image* imageToUse);
  38766. /** Changes the height of the title-bar. */
  38767. void setTitleBarHeight (int newHeight);
  38768. /** Returns the current title bar height. */
  38769. int getTitleBarHeight() const;
  38770. /** Changes the set of title-bar buttons being shown.
  38771. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  38772. should be shown on the title bar. This value is a bitwise
  38773. combination of values from the TitleBarButtons enum. Note
  38774. that it can be "allButtons" to get them all.
  38775. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  38776. left side of the bar; if false, they'll be placed at the right
  38777. */
  38778. void setTitleBarButtonsRequired (int requiredButtons,
  38779. bool positionTitleBarButtonsOnLeft);
  38780. /** Sets whether the title should be centred within the window.
  38781. If true, the title text is shown in the middle of the title-bar; if false,
  38782. it'll be shown at the left of the bar.
  38783. */
  38784. void setTitleBarTextCentred (bool textShouldBeCentred);
  38785. /** Creates a menu inside this window.
  38786. @param menuBarModel this specifies a MenuBarModel that should be used to
  38787. generate the contents of a menu bar that will be placed
  38788. just below the title bar, and just above any content
  38789. component. If this value is zero, any existing menu bar
  38790. will be removed from the component; if non-zero, one will
  38791. be added if it's required.
  38792. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  38793. or less to use the look-and-feel's default size.
  38794. */
  38795. void setMenuBar (MenuBarModel* menuBarModel,
  38796. int menuBarHeight = 0);
  38797. /** This method is called when the user tries to close the window.
  38798. This is triggered by the user clicking the close button, or using some other
  38799. OS-specific key shortcut or OS menu for getting rid of a window.
  38800. If the window is just a pop-up, you should override this closeButtonPressed()
  38801. method and make it delete the window in whatever way is appropriate for your
  38802. app. E.g. you might just want to call "delete this".
  38803. If your app is centred around this window such that the whole app should quit when
  38804. the window is closed, then you will probably want to use this method as an opportunity
  38805. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  38806. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  38807. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  38808. or closing it via the taskbar icon on Windows).
  38809. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  38810. redirects it to call this method, so any methods of closing the window that are
  38811. caught by userTriedToCloseWindow() will also end up here).
  38812. */
  38813. virtual void closeButtonPressed();
  38814. /** Callback that is triggered when the minimise button is pressed.
  38815. The default implementation of this calls ResizableWindow::setMinimised(), but
  38816. you can override it to do more customised behaviour.
  38817. */
  38818. virtual void minimiseButtonPressed();
  38819. /** Callback that is triggered when the maximise button is pressed, or when the
  38820. title-bar is double-clicked.
  38821. The default implementation of this calls ResizableWindow::setFullScreen(), but
  38822. you can override it to do more customised behaviour.
  38823. */
  38824. virtual void maximiseButtonPressed();
  38825. /** Returns the close button, (or 0 if there isn't one). */
  38826. Button* getCloseButton() const throw();
  38827. /** Returns the minimise button, (or 0 if there isn't one). */
  38828. Button* getMinimiseButton() const throw();
  38829. /** Returns the maximise button, (or 0 if there isn't one). */
  38830. Button* getMaximiseButton() const throw();
  38831. /** A set of colour IDs to use to change the colour of various aspects of the window.
  38832. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38833. methods.
  38834. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38835. */
  38836. enum ColourIds
  38837. {
  38838. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  38839. and feel class how this is used. */
  38840. };
  38841. /** @internal */
  38842. void paint (Graphics& g);
  38843. /** @internal */
  38844. void resized();
  38845. /** @internal */
  38846. void lookAndFeelChanged();
  38847. /** @internal */
  38848. const BorderSize getBorderThickness();
  38849. /** @internal */
  38850. const BorderSize getContentComponentBorder();
  38851. /** @internal */
  38852. void mouseDoubleClick (const MouseEvent& e);
  38853. /** @internal */
  38854. void userTriedToCloseWindow();
  38855. /** @internal */
  38856. void activeWindowStatusChanged();
  38857. /** @internal */
  38858. int getDesktopWindowStyleFlags() const;
  38859. /** @internal */
  38860. void parentHierarchyChanged();
  38861. /** @internal */
  38862. const Rectangle<int> getTitleBarArea();
  38863. juce_UseDebuggingNewOperator
  38864. private:
  38865. int titleBarHeight, menuBarHeight, requiredButtons;
  38866. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  38867. ScopedPointer <Button> titleBarButtons [3];
  38868. ScopedPointer <Image> titleBarIcon;
  38869. ScopedPointer <MenuBarComponent> menuBar;
  38870. MenuBarModel* menuBarModel;
  38871. class ButtonListenerProxy;
  38872. friend class ScopedPointer <ButtonListenerProxy>;
  38873. ScopedPointer <ButtonListenerProxy> buttonListener;
  38874. void repaintTitleBar();
  38875. DocumentWindow (const DocumentWindow&);
  38876. DocumentWindow& operator= (const DocumentWindow&);
  38877. };
  38878. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  38879. /*** End of inlined file: juce_DocumentWindow.h ***/
  38880. class MultiDocumentPanel;
  38881. class MDITabbedComponentInternal;
  38882. /**
  38883. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  38884. component.
  38885. It's like a normal DocumentWindow but has some extra functionality to make sure
  38886. everything works nicely inside a MultiDocumentPanel.
  38887. @see MultiDocumentPanel
  38888. */
  38889. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  38890. {
  38891. public:
  38892. /**
  38893. */
  38894. MultiDocumentPanelWindow (const Colour& backgroundColour);
  38895. /** Destructor. */
  38896. ~MultiDocumentPanelWindow();
  38897. /** @internal */
  38898. void maximiseButtonPressed();
  38899. /** @internal */
  38900. void closeButtonPressed();
  38901. /** @internal */
  38902. void activeWindowStatusChanged();
  38903. /** @internal */
  38904. void broughtToFront();
  38905. juce_UseDebuggingNewOperator
  38906. private:
  38907. void updateOrder();
  38908. MultiDocumentPanel* getOwner() const throw();
  38909. };
  38910. /**
  38911. A component that contains a set of other components either in floating windows
  38912. or tabs.
  38913. This acts as a panel that can be used to hold a set of open document windows, with
  38914. different layout modes.
  38915. Use addDocument() and closeDocument() to add or remove components from the
  38916. panel - never use any of the Component methods to access the panel's child
  38917. components directly, as these are managed internally.
  38918. */
  38919. class JUCE_API MultiDocumentPanel : public Component,
  38920. private ComponentListener
  38921. {
  38922. public:
  38923. /** Creates an empty panel.
  38924. Use addDocument() and closeDocument() to add or remove components from the
  38925. panel - never use any of the Component methods to access the panel's child
  38926. components directly, as these are managed internally.
  38927. */
  38928. MultiDocumentPanel();
  38929. /** Destructor.
  38930. When deleted, this will call closeAllDocuments (false) to make sure all its
  38931. components are deleted. If you need to make sure all documents are saved
  38932. before closing, then you should call closeAllDocuments (true) and check that
  38933. it returns true before deleting the panel.
  38934. */
  38935. ~MultiDocumentPanel();
  38936. /** Tries to close all the documents.
  38937. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  38938. be called for each open document, and any of these calls fails, this method
  38939. will stop and return false, leaving some documents still open.
  38940. If checkItsOkToCloseFirst is false, then all documents will be closed
  38941. unconditionally.
  38942. @see closeDocument
  38943. */
  38944. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  38945. /** Adds a document component to the panel.
  38946. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  38947. this will fail and return false. (If it does fail, the component passed-in will not be
  38948. deleted, even if deleteWhenRemoved was set to true).
  38949. The MultiDocumentPanel will deal with creating a window border to go around your component,
  38950. so just pass in the bare content component here, no need to give it a ResizableWindow
  38951. or DocumentWindow.
  38952. @param component the component to add
  38953. @param backgroundColour the background colour to use to fill the component's
  38954. window or tab
  38955. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  38956. or closeAllDocuments(), then it will be deleted. If false, then
  38957. the caller must handle the component's deletion
  38958. */
  38959. bool addDocument (Component* component,
  38960. const Colour& backgroundColour,
  38961. bool deleteWhenRemoved);
  38962. /** Closes one of the documents.
  38963. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  38964. be called, and if it fails, this method will return false without closing the
  38965. document.
  38966. If checkItsOkToCloseFirst is false, then the documents will be closed
  38967. unconditionally.
  38968. The component will be deleted if the deleteWhenRemoved parameter was set to
  38969. true when it was added with addDocument.
  38970. @see addDocument, closeAllDocuments
  38971. */
  38972. bool closeDocument (Component* component,
  38973. bool checkItsOkToCloseFirst);
  38974. /** Returns the number of open document windows.
  38975. @see getDocument
  38976. */
  38977. int getNumDocuments() const throw();
  38978. /** Returns one of the open documents.
  38979. The order of the documents in this array may change when they are added, removed
  38980. or moved around.
  38981. @see getNumDocuments
  38982. */
  38983. Component* getDocument (int index) const throw();
  38984. /** Returns the document component that is currently focused or on top.
  38985. If currently using floating windows, then this will be the component in the currently
  38986. active window, or the top component if none are active.
  38987. If it's currently in tabbed mode, then it'll return the component in the active tab.
  38988. @see setActiveDocument
  38989. */
  38990. Component* getActiveDocument() const throw();
  38991. /** Makes one of the components active and brings it to the top.
  38992. @see getActiveDocument
  38993. */
  38994. void setActiveDocument (Component* component);
  38995. /** Callback which gets invoked when the currently-active document changes. */
  38996. virtual void activeDocumentChanged();
  38997. /** Sets a limit on how many windows can be open at once.
  38998. If this is zero or less there's no limit (the default). addDocument() will fail
  38999. if this number is exceeded.
  39000. */
  39001. void setMaximumNumDocuments (int maximumNumDocuments);
  39002. /** Sets an option to make the document fullscreen if there's only one document open.
  39003. If set to true, then if there's only one document, it'll fill the whole of this
  39004. component without tabs or a window border. If false, then tabs or a window
  39005. will always be shown, even if there's only one document. If there's more than
  39006. one document open, then this option makes no difference.
  39007. */
  39008. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  39009. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  39010. */
  39011. bool isFullscreenWhenOneDocument() const throw();
  39012. /** The different layout modes available. */
  39013. enum LayoutMode
  39014. {
  39015. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  39016. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  39017. };
  39018. /** Changes the panel's mode.
  39019. @see LayoutMode, getLayoutMode
  39020. */
  39021. void setLayoutMode (LayoutMode newLayoutMode);
  39022. /** Returns the current layout mode. */
  39023. LayoutMode getLayoutMode() const throw() { return mode; }
  39024. /** Sets the background colour for the whole panel.
  39025. Each document has its own background colour, but this is the one used to fill the areas
  39026. behind them.
  39027. */
  39028. void setBackgroundColour (const Colour& newBackgroundColour);
  39029. /** Returns the current background colour.
  39030. @see setBackgroundColour
  39031. */
  39032. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  39033. /** A subclass must override this to say whether its currently ok for a document
  39034. to be closed.
  39035. This method is called by closeDocument() and closeAllDocuments() to indicate that
  39036. a document should be saved if possible, ready for it to be closed.
  39037. If this method returns true, then it means the document is ok and can be closed.
  39038. If it returns false, then it means that the closeDocument() method should stop
  39039. and not close.
  39040. Normally, you'd use this method to ask the user if they want to save any changes,
  39041. then return true if the save operation went ok. If the user cancelled the save
  39042. operation you could return false here to abort the close operation.
  39043. If your component is based on the FileBasedDocument class, then you'd probably want
  39044. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  39045. FileBasedDocument::savedOk
  39046. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  39047. */
  39048. virtual bool tryToCloseDocument (Component* component) = 0;
  39049. /** Creates a new window to be used for a document.
  39050. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  39051. but you might want to override it to return a custom component.
  39052. */
  39053. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  39054. /** @internal */
  39055. void paint (Graphics& g);
  39056. /** @internal */
  39057. void resized();
  39058. /** @internal */
  39059. void componentNameChanged (Component&);
  39060. juce_UseDebuggingNewOperator
  39061. private:
  39062. LayoutMode mode;
  39063. Array <Component*> components;
  39064. TabbedComponent* tabComponent;
  39065. Colour backgroundColour;
  39066. int maximumNumDocuments, numDocsBeforeTabsUsed;
  39067. friend class MultiDocumentPanelWindow;
  39068. friend class MDITabbedComponentInternal;
  39069. Component* getContainerComp (Component* c) const;
  39070. void updateOrder();
  39071. void addWindow (Component* component);
  39072. };
  39073. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  39074. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  39075. #endif
  39076. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39077. #endif
  39078. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39079. #endif
  39080. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  39081. #endif
  39082. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39083. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  39084. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39085. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39086. /**
  39087. For laying out a set of components, where the components have preferred sizes
  39088. and size limits, but where they are allowed to stretch to fill the available
  39089. space.
  39090. For example, if you have a component containing several other components, and
  39091. each one should be given a share of the total size, you could use one of these
  39092. to resize the child components when the parent component is resized. Then
  39093. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  39094. A StretchableLayoutManager operates only in one dimension, so if you have a set
  39095. of components stacked vertically on top of each other, you'd use one to manage their
  39096. heights. To build up complex arrangements of components, e.g. for applications
  39097. with multiple nested panels, you would use more than one StretchableLayoutManager.
  39098. E.g. by using two (one vertical, one horizontal), you could create a resizable
  39099. spreadsheet-style table.
  39100. E.g.
  39101. @code
  39102. class MyComp : public Component
  39103. {
  39104. StretchableLayoutManager myLayout;
  39105. MyComp()
  39106. {
  39107. myLayout.setItemLayout (0, // for item 0
  39108. 50, 100, // must be between 50 and 100 pixels in size
  39109. -0.6); // and its preferred size is 60% of the total available space
  39110. myLayout.setItemLayout (1, // for item 1
  39111. -0.2, -0.6, // size must be between 20% and 60% of the available space
  39112. 50); // and its preferred size is 50 pixels
  39113. }
  39114. void resized()
  39115. {
  39116. // make a list of two of our child components that we want to reposition
  39117. Component* comps[] = { myComp1, myComp2 };
  39118. // this will position the 2 components, one above the other, to fit
  39119. // vertically into the rectangle provided.
  39120. myLayout.layOutComponents (comps, 2,
  39121. 0, 0, getWidth(), getHeight(),
  39122. true);
  39123. }
  39124. };
  39125. @endcode
  39126. @see StretchableLayoutResizerBar
  39127. */
  39128. class JUCE_API StretchableLayoutManager
  39129. {
  39130. public:
  39131. /** Creates an empty layout.
  39132. You'll need to add some item properties to the layout before it can be used
  39133. to resize things - see setItemLayout().
  39134. */
  39135. StretchableLayoutManager();
  39136. /** Destructor. */
  39137. ~StretchableLayoutManager();
  39138. /** For a numbered item, this sets its size limits and preferred size.
  39139. @param itemIndex the index of the item to change.
  39140. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39141. indicates an absolute size in pixels. A negative number indicates a
  39142. proportion of the available space (e.g -0.5 is 50%)
  39143. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39144. indicates an absolute size in pixels. A negative number indicates a
  39145. proportion of the available space
  39146. @param preferredSize the size that this item would like to be, if there's enough room. A
  39147. positive number indicates an absolute size in pixels. A negative number
  39148. indicates a proportion of the available space
  39149. @see getItemLayout
  39150. */
  39151. void setItemLayout (int itemIndex,
  39152. double minimumSize,
  39153. double maximumSize,
  39154. double preferredSize);
  39155. /** For a numbered item, this returns its size limits and preferred size.
  39156. @param itemIndex the index of the item.
  39157. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39158. indicates an absolute size in pixels. A negative number indicates a
  39159. proportion of the available space (e.g -0.5 is 50%)
  39160. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39161. indicates an absolute size in pixels. A negative number indicates a
  39162. proportion of the available space
  39163. @param preferredSize the size that this item would like to be, if there's enough room. A
  39164. positive number indicates an absolute size in pixels. A negative number
  39165. indicates a proportion of the available space
  39166. @returns false if the item's properties hadn't been set
  39167. @see setItemLayout
  39168. */
  39169. bool getItemLayout (int itemIndex,
  39170. double& minimumSize,
  39171. double& maximumSize,
  39172. double& preferredSize) const;
  39173. /** Clears all the properties that have been set with setItemLayout() and resets
  39174. this object to its initial state.
  39175. */
  39176. void clearAllItems();
  39177. /** Takes a set of components that correspond to the layout's items, and positions
  39178. them to fill a space.
  39179. This will try to give each item its preferred size, whether that's a relative size
  39180. or an absolute one.
  39181. @param components an array of components that correspond to each of the
  39182. numbered items that the StretchableLayoutManager object
  39183. has been told about with setItemLayout()
  39184. @param numComponents the number of components in the array that is passed-in. This
  39185. should be the same as the number of items this object has been
  39186. told about.
  39187. @param x the left of the rectangle in which the components should
  39188. be laid out
  39189. @param y the top of the rectangle in which the components should
  39190. be laid out
  39191. @param width the width of the rectangle in which the components should
  39192. be laid out
  39193. @param height the height of the rectangle in which the components should
  39194. be laid out
  39195. @param vertically if true, the components will be positioned in a vertical stack,
  39196. so that they fill the height of the rectangle. If false, they
  39197. will be placed side-by-side in a horizontal line, filling the
  39198. available width
  39199. @param resizeOtherDimension if true, this means that the components will have their
  39200. other dimension resized to fit the space - i.e. if the 'vertically'
  39201. parameter is true, their x-positions and widths are adjusted to fit
  39202. the x and width parameters; if 'vertically' is false, their y-positions
  39203. and heights are adjusted to fit the y and height parameters.
  39204. */
  39205. void layOutComponents (Component** components,
  39206. int numComponents,
  39207. int x, int y, int width, int height,
  39208. bool vertically,
  39209. bool resizeOtherDimension);
  39210. /** Returns the current position of one of the items.
  39211. This is only a valid call after layOutComponents() has been called, as it
  39212. returns the last position that this item was placed at. If the layout was
  39213. vertical, the value returned will be the y position of the top of the item,
  39214. relative to the top of the rectangle in which the items were placed (so for
  39215. example, item 0 will always have position of 0, even in the rectangle passed
  39216. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  39217. the position returned is the item's left-hand position, again relative to the
  39218. x position of the rectangle used.
  39219. @see getItemCurrentSize, setItemPosition
  39220. */
  39221. int getItemCurrentPosition (int itemIndex) const;
  39222. /** Returns the current size of one of the items.
  39223. This is only meaningful after layOutComponents() has been called, as it
  39224. returns the last size that this item was given. If the layout was done
  39225. vertically, it'll return the item's height in pixels; if it was horizontal,
  39226. it'll return its width.
  39227. @see getItemCurrentRelativeSize
  39228. */
  39229. int getItemCurrentAbsoluteSize (int itemIndex) const;
  39230. /** Returns the current size of one of the items.
  39231. This is only meaningful after layOutComponents() has been called, as it
  39232. returns the last size that this item was given. If the layout was done
  39233. vertically, it'll return a negative value representing the item's height relative
  39234. to the last size used for laying the components out; if the layout was done
  39235. horizontally it'll be the proportion of its width.
  39236. @see getItemCurrentAbsoluteSize
  39237. */
  39238. double getItemCurrentRelativeSize (int itemIndex) const;
  39239. /** Moves one of the items, shifting along any other items as necessary in
  39240. order to get it to the desired position.
  39241. Calling this method will also update the preferred sizes of the items it
  39242. shuffles along, so that they reflect their new positions.
  39243. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  39244. about when it's dragged).
  39245. @param itemIndex the item to move
  39246. @param newPosition the absolute position that you'd like this item to move
  39247. to. The item might not be able to always reach exactly this position,
  39248. because other items may have minimum sizes that constrain how
  39249. far it can go
  39250. */
  39251. void setItemPosition (int itemIndex,
  39252. int newPosition);
  39253. juce_UseDebuggingNewOperator
  39254. private:
  39255. struct ItemLayoutProperties
  39256. {
  39257. int itemIndex;
  39258. int currentSize;
  39259. double minSize, maxSize, preferredSize;
  39260. };
  39261. OwnedArray <ItemLayoutProperties> items;
  39262. int totalSize;
  39263. static int sizeToRealSize (double size, int totalSpace);
  39264. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  39265. void setTotalSize (int newTotalSize);
  39266. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  39267. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  39268. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  39269. void updatePrefSizesToMatchCurrentPositions();
  39270. StretchableLayoutManager (const StretchableLayoutManager&);
  39271. StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  39272. };
  39273. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39274. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  39275. #endif
  39276. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39277. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39278. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39279. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39280. /**
  39281. A component that acts as one of the vertical or horizontal bars you see being
  39282. used to resize panels in a window.
  39283. One of these acts with a StretchableLayoutManager to resize the other components.
  39284. @see StretchableLayoutManager
  39285. */
  39286. class JUCE_API StretchableLayoutResizerBar : public Component
  39287. {
  39288. public:
  39289. /** Creates a resizer bar for use on a specified layout.
  39290. @param layoutToUse the layout that will be affected when this bar
  39291. is dragged
  39292. @param itemIndexInLayout the item index in the layout that corresponds to
  39293. this bar component. You'll need to set up the item
  39294. properties in a suitable way for a divider bar, e.g.
  39295. for an 8-pixel wide bar which, you could call
  39296. myLayout->setItemLayout (barIndex, 8, 8, 8)
  39297. @param isBarVertical true if it's an upright bar that you drag left and
  39298. right; false for a horizontal one that you drag up and
  39299. down
  39300. */
  39301. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  39302. int itemIndexInLayout,
  39303. bool isBarVertical);
  39304. /** Destructor. */
  39305. ~StretchableLayoutResizerBar();
  39306. /** This is called when the bar is dragged.
  39307. This method must update the positions of any components whose position is
  39308. determined by the StretchableLayoutManager, because they might have just
  39309. moved.
  39310. The default implementation calls the resized() method of this component's
  39311. parent component, because that's often where you're likely to apply the
  39312. layout, but it can be overridden for more specific needs.
  39313. */
  39314. virtual void hasBeenMoved();
  39315. /** @internal */
  39316. void paint (Graphics& g);
  39317. /** @internal */
  39318. void mouseDown (const MouseEvent& e);
  39319. /** @internal */
  39320. void mouseDrag (const MouseEvent& e);
  39321. juce_UseDebuggingNewOperator
  39322. private:
  39323. StretchableLayoutManager* layout;
  39324. int itemIndex, mouseDownPos;
  39325. bool isVertical;
  39326. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  39327. StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  39328. };
  39329. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39330. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39331. #endif
  39332. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39333. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  39334. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39335. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39336. /**
  39337. A utility class for fitting a set of objects whose sizes can vary between
  39338. a minimum and maximum size, into a space.
  39339. This is a trickier algorithm than it would first seem, so I've put it in this
  39340. class to allow it to be shared by various bits of code.
  39341. To use it, create one of these objects, call addItem() to add the list of items
  39342. you need, then call resizeToFit(), which will change all their sizes. You can
  39343. then retrieve the new sizes with getItemSize() and getNumItems().
  39344. It's currently used by the TableHeaderComponent for stretching out the table
  39345. headings to fill the table's width.
  39346. */
  39347. class StretchableObjectResizer
  39348. {
  39349. public:
  39350. /** Creates an empty object resizer. */
  39351. StretchableObjectResizer();
  39352. /** Destructor. */
  39353. ~StretchableObjectResizer();
  39354. /** Adds an item to the list.
  39355. The order parameter lets you specify groups of items that are resized first when some
  39356. space needs to be found. Those items with an order of 0 will be the first ones to be
  39357. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  39358. will then try resizing the items with an order of 1, then 2, and so on.
  39359. */
  39360. void addItem (double currentSize,
  39361. double minSize,
  39362. double maxSize,
  39363. int order = 0);
  39364. /** Resizes all the items to fit this amount of space.
  39365. This will attempt to fit them in without exceeding each item's miniumum and
  39366. maximum sizes. In cases where none of the items can be expanded or enlarged any
  39367. further, the final size may be greater or less than the size passed in.
  39368. After calling this method, you can retrieve the new sizes with the getItemSize()
  39369. method.
  39370. */
  39371. void resizeToFit (double targetSize);
  39372. /** Returns the number of items that have been added. */
  39373. int getNumItems() const throw() { return items.size(); }
  39374. /** Returns the size of one of the items. */
  39375. double getItemSize (int index) const throw();
  39376. juce_UseDebuggingNewOperator
  39377. private:
  39378. struct Item
  39379. {
  39380. double size;
  39381. double minSize;
  39382. double maxSize;
  39383. int order;
  39384. };
  39385. OwnedArray <Item> items;
  39386. StretchableObjectResizer (const StretchableObjectResizer&);
  39387. StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  39388. };
  39389. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39390. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  39391. #endif
  39392. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  39393. #endif
  39394. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  39395. #endif
  39396. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  39397. #endif
  39398. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39399. /*** Start of inlined file: juce_LookAndFeel.h ***/
  39400. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39401. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  39402. /*** Start of inlined file: juce_AlertWindow.h ***/
  39403. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  39404. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  39405. /*** Start of inlined file: juce_TextLayout.h ***/
  39406. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  39407. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  39408. class Graphics;
  39409. /**
  39410. A laid-out arrangement of text.
  39411. You can add text in different fonts to a TextLayout object, then call its
  39412. layout() method to word-wrap it into lines. The layout can then be drawn
  39413. using a graphics context.
  39414. It's handy if you've got a message to display, because you can format it,
  39415. measure the extent of the layout, and then create a suitably-sized window
  39416. to show it in.
  39417. @see Font, Graphics::drawFittedText, GlyphArrangement
  39418. */
  39419. class JUCE_API TextLayout
  39420. {
  39421. public:
  39422. /** Creates an empty text layout.
  39423. Text can then be appended using the appendText() method.
  39424. */
  39425. TextLayout();
  39426. /** Creates a copy of another layout object. */
  39427. TextLayout (const TextLayout& other);
  39428. /** Creates a text layout from an initial string and font. */
  39429. TextLayout (const String& text, const Font& font);
  39430. /** Destructor. */
  39431. ~TextLayout();
  39432. /** Copies another layout onto this one. */
  39433. TextLayout& operator= (const TextLayout& layoutToCopy);
  39434. /** Clears the layout, removing all its text. */
  39435. void clear();
  39436. /** Adds a string to the end of the arrangement.
  39437. The string will be broken onto new lines wherever it contains
  39438. carriage-returns or linefeeds. After adding it, you can call layout()
  39439. to wrap long lines into a paragraph and justify it.
  39440. */
  39441. void appendText (const String& textToAppend,
  39442. const Font& fontToUse);
  39443. /** Replaces all the text with a new string.
  39444. This is equivalent to calling clear() followed by appendText().
  39445. */
  39446. void setText (const String& newText,
  39447. const Font& fontToUse);
  39448. /** Breaks the text up to form a paragraph with the given width.
  39449. @param maximumWidth any text wider than this will be split
  39450. across multiple lines
  39451. @param justification how the lines are to be laid-out horizontally
  39452. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  39453. width that keeps all the lines of text at a
  39454. similar length - this is good when you're displaying
  39455. a short message and don't want it to get split
  39456. onto two lines with only a couple of words on
  39457. the second line, which looks untidy.
  39458. */
  39459. void layout (int maximumWidth,
  39460. const Justification& justification,
  39461. bool attemptToBalanceLineLengths);
  39462. /** Returns the overall width of the entire text layout. */
  39463. int getWidth() const;
  39464. /** Returns the overall height of the entire text layout. */
  39465. int getHeight() const;
  39466. /** Returns the total number of lines of text. */
  39467. int getNumLines() const { return totalLines; }
  39468. /** Returns the width of a particular line of text.
  39469. @param lineNumber the line, from 0 to (getNumLines() - 1)
  39470. */
  39471. int getLineWidth (int lineNumber) const;
  39472. /** Renders the text at a specified position using a graphics context.
  39473. */
  39474. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  39475. /** Renders the text within a specified rectangle using a graphics context.
  39476. The justification flags dictate how the block of text should be positioned
  39477. within the rectangle.
  39478. */
  39479. void drawWithin (Graphics& g,
  39480. int x, int y, int w, int h,
  39481. const Justification& layoutFlags) const;
  39482. juce_UseDebuggingNewOperator
  39483. private:
  39484. class Token;
  39485. friend class OwnedArray <Token>;
  39486. OwnedArray <Token> tokens;
  39487. int totalLines;
  39488. };
  39489. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  39490. /*** End of inlined file: juce_TextLayout.h ***/
  39491. /** A window that displays a message and has buttons for the user to react to it.
  39492. For simple dialog boxes with just a couple of buttons on them, there are
  39493. some static methods for running these.
  39494. For more complex dialogs, an AlertWindow can be created, then it can have some
  39495. buttons and components added to it, and its runModalLoop() method is then used to
  39496. show it. The value returned by runModalLoop() shows which button the
  39497. user pressed to dismiss the box.
  39498. @see ThreadWithProgressWindow
  39499. */
  39500. class JUCE_API AlertWindow : public TopLevelWindow,
  39501. private ButtonListener
  39502. {
  39503. public:
  39504. /** The type of icon to show in the dialog box. */
  39505. enum AlertIconType
  39506. {
  39507. NoIcon, /**< No icon will be shown on the dialog box. */
  39508. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  39509. user to answer a question. */
  39510. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  39511. warning about something and shouldn't be ignored. */
  39512. InfoIcon /**< An icon that indicates that the dialog box is just
  39513. giving the user some information, which doesn't require
  39514. a response from them. */
  39515. };
  39516. /** Creates an AlertWindow.
  39517. @param title the headline to show at the top of the dialog box
  39518. @param message a longer, more descriptive message to show underneath the
  39519. headline
  39520. @param iconType the type of icon to display
  39521. @param associatedComponent if this is non-zero, it specifies the component that the
  39522. alert window should be associated with. Depending on the look
  39523. and feel, this might be used for positioning of the alert window.
  39524. */
  39525. AlertWindow (const String& title,
  39526. const String& message,
  39527. AlertIconType iconType,
  39528. Component* associatedComponent = 0);
  39529. /** Destroys the AlertWindow */
  39530. ~AlertWindow();
  39531. /** Returns the type of alert icon that was specified when the window
  39532. was created. */
  39533. AlertIconType getAlertType() const throw() { return alertIconType; }
  39534. /** Changes the dialog box's message.
  39535. This will also resize the window to fit the new message if required.
  39536. */
  39537. void setMessage (const String& message);
  39538. /** Adds a button to the window.
  39539. @param name the text to show on the button
  39540. @param returnValue the value that should be returned from runModalLoop()
  39541. if this is the button that the user presses.
  39542. @param shortcutKey1 an optional key that can be pressed to trigger this button
  39543. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  39544. */
  39545. void addButton (const String& name,
  39546. int returnValue,
  39547. const KeyPress& shortcutKey1 = KeyPress(),
  39548. const KeyPress& shortcutKey2 = KeyPress());
  39549. /** Returns the number of buttons that the window currently has. */
  39550. int getNumButtons() const;
  39551. /** Invokes a click of one of the buttons. */
  39552. void triggerButtonClick (const String& buttonName);
  39553. /** Adds a textbox to the window for entering strings.
  39554. @param name an internal name for the text-box. This is the name to pass to
  39555. the getTextEditorContents() method to find out what the
  39556. user typed-in.
  39557. @param initialContents a string to show in the text box when it's first shown
  39558. @param onScreenLabel if this is non-empty, it will be displayed next to the
  39559. text-box to label it.
  39560. @param isPasswordBox if true, the text editor will display asterisks instead of
  39561. the actual text
  39562. @see getTextEditorContents
  39563. */
  39564. void addTextEditor (const String& name,
  39565. const String& initialContents,
  39566. const String& onScreenLabel = String::empty,
  39567. bool isPasswordBox = false);
  39568. /** Returns the contents of a named textbox.
  39569. After showing an AlertWindow that contains a text editor, this can be
  39570. used to find out what the user has typed into it.
  39571. @param nameOfTextEditor the name of the text box that you're interested in
  39572. @see addTextEditor
  39573. */
  39574. const String getTextEditorContents (const String& nameOfTextEditor) const;
  39575. /** Adds a drop-down list of choices to the box.
  39576. After the box has been shown, the getComboBoxComponent() method can
  39577. be used to find out which item the user picked.
  39578. @param name the label to use for the drop-down list
  39579. @param items the list of items to show in it
  39580. @param onScreenLabel if this is non-empty, it will be displayed next to the
  39581. combo-box to label it.
  39582. @see getComboBoxComponent
  39583. */
  39584. void addComboBox (const String& name,
  39585. const StringArray& items,
  39586. const String& onScreenLabel = String::empty);
  39587. /** Returns a drop-down list that was added to the AlertWindow.
  39588. @param nameOfList the name that was passed into the addComboBox() method
  39589. when creating the drop-down
  39590. @returns the ComboBox component, or 0 if none was found for the given name.
  39591. */
  39592. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  39593. /** Adds a block of text.
  39594. This is handy for adding a multi-line note next to a textbox or combo-box,
  39595. to provide more details about what's going on.
  39596. */
  39597. void addTextBlock (const String& text);
  39598. /** Adds a progress-bar to the window.
  39599. @param progressValue a variable that will be repeatedly checked while the
  39600. dialog box is visible, to see how far the process has
  39601. got. The value should be in the range 0 to 1.0
  39602. */
  39603. void addProgressBarComponent (double& progressValue);
  39604. /** Adds a user-defined component to the dialog box.
  39605. @param component the component to add - its size should be set up correctly
  39606. before it is passed in. The caller is responsible for deleting
  39607. the component later on - the AlertWindow won't delete it.
  39608. */
  39609. void addCustomComponent (Component* component);
  39610. /** Returns the number of custom components in the dialog box.
  39611. @see getCustomComponent, addCustomComponent
  39612. */
  39613. int getNumCustomComponents() const;
  39614. /** Returns one of the custom components in the dialog box.
  39615. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39616. will return 0
  39617. @see getNumCustomComponents, addCustomComponent
  39618. */
  39619. Component* getCustomComponent (int index) const;
  39620. /** Removes one of the custom components in the dialog box.
  39621. Note that this won't delete it, it just removes the component from the window
  39622. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  39623. will return 0
  39624. @returns the component that was removed (or zero)
  39625. @see getNumCustomComponents, addCustomComponent
  39626. */
  39627. Component* removeCustomComponent (int index);
  39628. /** Returns true if the window contains any components other than just buttons.*/
  39629. bool containsAnyExtraComponents() const;
  39630. // easy-to-use message box functions:
  39631. /** Shows a dialog box that just has a message and a single button to get rid of it.
  39632. The box is shown modally, and the method returns after the user
  39633. has clicked the button (or pressed the escape or return keys).
  39634. @param iconType the type of icon to show
  39635. @param title the headline to show at the top of the box
  39636. @param message a longer, more descriptive message to show underneath the
  39637. headline
  39638. @param buttonText the text to show in the button - if this string is empty, the
  39639. default string "ok" (or a localised version) will be used.
  39640. @param associatedComponent if this is non-zero, it specifies the component that the
  39641. alert window should be associated with. Depending on the look
  39642. and feel, this might be used for positioning of the alert window.
  39643. */
  39644. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  39645. const String& title,
  39646. const String& message,
  39647. const String& buttonText = String::empty,
  39648. Component* associatedComponent = 0);
  39649. /** Shows a dialog box with two buttons.
  39650. Ideal for ok/cancel or yes/no choices. The return key can also be used
  39651. to trigger the first button, and the escape key for the second button.
  39652. @param iconType the type of icon to show
  39653. @param title the headline to show at the top of the box
  39654. @param message a longer, more descriptive message to show underneath the
  39655. headline
  39656. @param button1Text the text to show in the first button - if this string is
  39657. empty, the default string "ok" (or a localised version of it)
  39658. will be used.
  39659. @param button2Text the text to show in the second button - if this string is
  39660. empty, the default string "cancel" (or a localised version of it)
  39661. will be used.
  39662. @param associatedComponent if this is non-zero, it specifies the component that the
  39663. alert window should be associated with. Depending on the look
  39664. and feel, this might be used for positioning of the alert window.
  39665. @returns true if button 1 was clicked, false if it was button 2
  39666. */
  39667. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  39668. const String& title,
  39669. const String& message,
  39670. const String& button1Text = String::empty,
  39671. const String& button2Text = String::empty,
  39672. Component* associatedComponent = 0);
  39673. /** Shows a dialog box with three buttons.
  39674. Ideal for yes/no/cancel boxes.
  39675. The escape key can be used to trigger the third button.
  39676. @param iconType the type of icon to show
  39677. @param title the headline to show at the top of the box
  39678. @param message a longer, more descriptive message to show underneath the
  39679. headline
  39680. @param button1Text the text to show in the first button - if an empty string, then
  39681. "yes" will be used (or a localised version of it)
  39682. @param button2Text the text to show in the first button - if an empty string, then
  39683. "no" will be used (or a localised version of it)
  39684. @param button3Text the text to show in the first button - if an empty string, then
  39685. "cancel" will be used (or a localised version of it)
  39686. @param associatedComponent if this is non-zero, it specifies the component that the
  39687. alert window should be associated with. Depending on the look
  39688. and feel, this might be used for positioning of the alert window.
  39689. @returns one of the following values:
  39690. - 0 if the third button was pressed (normally used for 'cancel')
  39691. - 1 if the first button was pressed (normally used for 'yes')
  39692. - 2 if the middle button was pressed (normally used for 'no')
  39693. */
  39694. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  39695. const String& title,
  39696. const String& message,
  39697. const String& button1Text = String::empty,
  39698. const String& button2Text = String::empty,
  39699. const String& button3Text = String::empty,
  39700. Component* associatedComponent = 0);
  39701. /** Shows an operating-system native dialog box.
  39702. @param title the title to use at the top
  39703. @param bodyText the longer message to show
  39704. @param isOkCancel if true, this will show an ok/cancel box, if false,
  39705. it'll show a box with just an ok button
  39706. @returns true if the ok button was pressed, false if they pressed cancel.
  39707. */
  39708. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  39709. const String& bodyText,
  39710. bool isOkCancel);
  39711. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  39712. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39713. methods.
  39714. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39715. */
  39716. enum ColourIds
  39717. {
  39718. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  39719. textColourId = 0x1001810, /**< The colour for the text. */
  39720. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  39721. };
  39722. juce_UseDebuggingNewOperator
  39723. protected:
  39724. /** @internal */
  39725. void paint (Graphics& g);
  39726. /** @internal */
  39727. void mouseDown (const MouseEvent& e);
  39728. /** @internal */
  39729. void mouseDrag (const MouseEvent& e);
  39730. /** @internal */
  39731. bool keyPressed (const KeyPress& key);
  39732. /** @internal */
  39733. void buttonClicked (Button* button);
  39734. /** @internal */
  39735. void lookAndFeelChanged();
  39736. /** @internal */
  39737. void userTriedToCloseWindow();
  39738. /** @internal */
  39739. int getDesktopWindowStyleFlags() const;
  39740. private:
  39741. String text;
  39742. TextLayout textLayout;
  39743. AlertIconType alertIconType;
  39744. ComponentBoundsConstrainer constrainer;
  39745. ComponentDragger dragger;
  39746. Rectangle<int> textArea;
  39747. Array<void*> buttons, textBoxes, comboBoxes;
  39748. Array<void*> progressBars, customComps, textBlocks, allComps;
  39749. StringArray textboxNames, comboBoxNames;
  39750. Font font;
  39751. Component* associatedComponent;
  39752. void updateLayout (bool onlyIncreaseSize);
  39753. // disable copy constructor
  39754. AlertWindow (const AlertWindow&);
  39755. AlertWindow& operator= (const AlertWindow&);
  39756. };
  39757. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  39758. /*** End of inlined file: juce_AlertWindow.h ***/
  39759. class ToggleButton;
  39760. class TextButton;
  39761. class AlertWindow;
  39762. class TextLayout;
  39763. class ScrollBar;
  39764. class BubbleComponent;
  39765. class ComboBox;
  39766. class Button;
  39767. class FilenameComponent;
  39768. class DocumentWindow;
  39769. class ResizableWindow;
  39770. class GroupComponent;
  39771. class MenuBarComponent;
  39772. class DropShadower;
  39773. class GlyphArrangement;
  39774. class PropertyComponent;
  39775. class TableHeaderComponent;
  39776. class Toolbar;
  39777. class ToolbarItemComponent;
  39778. class PopupMenu;
  39779. class ProgressBar;
  39780. class FileBrowserComponent;
  39781. class DirectoryContentsDisplayComponent;
  39782. class FilePreviewComponent;
  39783. class ImageButton;
  39784. /**
  39785. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  39786. can be used to apply different 'skins' to the application.
  39787. */
  39788. class JUCE_API LookAndFeel
  39789. {
  39790. public:
  39791. /** Creates the default JUCE look and feel. */
  39792. LookAndFeel();
  39793. /** Destructor. */
  39794. virtual ~LookAndFeel();
  39795. /** Returns the current default look-and-feel for a component to use when it
  39796. hasn't got one explicitly set.
  39797. @see setDefaultLookAndFeel
  39798. */
  39799. static LookAndFeel& getDefaultLookAndFeel() throw();
  39800. /** Changes the default look-and-feel.
  39801. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  39802. set to 0, it will revert to using the default one. The
  39803. object passed-in must be deleted by the caller when
  39804. it's no longer needed.
  39805. @see getDefaultLookAndFeel
  39806. */
  39807. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  39808. /** Looks for a colour that has been registered with the given colour ID number.
  39809. If a colour has been set for this ID number using setColour(), then it is
  39810. returned. If none has been set, it will just return Colours::black.
  39811. The colour IDs for various purposes are stored as enums in the components that
  39812. they are relevent to - for an example, see Slider::ColourIds,
  39813. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  39814. If you're looking up a colour for use in drawing a component, it's usually
  39815. best not to call this directly, but to use the Component::findColour() method
  39816. instead. That will first check whether a suitable colour has been registered
  39817. directly with the component, and will fall-back on calling the component's
  39818. LookAndFeel's findColour() method if none is found.
  39819. @see setColour, Component::findColour, Component::setColour
  39820. */
  39821. const Colour findColour (int colourId) const throw();
  39822. /** Registers a colour to be used for a particular purpose.
  39823. For more details, see the comments for findColour().
  39824. @see findColour, Component::findColour, Component::setColour
  39825. */
  39826. void setColour (int colourId, const Colour& colour) throw();
  39827. /** Returns true if the specified colour ID has been explicitly set using the
  39828. setColour() method.
  39829. */
  39830. bool isColourSpecified (int colourId) const throw();
  39831. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  39832. /** Allows you to change the default sans-serif font.
  39833. If you need to supply your own Typeface object for any of the default fonts, rather
  39834. than just supplying the name (e.g. if you want to use an embedded font), then
  39835. you should instead override getTypefaceForFont() to create and return the typeface.
  39836. */
  39837. void setDefaultSansSerifTypefaceName (const String& newName);
  39838. /** Override this to get the chance to swap a component's mouse cursor for a
  39839. customised one.
  39840. */
  39841. virtual const MouseCursor getMouseCursorFor (Component& component);
  39842. /** Draws the lozenge-shaped background for a standard button. */
  39843. virtual void drawButtonBackground (Graphics& g,
  39844. Button& button,
  39845. const Colour& backgroundColour,
  39846. bool isMouseOverButton,
  39847. bool isButtonDown);
  39848. virtual const Font getFontForTextButton (TextButton& button);
  39849. /** Draws the text for a TextButton. */
  39850. virtual void drawButtonText (Graphics& g,
  39851. TextButton& button,
  39852. bool isMouseOverButton,
  39853. bool isButtonDown);
  39854. /** Draws the contents of a standard ToggleButton. */
  39855. virtual void drawToggleButton (Graphics& g,
  39856. ToggleButton& button,
  39857. bool isMouseOverButton,
  39858. bool isButtonDown);
  39859. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  39860. virtual void drawTickBox (Graphics& g,
  39861. Component& component,
  39862. float x, float y, float w, float h,
  39863. bool ticked,
  39864. bool isEnabled,
  39865. bool isMouseOverButton,
  39866. bool isButtonDown);
  39867. /* AlertWindow handling..
  39868. */
  39869. virtual AlertWindow* createAlertWindow (const String& title,
  39870. const String& message,
  39871. const String& button1,
  39872. const String& button2,
  39873. const String& button3,
  39874. AlertWindow::AlertIconType iconType,
  39875. int numButtons,
  39876. Component* associatedComponent);
  39877. virtual void drawAlertBox (Graphics& g,
  39878. AlertWindow& alert,
  39879. const Rectangle<int>& textArea,
  39880. TextLayout& textLayout);
  39881. virtual int getAlertBoxWindowFlags();
  39882. virtual int getAlertWindowButtonHeight();
  39883. virtual const Font getAlertWindowFont();
  39884. /** Draws a progress bar.
  39885. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  39886. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  39887. isn't known). It can use the current time as a basis for playing an animation.
  39888. (Used by progress bars in AlertWindow).
  39889. */
  39890. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  39891. int width, int height,
  39892. double progress, const String& textToShow);
  39893. // Draws a small image that spins to indicate that something's happening..
  39894. // This method should use the current time to animate itself, so just keep
  39895. // repainting it every so often.
  39896. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  39897. int x, int y, int w, int h);
  39898. /** Draws one of the buttons on a scrollbar.
  39899. @param g the context to draw into
  39900. @param scrollbar the bar itself
  39901. @param width the width of the button
  39902. @param height the height of the button
  39903. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  39904. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39905. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  39906. @param isButtonDown whether the mouse button's held down
  39907. */
  39908. virtual void drawScrollbarButton (Graphics& g,
  39909. ScrollBar& scrollbar,
  39910. int width, int height,
  39911. int buttonDirection,
  39912. bool isScrollbarVertical,
  39913. bool isMouseOverButton,
  39914. bool isButtonDown);
  39915. /** Draws the thumb area of a scrollbar.
  39916. @param g the context to draw into
  39917. @param scrollbar the bar itself
  39918. @param x the x position of the left edge of the thumb area to draw in
  39919. @param y the y position of the top edge of the thumb area to draw in
  39920. @param width the width of the thumb area to draw in
  39921. @param height the height of the thumb area to draw in
  39922. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  39923. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  39924. thumb, or its x position for horizontal bars
  39925. @param thumbSize for vertical bars, the height of the thumb, or its width for
  39926. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  39927. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  39928. currently dragging the thumb
  39929. @param isMouseDown whether the mouse is currently dragging the scrollbar
  39930. */
  39931. virtual void drawScrollbar (Graphics& g,
  39932. ScrollBar& scrollbar,
  39933. int x, int y,
  39934. int width, int height,
  39935. bool isScrollbarVertical,
  39936. int thumbStartPosition,
  39937. int thumbSize,
  39938. bool isMouseOver,
  39939. bool isMouseDown);
  39940. /** Returns the component effect to use for a scrollbar */
  39941. virtual ImageEffectFilter* getScrollbarEffect();
  39942. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  39943. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  39944. /** Returns the default thickness to use for a scrollbar. */
  39945. virtual int getDefaultScrollbarWidth();
  39946. /** Returns the length in pixels to use for a scrollbar button. */
  39947. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  39948. /** Returns a tick shape for use in yes/no boxes, etc. */
  39949. virtual const Path getTickShape (float height);
  39950. /** Returns a cross shape for use in yes/no boxes, etc. */
  39951. virtual const Path getCrossShape (float height);
  39952. /** Draws the + or - box in a treeview. */
  39953. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  39954. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  39955. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  39956. // these return an image from the ImageCache, so use ImageCache::release() to free it
  39957. virtual Image* getDefaultFolderImage();
  39958. virtual Image* getDefaultDocumentFileImage();
  39959. virtual void createFileChooserHeaderText (const String& title,
  39960. const String& instructions,
  39961. GlyphArrangement& destArrangement,
  39962. int width);
  39963. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  39964. const String& filename, Image* icon,
  39965. const String& fileSizeDescription,
  39966. const String& fileTimeDescription,
  39967. bool isDirectory,
  39968. bool isItemSelected,
  39969. int itemIndex);
  39970. virtual Button* createFileBrowserGoUpButton();
  39971. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  39972. DirectoryContentsDisplayComponent* fileListComponent,
  39973. FilePreviewComponent* previewComp,
  39974. ComboBox* currentPathBox,
  39975. TextEditor* filenameBox,
  39976. Button* goUpButton);
  39977. virtual void drawBubble (Graphics& g,
  39978. float tipX, float tipY,
  39979. float boxX, float boxY, float boxW, float boxH);
  39980. /** Fills the background of a popup menu component. */
  39981. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  39982. /** Draws one of the items in a popup menu. */
  39983. virtual void drawPopupMenuItem (Graphics& g,
  39984. int width, int height,
  39985. bool isSeparator,
  39986. bool isActive,
  39987. bool isHighlighted,
  39988. bool isTicked,
  39989. bool hasSubMenu,
  39990. const String& text,
  39991. const String& shortcutKeyText,
  39992. Image* image,
  39993. const Colour* const textColour);
  39994. /** Returns the size and style of font to use in popup menus. */
  39995. virtual const Font getPopupMenuFont();
  39996. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  39997. int width, int height,
  39998. bool isScrollUpArrow);
  39999. /** Finds the best size for an item in a popup menu. */
  40000. virtual void getIdealPopupMenuItemSize (const String& text,
  40001. bool isSeparator,
  40002. int standardMenuItemHeight,
  40003. int& idealWidth,
  40004. int& idealHeight);
  40005. virtual int getMenuWindowFlags();
  40006. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40007. bool isMouseOverBar,
  40008. MenuBarComponent& menuBar);
  40009. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40010. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40011. virtual void drawMenuBarItem (Graphics& g,
  40012. int width, int height,
  40013. int itemIndex,
  40014. const String& itemText,
  40015. bool isMouseOverItem,
  40016. bool isMenuOpen,
  40017. bool isMouseOverBar,
  40018. MenuBarComponent& menuBar);
  40019. virtual void drawComboBox (Graphics& g, int width, int height,
  40020. bool isButtonDown,
  40021. int buttonX, int buttonY,
  40022. int buttonW, int buttonH,
  40023. ComboBox& box);
  40024. virtual const Font getComboBoxFont (ComboBox& box);
  40025. virtual Label* createComboBoxTextBox (ComboBox& box);
  40026. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40027. virtual void drawLabel (Graphics& g, Label& label);
  40028. virtual void drawLinearSlider (Graphics& g,
  40029. int x, int y,
  40030. int width, int height,
  40031. float sliderPos,
  40032. float minSliderPos,
  40033. float maxSliderPos,
  40034. const Slider::SliderStyle style,
  40035. Slider& slider);
  40036. virtual void drawLinearSliderBackground (Graphics& g,
  40037. int x, int y,
  40038. int width, int height,
  40039. float sliderPos,
  40040. float minSliderPos,
  40041. float maxSliderPos,
  40042. const Slider::SliderStyle style,
  40043. Slider& slider);
  40044. virtual void drawLinearSliderThumb (Graphics& g,
  40045. int x, int y,
  40046. int width, int height,
  40047. float sliderPos,
  40048. float minSliderPos,
  40049. float maxSliderPos,
  40050. const Slider::SliderStyle style,
  40051. Slider& slider);
  40052. virtual int getSliderThumbRadius (Slider& slider);
  40053. virtual void drawRotarySlider (Graphics& g,
  40054. int x, int y,
  40055. int width, int height,
  40056. float sliderPosProportional,
  40057. float rotaryStartAngle,
  40058. float rotaryEndAngle,
  40059. Slider& slider);
  40060. virtual Button* createSliderButton (bool isIncrement);
  40061. virtual Label* createSliderTextBox (Slider& slider);
  40062. virtual ImageEffectFilter* getSliderEffect();
  40063. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40064. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40065. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40066. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40067. ComboBox* filenameBox, Button* browseButton);
  40068. virtual void drawCornerResizer (Graphics& g,
  40069. int w, int h,
  40070. bool isMouseOver,
  40071. bool isMouseDragging);
  40072. virtual void drawResizableFrame (Graphics& g,
  40073. int w, int h,
  40074. const BorderSize& borders);
  40075. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  40076. const BorderSize& border,
  40077. ResizableWindow& window);
  40078. virtual void drawResizableWindowBorder (Graphics& g,
  40079. int w, int h,
  40080. const BorderSize& border,
  40081. ResizableWindow& window);
  40082. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40083. Graphics& g, int w, int h,
  40084. int titleSpaceX, int titleSpaceW,
  40085. const Image* icon,
  40086. bool drawTitleTextOnLeft);
  40087. virtual Button* createDocumentWindowButton (int buttonType);
  40088. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40089. int titleBarX, int titleBarY,
  40090. int titleBarW, int titleBarH,
  40091. Button* minimiseButton,
  40092. Button* maximiseButton,
  40093. Button* closeButton,
  40094. bool positionTitleBarButtonsOnLeft);
  40095. virtual int getDefaultMenuBarHeight();
  40096. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40097. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40098. int w, int h,
  40099. bool isVerticalBar,
  40100. bool isMouseOver,
  40101. bool isMouseDragging);
  40102. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40103. const String& text,
  40104. const Justification& position,
  40105. GroupComponent& group);
  40106. virtual void createTabButtonShape (Path& p,
  40107. int width, int height,
  40108. int tabIndex,
  40109. const String& text,
  40110. Button& button,
  40111. TabbedButtonBar::Orientation orientation,
  40112. bool isMouseOver,
  40113. bool isMouseDown,
  40114. bool isFrontTab);
  40115. virtual void fillTabButtonShape (Graphics& g,
  40116. const Path& path,
  40117. const Colour& preferredBackgroundColour,
  40118. int tabIndex,
  40119. const String& text,
  40120. Button& button,
  40121. TabbedButtonBar::Orientation orientation,
  40122. bool isMouseOver,
  40123. bool isMouseDown,
  40124. bool isFrontTab);
  40125. virtual void drawTabButtonText (Graphics& g,
  40126. int x, int y, int w, int h,
  40127. const Colour& preferredBackgroundColour,
  40128. int tabIndex,
  40129. const String& text,
  40130. Button& button,
  40131. TabbedButtonBar::Orientation orientation,
  40132. bool isMouseOver,
  40133. bool isMouseDown,
  40134. bool isFrontTab);
  40135. virtual int getTabButtonOverlap (int tabDepth);
  40136. virtual int getTabButtonSpaceAroundImage();
  40137. virtual int getTabButtonBestWidth (int tabIndex,
  40138. const String& text,
  40139. int tabDepth,
  40140. Button& button);
  40141. virtual void drawTabButton (Graphics& g,
  40142. int w, int h,
  40143. const Colour& preferredColour,
  40144. int tabIndex,
  40145. const String& text,
  40146. Button& button,
  40147. TabbedButtonBar::Orientation orientation,
  40148. bool isMouseOver,
  40149. bool isMouseDown,
  40150. bool isFrontTab);
  40151. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40152. int w, int h,
  40153. TabbedButtonBar& tabBar,
  40154. TabbedButtonBar::Orientation orientation);
  40155. virtual Button* createTabBarExtrasButton();
  40156. virtual void drawImageButton (Graphics& g, Image* image,
  40157. int imageX, int imageY, int imageW, int imageH,
  40158. const Colour& overlayColour,
  40159. float imageOpacity,
  40160. ImageButton& button);
  40161. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40162. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40163. int width, int height,
  40164. bool isMouseOver, bool isMouseDown,
  40165. int columnFlags);
  40166. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40167. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40168. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40169. bool isMouseOver, bool isMouseDown,
  40170. ToolbarItemComponent& component);
  40171. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40172. const String& text, ToolbarItemComponent& component);
  40173. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40174. bool isOpen, int width, int height);
  40175. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40176. PropertyComponent& component);
  40177. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40178. PropertyComponent& component);
  40179. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  40180. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40181. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  40182. /**
  40183. */
  40184. virtual void playAlertSound();
  40185. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40186. static void drawGlassSphere (Graphics& g,
  40187. float x, float y,
  40188. float diameter,
  40189. const Colour& colour,
  40190. float outlineThickness) throw();
  40191. static void drawGlassPointer (Graphics& g,
  40192. float x, float y,
  40193. float diameter,
  40194. const Colour& colour, float outlineThickness,
  40195. int direction) throw();
  40196. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40197. static void drawGlassLozenge (Graphics& g,
  40198. float x, float y,
  40199. float width, float height,
  40200. const Colour& colour,
  40201. float outlineThickness,
  40202. float cornerSize,
  40203. bool flatOnLeft, bool flatOnRight,
  40204. bool flatOnTop, bool flatOnBottom) throw();
  40205. juce_UseDebuggingNewOperator
  40206. private:
  40207. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40208. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40209. Array <int> colourIds;
  40210. Array <Colour> colours;
  40211. // default typeface names
  40212. String defaultSans, defaultSerif, defaultFixed;
  40213. void drawShinyButtonShape (Graphics& g,
  40214. float x, float y, float w, float h, float maxCornerSize,
  40215. const Colour& baseColour,
  40216. float strokeWidth,
  40217. bool flatOnLeft,
  40218. bool flatOnRight,
  40219. bool flatOnTop,
  40220. bool flatOnBottom) throw();
  40221. LookAndFeel (const LookAndFeel&);
  40222. LookAndFeel& operator= (const LookAndFeel&);
  40223. };
  40224. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40225. /*** End of inlined file: juce_LookAndFeel.h ***/
  40226. #endif
  40227. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40228. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40229. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40230. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40231. /**
  40232. The original Juce look-and-feel.
  40233. */
  40234. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40235. {
  40236. public:
  40237. /** Creates the default JUCE look and feel. */
  40238. OldSchoolLookAndFeel();
  40239. /** Destructor. */
  40240. virtual ~OldSchoolLookAndFeel();
  40241. /** Draws the lozenge-shaped background for a standard button. */
  40242. virtual void drawButtonBackground (Graphics& g,
  40243. Button& button,
  40244. const Colour& backgroundColour,
  40245. bool isMouseOverButton,
  40246. bool isButtonDown);
  40247. /** Draws the contents of a standard ToggleButton. */
  40248. virtual void drawToggleButton (Graphics& g,
  40249. ToggleButton& button,
  40250. bool isMouseOverButton,
  40251. bool isButtonDown);
  40252. virtual void drawTickBox (Graphics& g,
  40253. Component& component,
  40254. float x, float y, float w, float h,
  40255. bool ticked,
  40256. bool isEnabled,
  40257. bool isMouseOverButton,
  40258. bool isButtonDown);
  40259. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40260. int width, int height,
  40261. double progress, const String& textToShow);
  40262. virtual void drawScrollbarButton (Graphics& g,
  40263. ScrollBar& scrollbar,
  40264. int width, int height,
  40265. int buttonDirection,
  40266. bool isScrollbarVertical,
  40267. bool isMouseOverButton,
  40268. bool isButtonDown);
  40269. virtual void drawScrollbar (Graphics& g,
  40270. ScrollBar& scrollbar,
  40271. int x, int y,
  40272. int width, int height,
  40273. bool isScrollbarVertical,
  40274. int thumbStartPosition,
  40275. int thumbSize,
  40276. bool isMouseOver,
  40277. bool isMouseDown);
  40278. virtual ImageEffectFilter* getScrollbarEffect();
  40279. virtual void drawTextEditorOutline (Graphics& g,
  40280. int width, int height,
  40281. TextEditor& textEditor);
  40282. /** Fills the background of a popup menu component. */
  40283. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40284. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40285. bool isMouseOverBar,
  40286. MenuBarComponent& menuBar);
  40287. virtual void drawComboBox (Graphics& g, int width, int height,
  40288. bool isButtonDown,
  40289. int buttonX, int buttonY,
  40290. int buttonW, int buttonH,
  40291. ComboBox& box);
  40292. virtual const Font getComboBoxFont (ComboBox& box);
  40293. virtual void drawLinearSlider (Graphics& g,
  40294. int x, int y,
  40295. int width, int height,
  40296. float sliderPos,
  40297. float minSliderPos,
  40298. float maxSliderPos,
  40299. const Slider::SliderStyle style,
  40300. Slider& slider);
  40301. virtual int getSliderThumbRadius (Slider& slider);
  40302. virtual Button* createSliderButton (bool isIncrement);
  40303. virtual ImageEffectFilter* getSliderEffect();
  40304. virtual void drawCornerResizer (Graphics& g,
  40305. int w, int h,
  40306. bool isMouseOver,
  40307. bool isMouseDragging);
  40308. virtual Button* createDocumentWindowButton (int buttonType);
  40309. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40310. int titleBarX, int titleBarY,
  40311. int titleBarW, int titleBarH,
  40312. Button* minimiseButton,
  40313. Button* maximiseButton,
  40314. Button* closeButton,
  40315. bool positionTitleBarButtonsOnLeft);
  40316. juce_UseDebuggingNewOperator
  40317. private:
  40318. DropShadowEffect scrollbarShadow;
  40319. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40320. OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40321. };
  40322. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40323. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40324. #endif
  40325. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  40326. #endif
  40327. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  40328. #endif
  40329. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  40330. #endif
  40331. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40332. /*** Start of inlined file: juce_PopupMenuCustomComponent.h ***/
  40333. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40334. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40335. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  40336. @see PopupMenu::addCustomItem
  40337. */
  40338. class JUCE_API PopupMenuCustomComponent : public Component,
  40339. public ReferenceCountedObject
  40340. {
  40341. public:
  40342. /** Destructor. */
  40343. ~PopupMenuCustomComponent();
  40344. /** Chooses the size that this component would like to have.
  40345. Note that the size which this method returns isn't necessarily the one that
  40346. the menu will give it, as it will be stretched to fit the other items in
  40347. the menu.
  40348. */
  40349. virtual void getIdealSize (int& idealWidth,
  40350. int& idealHeight) = 0;
  40351. /** Dismisses the menu indicating that this item has been chosen.
  40352. This will cause the menu to exit from its modal state, returning
  40353. this item's id as the result.
  40354. */
  40355. void triggerMenuItem();
  40356. /** Returns true if this item should be highlighted because the mouse is
  40357. over it.
  40358. You can call this method in your paint() method to find out whether
  40359. to draw a highlight.
  40360. */
  40361. bool isItemHighlighted() const throw() { return isHighlighted; }
  40362. protected:
  40363. /** Constructor.
  40364. If isTriggeredAutomatically is true, then the menu will automatically detect
  40365. a click on this component and use that to trigger it. If it's false, then it's
  40366. up to your class to manually trigger the item if it wants to.
  40367. */
  40368. PopupMenuCustomComponent (bool isTriggeredAutomatically = true);
  40369. private:
  40370. friend class PopupMenu;
  40371. friend class PopupMenu::ItemComponent;
  40372. friend class PopupMenu::Window;
  40373. bool isHighlighted, isTriggeredAutomatically;
  40374. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  40375. PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  40376. };
  40377. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40378. /*** End of inlined file: juce_PopupMenuCustomComponent.h ***/
  40379. #endif
  40380. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  40381. #endif
  40382. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  40383. #endif
  40384. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  40385. #endif
  40386. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40387. #endif
  40388. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40389. /*** Start of inlined file: juce_LassoComponent.h ***/
  40390. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40391. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40392. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  40393. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40394. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40395. /** Manages a list of selectable items.
  40396. Use one of these to keep a track of things that the user has highlighted, like
  40397. icons or things in a list.
  40398. The class is templated so that you can use it to hold either a set of pointers
  40399. to objects, or a set of ID numbers or handles, for cases where each item may
  40400. not always have a corresponding object.
  40401. To be informed when items are selected/deselected, register a ChangeListener with
  40402. this object.
  40403. @see SelectableObject
  40404. */
  40405. template <class SelectableItemType>
  40406. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  40407. {
  40408. public:
  40409. typedef SelectableItemType ItemType;
  40410. /** Creates an empty set. */
  40411. SelectedItemSet()
  40412. {
  40413. }
  40414. /** Creates a set based on an array of items. */
  40415. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  40416. : selectedItems (items)
  40417. {
  40418. }
  40419. /** Creates a copy of another set. */
  40420. SelectedItemSet (const SelectedItemSet& other)
  40421. : selectedItems (other.selectedItems)
  40422. {
  40423. }
  40424. /** Creates a copy of another set. */
  40425. SelectedItemSet& operator= (const SelectedItemSet& other)
  40426. {
  40427. if (selectedItems != other.selectedItems)
  40428. {
  40429. selectedItems = other.selectedItems;
  40430. changed();
  40431. }
  40432. return *this;
  40433. }
  40434. /** Destructor. */
  40435. ~SelectedItemSet()
  40436. {
  40437. }
  40438. /** Clears any other currently selected items, and selects this item.
  40439. If this item is already the only thing selected, no change notification
  40440. will be sent out.
  40441. @see addToSelection, addToSelectionBasedOnModifiers
  40442. */
  40443. void selectOnly (SelectableItemType item)
  40444. {
  40445. if (isSelected (item))
  40446. {
  40447. for (int i = selectedItems.size(); --i >= 0;)
  40448. {
  40449. if (selectedItems.getUnchecked(i) != item)
  40450. {
  40451. deselect (selectedItems.getUnchecked(i));
  40452. i = jmin (i, selectedItems.size());
  40453. }
  40454. }
  40455. }
  40456. else
  40457. {
  40458. deselectAll();
  40459. changed();
  40460. selectedItems.add (item);
  40461. itemSelected (item);
  40462. }
  40463. }
  40464. /** Selects an item.
  40465. If the item is already selected, no change notification will be sent out.
  40466. @see selectOnly, addToSelectionBasedOnModifiers
  40467. */
  40468. void addToSelection (SelectableItemType item)
  40469. {
  40470. if (! isSelected (item))
  40471. {
  40472. changed();
  40473. selectedItems.add (item);
  40474. itemSelected (item);
  40475. }
  40476. }
  40477. /** Selects or deselects an item.
  40478. This will use the modifier keys to decide whether to deselect other items
  40479. first.
  40480. So if the shift key is held down, the item will be added without deselecting
  40481. anything (same as calling addToSelection() )
  40482. If no modifiers are down, the current selection will be cleared first (same
  40483. as calling selectOnly() )
  40484. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  40485. so it'll be added to the set unless it's already there, in which case it'll be
  40486. deselected.
  40487. If the items that you're selecting can also be dragged, you may need to use the
  40488. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  40489. subtleties of this kind of usage.
  40490. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  40491. */
  40492. void addToSelectionBasedOnModifiers (SelectableItemType item,
  40493. const ModifierKeys& modifiers)
  40494. {
  40495. if (modifiers.isShiftDown())
  40496. {
  40497. addToSelection (item);
  40498. }
  40499. else if (modifiers.isCommandDown())
  40500. {
  40501. if (isSelected (item))
  40502. deselect (item);
  40503. else
  40504. addToSelection (item);
  40505. }
  40506. else
  40507. {
  40508. selectOnly (item);
  40509. }
  40510. }
  40511. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  40512. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  40513. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  40514. makes it easy to handle multiple-selection of sets of objects that can also
  40515. be dragged.
  40516. For example, if you have several items already selected, and you click on
  40517. one of them (without dragging), then you'd expect this to deselect the other, and
  40518. just select the item you clicked on. But if you had clicked on this item and
  40519. dragged it, you'd have expected them all to stay selected.
  40520. When you call this method, you'll need to store the boolean result, because the
  40521. addToSelectionOnMouseUp() method will need to be know this value.
  40522. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  40523. */
  40524. bool addToSelectionOnMouseDown (SelectableItemType item,
  40525. const ModifierKeys& modifiers)
  40526. {
  40527. if (isSelected (item))
  40528. {
  40529. return ! modifiers.isPopupMenu();
  40530. }
  40531. else
  40532. {
  40533. addToSelectionBasedOnModifiers (item, modifiers);
  40534. return false;
  40535. }
  40536. }
  40537. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  40538. Call this during a mouseUp callback, when you have previously called the
  40539. addToSelectionOnMouseDown() method during your mouseDown event.
  40540. See addToSelectionOnMouseDown() for more info
  40541. @param item the item to select (or deselect)
  40542. @param modifiers the modifiers from the mouse-up event
  40543. @param wasItemDragged true if your item was dragged during the mouse click
  40544. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  40545. back from the addToSelectionOnMouseDown() call that you
  40546. should have made during the matching mouseDown event
  40547. */
  40548. void addToSelectionOnMouseUp (SelectableItemType item,
  40549. const ModifierKeys& modifiers,
  40550. const bool wasItemDragged,
  40551. const bool resultOfMouseDownSelectMethod)
  40552. {
  40553. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  40554. addToSelectionBasedOnModifiers (item, modifiers);
  40555. }
  40556. /** Deselects an item. */
  40557. void deselect (SelectableItemType item)
  40558. {
  40559. const int i = selectedItems.indexOf (item);
  40560. if (i >= 0)
  40561. {
  40562. changed();
  40563. itemDeselected (selectedItems.remove (i));
  40564. }
  40565. }
  40566. /** Deselects all items. */
  40567. void deselectAll()
  40568. {
  40569. if (selectedItems.size() > 0)
  40570. {
  40571. changed();
  40572. for (int i = selectedItems.size(); --i >= 0;)
  40573. {
  40574. itemDeselected (selectedItems.remove (i));
  40575. i = jmin (i, selectedItems.size());
  40576. }
  40577. }
  40578. }
  40579. /** Returns the number of currently selected items.
  40580. @see getSelectedItem
  40581. */
  40582. int getNumSelected() const throw()
  40583. {
  40584. return selectedItems.size();
  40585. }
  40586. /** Returns one of the currently selected items.
  40587. Returns 0 if the index is out-of-range.
  40588. @see getNumSelected
  40589. */
  40590. SelectableItemType getSelectedItem (const int index) const throw()
  40591. {
  40592. return selectedItems [index];
  40593. }
  40594. /** True if this item is currently selected. */
  40595. bool isSelected (const SelectableItemType item) const throw()
  40596. {
  40597. return selectedItems.contains (item);
  40598. }
  40599. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  40600. /** Can be overridden to do special handling when an item is selected.
  40601. For example, if the item is an object, you might want to call it and tell
  40602. it that it's being selected.
  40603. */
  40604. virtual void itemSelected (SelectableItemType item) { (void) item; }
  40605. /** Can be overridden to do special handling when an item is deselected.
  40606. For example, if the item is an object, you might want to call it and tell
  40607. it that it's being deselected.
  40608. */
  40609. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  40610. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  40611. */
  40612. void changed (const bool synchronous = false)
  40613. {
  40614. if (synchronous)
  40615. sendSynchronousChangeMessage (this);
  40616. else
  40617. sendChangeMessage (this);
  40618. }
  40619. juce_UseDebuggingNewOperator
  40620. private:
  40621. Array <SelectableItemType> selectedItems;
  40622. };
  40623. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40624. /*** End of inlined file: juce_SelectedItemSet.h ***/
  40625. /**
  40626. A class used by the LassoComponent to manage the things that it selects.
  40627. This allows the LassoComponent to find out which items are within the lasso,
  40628. and to change the list of selected items.
  40629. @see LassoComponent, SelectedItemSet
  40630. */
  40631. template <class SelectableItemType>
  40632. class LassoSource
  40633. {
  40634. public:
  40635. /** Destructor. */
  40636. virtual ~LassoSource() {}
  40637. /** Returns the set of items that lie within a given lassoable region.
  40638. Your implementation of this method must find all the relevent items that lie
  40639. within the given rectangle. and add them to the itemsFound array.
  40640. The co-ordinates are relative to the top-left of the lasso component's parent
  40641. component. (i.e. they are the same as the size and position of the lasso
  40642. component itself).
  40643. */
  40644. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  40645. const Rectangle<int>& area) = 0;
  40646. /** Returns the SelectedItemSet that the lasso should update.
  40647. This set will be continuously updated by the LassoComponent as it gets
  40648. dragged around, so make sure that you've got a ChangeListener attached to
  40649. the set so that your UI objects will know when the selection changes and
  40650. be able to update themselves appropriately.
  40651. */
  40652. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  40653. };
  40654. /**
  40655. A component that acts as a rectangular selection region, which you drag with
  40656. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  40657. To use one of these:
  40658. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  40659. component, and call its beginLasso() method, giving it a
  40660. suitable LassoSource object that it can use to find out which items are in
  40661. the active area.
  40662. - Each time your parent component gets a mouseDrag event, call dragLasso()
  40663. to update the lasso's position - it will use its LassoSource to calculate and
  40664. update the current selection.
  40665. - After the drag has finished and you get a mouseUp callback, you should call
  40666. endLasso() to clean up. This will make the lasso component invisible, and you
  40667. can remove it from the parent component, or delete it.
  40668. The class takes into account the modifier keys that are being held down while
  40669. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  40670. be added to the original selection; if ctrl or command is pressed, they will be
  40671. xor'ed with any previously selected items.
  40672. @see LassoSource, SelectedItemSet
  40673. */
  40674. template <class SelectableItemType>
  40675. class LassoComponent : public Component
  40676. {
  40677. public:
  40678. /** Creates a Lasso component.
  40679. The fill colour is used to fill the lasso'ed rectangle, and the outline
  40680. colour is used to draw a line around its edge.
  40681. */
  40682. explicit LassoComponent (const int outlineThickness_ = 1)
  40683. : source (0),
  40684. outlineThickness (outlineThickness_)
  40685. {
  40686. }
  40687. /** Destructor. */
  40688. ~LassoComponent()
  40689. {
  40690. }
  40691. /** Call this in your mouseDown event, to initialise a drag.
  40692. Pass in a suitable LassoSource object which the lasso will use to find
  40693. the items and change the selection.
  40694. After using this method to initialise the lasso, repeatedly call dragLasso()
  40695. in your component's mouseDrag callback.
  40696. @see dragLasso, endLasso, LassoSource
  40697. */
  40698. void beginLasso (const MouseEvent& e,
  40699. LassoSource <SelectableItemType>* const lassoSource)
  40700. {
  40701. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  40702. jassert (lassoSource != 0); // the source can't be null!
  40703. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  40704. source = lassoSource;
  40705. if (lassoSource != 0)
  40706. originalSelection = lassoSource->getLassoSelection().getItemArray();
  40707. setSize (0, 0);
  40708. dragStartPos = e.getMouseDownPosition();
  40709. }
  40710. /** Call this in your mouseDrag event, to update the lasso's position.
  40711. This must be repeatedly calling when the mouse is dragged, after you've
  40712. first initialised the lasso with beginLasso().
  40713. This method takes into account the modifier keys that are being held down, so
  40714. if shift is pressed, then the lassoed items will be added to any that were
  40715. previously selected; if ctrl or command is pressed, then they will be xor'ed
  40716. with previously selected items.
  40717. @see beginLasso, endLasso
  40718. */
  40719. void dragLasso (const MouseEvent& e)
  40720. {
  40721. if (source != 0)
  40722. {
  40723. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  40724. setVisible (true);
  40725. Array <SelectableItemType> itemsInLasso;
  40726. source->findLassoItemsInArea (itemsInLasso, getBounds());
  40727. if (e.mods.isShiftDown())
  40728. {
  40729. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  40730. itemsInLasso.addArray (originalSelection);
  40731. }
  40732. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  40733. {
  40734. Array <SelectableItemType> originalMinusNew (originalSelection);
  40735. originalMinusNew.removeValuesIn (itemsInLasso);
  40736. itemsInLasso.removeValuesIn (originalSelection);
  40737. itemsInLasso.addArray (originalMinusNew);
  40738. }
  40739. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  40740. }
  40741. }
  40742. /** Call this in your mouseUp event, after the lasso has been dragged.
  40743. @see beginLasso, dragLasso
  40744. */
  40745. void endLasso()
  40746. {
  40747. source = 0;
  40748. originalSelection.clear();
  40749. setVisible (false);
  40750. }
  40751. /** A set of colour IDs to use to change the colour of various aspects of the label.
  40752. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40753. methods.
  40754. Note that you can also use the constants from TextEditor::ColourIds to change the
  40755. colour of the text editor that is opened when a label is editable.
  40756. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40757. */
  40758. enum ColourIds
  40759. {
  40760. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  40761. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  40762. };
  40763. /** @internal */
  40764. void paint (Graphics& g)
  40765. {
  40766. g.fillAll (findColour (lassoFillColourId));
  40767. g.setColour (findColour (lassoOutlineColourId));
  40768. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  40769. // this suggests that you've left a lasso comp lying around after the
  40770. // mouse drag has finished.. Be careful to call endLasso() when you get a
  40771. // mouse-up event.
  40772. jassert (isMouseButtonDownAnywhere());
  40773. }
  40774. /** @internal */
  40775. bool hitTest (int, int) { return false; }
  40776. juce_UseDebuggingNewOperator
  40777. private:
  40778. Array <SelectableItemType> originalSelection;
  40779. LassoSource <SelectableItemType>* source;
  40780. int outlineThickness;
  40781. Point<int> dragStartPos;
  40782. };
  40783. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40784. /*** End of inlined file: juce_LassoComponent.h ***/
  40785. #endif
  40786. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  40787. #endif
  40788. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  40789. #endif
  40790. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  40791. /*** Start of inlined file: juce_MouseHoverDetector.h ***/
  40792. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  40793. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  40794. /**
  40795. Monitors a component for mouse activity, and triggers a callback
  40796. when the mouse hovers in one place for a specified length of time.
  40797. To use a hover-detector, just create one and call its setHoverComponent()
  40798. method to start it watching a component. You can call setHoverComponent (0)
  40799. to make it inactive.
  40800. (Be careful not to delete a component that's being monitored without first
  40801. stopping or deleting the hover detector).
  40802. */
  40803. class JUCE_API MouseHoverDetector
  40804. {
  40805. public:
  40806. /** Creates a hover detector.
  40807. Initially the object is inactive, and you need to tell it which component
  40808. to monitor, using the setHoverComponent() method.
  40809. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  40810. needs to stay still before the mouseHovered() method
  40811. is invoked. You can change this setting later with
  40812. the setHoverTimeMillisecs() method
  40813. */
  40814. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  40815. /** Destructor. */
  40816. virtual ~MouseHoverDetector();
  40817. /** Changes the time for which the mouse has to stay still before it's considered
  40818. to be hovering.
  40819. */
  40820. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  40821. /** Changes the component that's being monitored for hovering.
  40822. Be careful not to delete a component that's being monitored without first
  40823. stopping or deleting the hover detector.
  40824. */
  40825. void setHoverComponent (Component* const newSourceComponent);
  40826. protected:
  40827. /** Called back when the mouse hovers.
  40828. After the mouse has stayed still over the component for the length of time
  40829. specified by setHoverTimeMillisecs(), this method will be invoked.
  40830. When the mouse is first moved after this callback has occurred, the
  40831. mouseMovedAfterHover() method will be called.
  40832. @param mouseX the mouse's X position relative to the component being monitored
  40833. @param mouseY the mouse's Y position relative to the component being monitored
  40834. */
  40835. virtual void mouseHovered (int mouseX,
  40836. int mouseY) = 0;
  40837. /** Called when the mouse is moved away after just having hovered. */
  40838. virtual void mouseMovedAfterHover() = 0;
  40839. private:
  40840. class JUCE_API HoverDetectorInternal : public MouseListener,
  40841. public Timer
  40842. {
  40843. public:
  40844. MouseHoverDetector* owner;
  40845. int lastX, lastY;
  40846. void timerCallback();
  40847. void mouseEnter (const MouseEvent&);
  40848. void mouseExit (const MouseEvent&);
  40849. void mouseDown (const MouseEvent&);
  40850. void mouseUp (const MouseEvent&);
  40851. void mouseMove (const MouseEvent&);
  40852. void mouseWheelMove (const MouseEvent&, float, float);
  40853. } internalTimer;
  40854. friend class HoverDetectorInternal;
  40855. Component* source;
  40856. int hoverTimeMillisecs;
  40857. bool hasJustHovered;
  40858. void hoverTimerCallback();
  40859. void checkJustHoveredCallback();
  40860. MouseHoverDetector (const MouseHoverDetector&);
  40861. MouseHoverDetector& operator= (const MouseHoverDetector&);
  40862. };
  40863. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  40864. /*** End of inlined file: juce_MouseHoverDetector.h ***/
  40865. #endif
  40866. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  40867. /*** Start of inlined file: juce_MouseInputSource.h ***/
  40868. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  40869. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  40870. class Component;
  40871. class ComponentPeer;
  40872. class MouseInputSourceInternal;
  40873. /**
  40874. Represents a linear source of mouse events from a mouse device or individual finger
  40875. in a multi-touch environment.
  40876. Each MouseEvent object contains a reference to the MouseInputSource that generated
  40877. it. In an environment with a single mouse for input, all events will come from the
  40878. same source, but in a multi-touch system, there may be multiple MouseInputSource
  40879. obects active, each representing a stream of events coming from a particular finger.
  40880. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  40881. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  40882. the only events that can happen between a mouseDown and its corresponding mouseUp are
  40883. mouseDrags, etc.
  40884. When there are multiple touches arriving from multiple MouseInputSources, their
  40885. event streams may arrive in an interleaved order, so you should use the getIndex()
  40886. method to find out which finger each event came from.
  40887. @see MouseEvent
  40888. */
  40889. class JUCE_API MouseInputSource
  40890. {
  40891. public:
  40892. /** Creates a MouseInputSource.
  40893. You should never actually create a MouseInputSource in your own code - the
  40894. library takes care of managing these objects.
  40895. */
  40896. MouseInputSource (int index, bool isMouseDevice);
  40897. /** Destructor. */
  40898. ~MouseInputSource();
  40899. /** Returns true if this object represents a normal desk-based mouse device. */
  40900. bool isMouse() const;
  40901. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  40902. bool isTouch() const;
  40903. /** Returns true if this source has an on-screen pointer that can hover over
  40904. items without clicking them.
  40905. */
  40906. bool canHover() const;
  40907. /** Returns true if this source may have a scroll wheel. */
  40908. bool hasMouseWheel() const;
  40909. /** Returns this source's index in the global list of possible sources.
  40910. If the system only has a single mouse, there will only be a single MouseInputSource
  40911. with an index of 0.
  40912. If the system supports multi-touch input, then the index will represent a finger
  40913. number, starting from 0. When the first touch event begins, it will have finger
  40914. number 0, and then if a second touch happens while the first is still down, it
  40915. will have index 1, etc.
  40916. */
  40917. int getIndex() const;
  40918. /** Returns true if this device is currently being pressed. */
  40919. bool isDragging() const;
  40920. /** Returns the last-known screen position of this source. */
  40921. const Point<int> getScreenPosition() const;
  40922. /** Returns a set of modifiers that indicate which buttons are currently
  40923. held down on this device.
  40924. */
  40925. const ModifierKeys getCurrentModifiers() const;
  40926. /** Returns the component that was last known to be under this pointer. */
  40927. Component* getComponentUnderMouse() const;
  40928. /** Tells the device to dispatch a mouse-move event.
  40929. This is asynchronous - the event will occur on the message thread.
  40930. */
  40931. void triggerFakeMove() const;
  40932. /** Returns the number of clicks that should be counted as belonging to the
  40933. current mouse event.
  40934. So the mouse is currently down and it's the second click of a double-click, this
  40935. will return 2.
  40936. */
  40937. int getNumberOfMultipleClicks() const throw();
  40938. /** Returns the time at which the last mouse-down occurred. */
  40939. const Time getLastMouseDownTime() const throw();
  40940. /** Returns the screen position at which the last mouse-down occurred. */
  40941. const Point<int> getLastMouseDownPosition() const throw();
  40942. /** Returns true if this mouse is currently down, and if it has been dragged more
  40943. than a couple of pixels from the place it was pressed.
  40944. */
  40945. bool hasMouseMovedSignificantlySincePressed() const throw();
  40946. bool hasMouseCursor() const throw();
  40947. void showMouseCursor (const MouseCursor& cursor);
  40948. void hideCursor();
  40949. void revealCursor();
  40950. void forceMouseCursorUpdate();
  40951. bool canDoUnboundedMovement() const throw();
  40952. /** Allows the mouse to move beyond the edges of the screen.
  40953. Calling this method when the mouse button is currently pressed will remove the cursor
  40954. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  40955. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  40956. can be used for things like custom slider controls or dragging objects around, where
  40957. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  40958. The unbounded mode is automatically turned off when the mouse button is released, or
  40959. it can be turned off explicitly by calling this method again.
  40960. @param isEnabled whether to turn this mode on or off
  40961. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  40962. hidden; if true, it will only be hidden when it
  40963. is moved beyond the edge of the screen
  40964. */
  40965. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  40966. juce_UseDebuggingNewOperator
  40967. /** @internal */
  40968. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  40969. /** @internal */
  40970. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  40971. private:
  40972. friend class Desktop;
  40973. friend class ComponentPeer;
  40974. friend class MouseInputSourceInternal;
  40975. ScopedPointer<MouseInputSourceInternal> pimpl;
  40976. MouseInputSource (const MouseInputSource&);
  40977. MouseInputSource& operator= (const MouseInputSource&);
  40978. };
  40979. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  40980. /*** End of inlined file: juce_MouseInputSource.h ***/
  40981. #endif
  40982. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  40983. #endif
  40984. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  40985. #endif
  40986. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  40987. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  40988. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  40989. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  40990. /**
  40991. A PropertyComponent that contains an on/off toggle button.
  40992. This type of property component can be used if you have a boolean value to
  40993. toggle on/off.
  40994. @see PropertyComponent
  40995. */
  40996. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  40997. private ButtonListener
  40998. {
  40999. protected:
  41000. /** Creates a button component.
  41001. If you use this constructor, you must override the getState() and setState()
  41002. methods.
  41003. @param propertyName the property name to be passed to the PropertyComponent
  41004. @param buttonTextWhenTrue the text shown in the button when the value is true
  41005. @param buttonTextWhenFalse the text shown in the button when the value is false
  41006. */
  41007. BooleanPropertyComponent (const String& propertyName,
  41008. const String& buttonTextWhenTrue,
  41009. const String& buttonTextWhenFalse);
  41010. public:
  41011. /** Creates a button component.
  41012. @param valueToControl a Value object that this property should refer to.
  41013. @param propertyName the property name to be passed to the PropertyComponent
  41014. @param buttonText the text shown in the ToggleButton component
  41015. */
  41016. BooleanPropertyComponent (const Value& valueToControl,
  41017. const String& propertyName,
  41018. const String& buttonText);
  41019. /** Destructor. */
  41020. ~BooleanPropertyComponent();
  41021. /** Called to change the state of the boolean value. */
  41022. virtual void setState (bool newState);
  41023. /** Must return the current value of the property. */
  41024. virtual bool getState() const;
  41025. /** @internal */
  41026. void paint (Graphics& g);
  41027. /** @internal */
  41028. void refresh();
  41029. /** @internal */
  41030. void buttonClicked (Button*);
  41031. juce_UseDebuggingNewOperator
  41032. private:
  41033. ToggleButton* button;
  41034. String onText, offText;
  41035. void createButton();
  41036. BooleanPropertyComponent (const BooleanPropertyComponent&);
  41037. BooleanPropertyComponent& operator= (const BooleanPropertyComponent&);
  41038. };
  41039. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41040. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  41041. #endif
  41042. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41043. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  41044. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41045. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41046. /**
  41047. A PropertyComponent that contains a button.
  41048. This type of property component can be used if you need a button to trigger some
  41049. kind of action.
  41050. @see PropertyComponent
  41051. */
  41052. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  41053. private ButtonListener
  41054. {
  41055. public:
  41056. /** Creates a button component.
  41057. @param propertyName the property name to be passed to the PropertyComponent
  41058. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  41059. */
  41060. ButtonPropertyComponent (const String& propertyName,
  41061. bool triggerOnMouseDown);
  41062. /** Destructor. */
  41063. ~ButtonPropertyComponent();
  41064. /** Called when the user clicks the button.
  41065. */
  41066. virtual void buttonClicked() = 0;
  41067. /** Returns the string that should be displayed in the button.
  41068. If you need to change this string, call refresh() to update the component.
  41069. */
  41070. virtual const String getButtonText() const = 0;
  41071. /** @internal */
  41072. void refresh();
  41073. /** @internal */
  41074. void buttonClicked (Button*);
  41075. juce_UseDebuggingNewOperator
  41076. private:
  41077. TextButton* button;
  41078. ButtonPropertyComponent (const ButtonPropertyComponent&);
  41079. ButtonPropertyComponent& operator= (const ButtonPropertyComponent&);
  41080. };
  41081. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41082. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  41083. #endif
  41084. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41085. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  41086. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41087. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41088. /**
  41089. A PropertyComponent that shows its value as a combo box.
  41090. This type of property component contains a list of options and has a
  41091. combo box to choose one.
  41092. Your subclass's constructor must add some strings to the choices StringArray
  41093. and these are shown in the list.
  41094. The getIndex() method will be called to find out which option is the currently
  41095. selected one. If you call refresh() it will call getIndex() to check whether
  41096. the value has changed, and will update the combo box if needed.
  41097. If the user selects a different item from the list, setIndex() will be
  41098. called to let your class process this.
  41099. @see PropertyComponent, PropertyPanel
  41100. */
  41101. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  41102. private ComboBoxListener
  41103. {
  41104. protected:
  41105. /** Creates the component.
  41106. Your subclass's constructor must add a list of options to the choices
  41107. member variable.
  41108. */
  41109. ChoicePropertyComponent (const String& propertyName);
  41110. public:
  41111. /** Creates the component.
  41112. @param valueToControl the value that the combo box will read and control
  41113. @param propertyName the name of the property
  41114. @param choices the list of possible values that the drop-down list will contain
  41115. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  41116. These are the values that will be read and written to the
  41117. valueToControl value. This array must contain the same number of items
  41118. as the choices array
  41119. */
  41120. ChoicePropertyComponent (const Value& valueToControl,
  41121. const String& propertyName,
  41122. const StringArray& choices,
  41123. const Array <var>& correspondingValues);
  41124. /** Destructor. */
  41125. ~ChoicePropertyComponent();
  41126. /** Called when the user selects an item from the combo box.
  41127. Your subclass must use this callback to update the value that this component
  41128. represents. The index is the index of the chosen item in the choices
  41129. StringArray.
  41130. */
  41131. virtual void setIndex (int newIndex);
  41132. /** Returns the index of the item that should currently be shown.
  41133. This is the index of the item in the choices StringArray that will be
  41134. shown.
  41135. */
  41136. virtual int getIndex() const;
  41137. /** Returns the list of options. */
  41138. const StringArray& getChoices() const;
  41139. /** @internal */
  41140. void refresh();
  41141. /** @internal */
  41142. void comboBoxChanged (ComboBox*);
  41143. juce_UseDebuggingNewOperator
  41144. protected:
  41145. /** The list of options that will be shown in the combo box.
  41146. Your subclass must populate this array in its constructor. If any empty
  41147. strings are added, these will be replaced with horizontal separators (see
  41148. ComboBox::addSeparator() for more info).
  41149. */
  41150. StringArray choices;
  41151. private:
  41152. ComboBox* comboBox;
  41153. bool isCustomClass;
  41154. class RemapperValueSource;
  41155. void createComboBox();
  41156. ChoicePropertyComponent (const ChoicePropertyComponent&);
  41157. ChoicePropertyComponent& operator= (const ChoicePropertyComponent&);
  41158. };
  41159. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41160. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  41161. #endif
  41162. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  41163. #endif
  41164. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  41165. #endif
  41166. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41167. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  41168. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41169. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41170. /**
  41171. A PropertyComponent that shows its value as a slider.
  41172. @see PropertyComponent, Slider
  41173. */
  41174. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  41175. private SliderListener
  41176. {
  41177. protected:
  41178. /** Creates the property component.
  41179. The ranges, interval and skew factor are passed to the Slider component.
  41180. If you need to customise the slider in other ways, your constructor can
  41181. access the slider member variable and change it directly.
  41182. */
  41183. SliderPropertyComponent (const String& propertyName,
  41184. double rangeMin,
  41185. double rangeMax,
  41186. double interval,
  41187. double skewFactor = 1.0);
  41188. public:
  41189. /** Creates the property component.
  41190. The ranges, interval and skew factor are passed to the Slider component.
  41191. If you need to customise the slider in other ways, your constructor can
  41192. access the slider member variable and change it directly.
  41193. */
  41194. SliderPropertyComponent (const Value& valueToControl,
  41195. const String& propertyName,
  41196. double rangeMin,
  41197. double rangeMax,
  41198. double interval,
  41199. double skewFactor = 1.0);
  41200. /** Destructor. */
  41201. ~SliderPropertyComponent();
  41202. /** Called when the user moves the slider to change its value.
  41203. Your subclass must use this method to update whatever item this property
  41204. represents.
  41205. */
  41206. virtual void setValue (double newValue);
  41207. /** Returns the value that the slider should show. */
  41208. virtual double getValue() const;
  41209. /** @internal */
  41210. void refresh();
  41211. /** @internal */
  41212. void changeListenerCallback (void*);
  41213. /** @internal */
  41214. void sliderValueChanged (Slider*);
  41215. juce_UseDebuggingNewOperator
  41216. protected:
  41217. /** The slider component being used in this component.
  41218. Your subclass has access to this in case it needs to customise it in some way.
  41219. */
  41220. Slider* slider;
  41221. SliderPropertyComponent (const SliderPropertyComponent&);
  41222. SliderPropertyComponent& operator= (const SliderPropertyComponent&);
  41223. };
  41224. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41225. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  41226. #endif
  41227. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41228. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  41229. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41230. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41231. /**
  41232. A PropertyComponent that shows its value as editable text.
  41233. @see PropertyComponent
  41234. */
  41235. class JUCE_API TextPropertyComponent : public PropertyComponent
  41236. {
  41237. protected:
  41238. /** Creates a text property component.
  41239. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41240. sets whether the text editor allows carriage returns.
  41241. @see TextEditor
  41242. */
  41243. TextPropertyComponent (const String& propertyName,
  41244. int maxNumChars,
  41245. bool isMultiLine);
  41246. public:
  41247. /** Creates a text property component.
  41248. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41249. sets whether the text editor allows carriage returns.
  41250. @see TextEditor
  41251. */
  41252. TextPropertyComponent (const Value& valueToControl,
  41253. const String& propertyName,
  41254. int maxNumChars,
  41255. bool isMultiLine);
  41256. /** Destructor. */
  41257. ~TextPropertyComponent();
  41258. /** Called when the user edits the text.
  41259. Your subclass must use this callback to change the value of whatever item
  41260. this property component represents.
  41261. */
  41262. virtual void setText (const String& newText);
  41263. /** Returns the text that should be shown in the text editor.
  41264. */
  41265. virtual const String getText() const;
  41266. /** @internal */
  41267. void refresh();
  41268. /** @internal */
  41269. void textWasEdited();
  41270. juce_UseDebuggingNewOperator
  41271. private:
  41272. Label* textEditor;
  41273. void createEditor (int maxNumChars, bool isMultiLine);
  41274. TextPropertyComponent (const TextPropertyComponent&);
  41275. TextPropertyComponent& operator= (const TextPropertyComponent&);
  41276. };
  41277. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41278. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  41279. #endif
  41280. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41281. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  41282. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41283. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41284. #if JUCE_WINDOWS || DOXYGEN
  41285. /**
  41286. A Windows-specific class that can create and embed an ActiveX control inside
  41287. itself.
  41288. To use it, create one of these, put it in place and make sure it's visible in a
  41289. window, then use createControl() to instantiate an ActiveX control. The control
  41290. will then be moved and resized to follow the movements of this component.
  41291. Of course, since the control is a heavyweight window, it'll obliterate any
  41292. juce components that may overlap this component, but that's life.
  41293. */
  41294. class JUCE_API ActiveXControlComponent : public Component
  41295. {
  41296. public:
  41297. /** Create an initially-empty container. */
  41298. ActiveXControlComponent();
  41299. /** Destructor. */
  41300. ~ActiveXControlComponent();
  41301. /** Tries to create an ActiveX control and embed it in this peer.
  41302. The peer controlIID is a pointer to an IID structure - it's treated
  41303. as a void* because when including the Juce headers, you might not always
  41304. have included windows.h first, in which case IID wouldn't be defined.
  41305. e.g. @code
  41306. const IID myIID = __uuidof (QTControl);
  41307. myControlComp->createControl (&myIID);
  41308. @endcode
  41309. */
  41310. bool createControl (const void* controlIID);
  41311. /** Deletes the ActiveX control, if one has been created.
  41312. */
  41313. void deleteControl();
  41314. /** Returns true if a control is currently in use. */
  41315. bool isControlOpen() const throw() { return control != 0; }
  41316. /** Does a QueryInterface call on the embedded control object.
  41317. This allows you to cast the control to whatever type of COM object you need.
  41318. The iid parameter is a pointer to an IID structure - it's treated
  41319. as a void* because when including the Juce headers, you might not always
  41320. have included windows.h first, in which case IID wouldn't be defined, but
  41321. you should just pass a pointer to an IID.
  41322. e.g. @code
  41323. const IID iid = __uuidof (IOleWindow);
  41324. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  41325. if (oleWindow != 0)
  41326. {
  41327. HWND hwnd;
  41328. oleWindow->GetWindow (&hwnd);
  41329. ...
  41330. oleWindow->Release();
  41331. }
  41332. @endcode
  41333. */
  41334. void* queryInterface (const void* iid) const;
  41335. /** Set this to false to stop mouse events being allowed through to the control.
  41336. */
  41337. void setMouseEventsAllowed (bool eventsCanReachControl);
  41338. /** Returns true if mouse events are allowed to get through to the control.
  41339. */
  41340. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  41341. /** @internal */
  41342. void paint (Graphics& g);
  41343. /** @internal */
  41344. void* originalWndProc;
  41345. juce_UseDebuggingNewOperator
  41346. private:
  41347. class Pimpl;
  41348. friend class Pimpl;
  41349. friend class ScopedPointer <Pimpl>;
  41350. ScopedPointer <Pimpl> control;
  41351. bool mouseEventsAllowed;
  41352. void setControlBounds (const Rectangle<int>& bounds) const;
  41353. void setControlVisible (bool b) const;
  41354. ActiveXControlComponent (const ActiveXControlComponent&);
  41355. ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  41356. };
  41357. #endif
  41358. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41359. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  41360. #endif
  41361. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41362. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41363. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41364. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41365. /**
  41366. A component containing controls to let the user change the audio settings of
  41367. an AudioDeviceManager object.
  41368. Very easy to use - just create one of these and show it to the user.
  41369. @see AudioDeviceManager
  41370. */
  41371. class JUCE_API AudioDeviceSelectorComponent : public Component,
  41372. public ComboBoxListener,
  41373. public ButtonListener,
  41374. public ChangeListener
  41375. {
  41376. public:
  41377. /** Creates the component.
  41378. If your app needs only output channels, you might ask for a maximum of 0 input
  41379. channels, and the component won't display any options for choosing the input
  41380. channels. And likewise if you're doing an input-only app.
  41381. @param deviceManager the device manager that this component should control
  41382. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  41383. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  41384. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  41385. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  41386. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  41387. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  41388. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  41389. treated as a set of separate mono channels.
  41390. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  41391. are shown, with an "advanced" button that shows the rest of them
  41392. */
  41393. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  41394. const int minAudioInputChannels,
  41395. const int maxAudioInputChannels,
  41396. const int minAudioOutputChannels,
  41397. const int maxAudioOutputChannels,
  41398. const bool showMidiInputOptions,
  41399. const bool showMidiOutputSelector,
  41400. const bool showChannelsAsStereoPairs,
  41401. const bool hideAdvancedOptionsWithButton);
  41402. /** Destructor */
  41403. ~AudioDeviceSelectorComponent();
  41404. /** @internal */
  41405. void resized();
  41406. /** @internal */
  41407. void comboBoxChanged (ComboBox*);
  41408. /** @internal */
  41409. void buttonClicked (Button*);
  41410. /** @internal */
  41411. void changeListenerCallback (void*);
  41412. /** @internal */
  41413. void childBoundsChanged (Component*);
  41414. juce_UseDebuggingNewOperator
  41415. private:
  41416. AudioDeviceManager& deviceManager;
  41417. ComboBox* deviceTypeDropDown;
  41418. Label* deviceTypeDropDownLabel;
  41419. Component* audioDeviceSettingsComp;
  41420. String audioDeviceSettingsCompType;
  41421. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  41422. const bool showChannelsAsStereoPairs;
  41423. const bool hideAdvancedOptionsWithButton;
  41424. class MidiInputSelectorComponentListBox;
  41425. MidiInputSelectorComponentListBox* midiInputsList;
  41426. Label* midiInputsLabel;
  41427. ComboBox* midiOutputSelector;
  41428. Label* midiOutputLabel;
  41429. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  41430. AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  41431. };
  41432. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41433. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41434. #endif
  41435. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41436. /*** Start of inlined file: juce_BubbleComponent.h ***/
  41437. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41438. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41439. /**
  41440. A component for showing a message or other graphics inside a speech-bubble-shaped
  41441. outline, pointing at a location on the screen.
  41442. This is a base class that just draws and positions the bubble shape, but leaves
  41443. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  41444. that draws a text message.
  41445. To use it, create your subclass, then either add it to a parent component or
  41446. put it on the desktop with addToDesktop (0), use setPosition() to
  41447. resize and position it, then make it visible.
  41448. @see BubbleMessageComponent
  41449. */
  41450. class JUCE_API BubbleComponent : public Component
  41451. {
  41452. protected:
  41453. /** Creates a BubbleComponent.
  41454. Your subclass will need to implement the getContentSize() and paintContent()
  41455. methods to draw the bubble's contents.
  41456. */
  41457. BubbleComponent();
  41458. public:
  41459. /** Destructor. */
  41460. ~BubbleComponent();
  41461. /** A list of permitted placements for the bubble, relative to the co-ordinates
  41462. at which it should be pointing.
  41463. @see setAllowedPlacement
  41464. */
  41465. enum BubblePlacement
  41466. {
  41467. above = 1,
  41468. below = 2,
  41469. left = 4,
  41470. right = 8
  41471. };
  41472. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  41473. point at which it's pointing.
  41474. By default when setPosition() is called, the bubble will place itself either
  41475. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  41476. the values in BubblePlacement to restrict this choice.
  41477. E.g. if you only want your bubble to appear above or below the target area,
  41478. use setAllowedPlacement (above | below);
  41479. @see BubblePlacement
  41480. */
  41481. void setAllowedPlacement (int newPlacement);
  41482. /** Moves and resizes the bubble to point at a given component.
  41483. This will resize the bubble to fit its content, then find a position for it
  41484. so that it's next to, but doesn't overlap the given component.
  41485. It'll put itself either above, below, or to the side of the component depending
  41486. on where there's the most space, honouring any restrictions that were set
  41487. with setAllowedPlacement().
  41488. */
  41489. void setPosition (Component* componentToPointTo);
  41490. /** Moves and resizes the bubble to point at a given point.
  41491. This will resize the bubble to fit its content, then position it
  41492. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  41493. are relative to either the bubble component's parent component if it has one, or
  41494. they are screen co-ordinates if not.
  41495. It'll put itself either above, below, or to the side of this point, depending
  41496. on where there's the most space, honouring any restrictions that were set
  41497. with setAllowedPlacement().
  41498. */
  41499. void setPosition (int arrowTipX,
  41500. int arrowTipY);
  41501. /** Moves and resizes the bubble to point at a given rectangle.
  41502. This will resize the bubble to fit its content, then find a position for it
  41503. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  41504. co-ordinates are relative to either the bubble component's parent component
  41505. if it has one, or they are screen co-ordinates if not.
  41506. It'll put itself either above, below, or to the side of the component depending
  41507. on where there's the most space, honouring any restrictions that were set
  41508. with setAllowedPlacement().
  41509. */
  41510. void setPosition (const Rectangle<int>& rectangleToPointTo);
  41511. protected:
  41512. /** Subclasses should override this to return the size of the content they
  41513. want to draw inside the bubble.
  41514. */
  41515. virtual void getContentSize (int& width, int& height) = 0;
  41516. /** Subclasses should override this to draw their bubble's contents.
  41517. The graphics object's clip region and the dimensions passed in here are
  41518. set up to paint just the rectangle inside the bubble.
  41519. */
  41520. virtual void paintContent (Graphics& g, int width, int height) = 0;
  41521. public:
  41522. /** @internal */
  41523. void paint (Graphics& g);
  41524. juce_UseDebuggingNewOperator
  41525. private:
  41526. Rectangle<int> content;
  41527. int side, allowablePlacements;
  41528. float arrowTipX, arrowTipY;
  41529. DropShadowEffect shadow;
  41530. BubbleComponent (const BubbleComponent&);
  41531. BubbleComponent& operator= (const BubbleComponent&);
  41532. };
  41533. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  41534. /*** End of inlined file: juce_BubbleComponent.h ***/
  41535. #endif
  41536. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41537. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  41538. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41539. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41540. /**
  41541. A speech-bubble component that displays a short message.
  41542. This can be used to show a message with the tail of the speech bubble
  41543. pointing to a particular component or location on the screen.
  41544. @see BubbleComponent
  41545. */
  41546. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  41547. private Timer
  41548. {
  41549. public:
  41550. /** Creates a bubble component.
  41551. After creating one a BubbleComponent, do the following:
  41552. - add it to an appropriate parent component, or put it on the
  41553. desktop with Component::addToDesktop (0).
  41554. - use the showAt() method to show a message.
  41555. - it will make itself invisible after it times-out (and can optionally
  41556. also delete itself), or you can reuse it somewhere else by calling
  41557. showAt() again.
  41558. */
  41559. BubbleMessageComponent (int fadeOutLengthMs = 150);
  41560. /** Destructor. */
  41561. ~BubbleMessageComponent();
  41562. /** Shows a message bubble at a particular position.
  41563. This shows the bubble with its stem pointing to the given location
  41564. (co-ordinates being relative to its parent component).
  41565. For details about exactly how it decides where to position itself, see
  41566. BubbleComponent::updatePosition().
  41567. @param x the x co-ordinate of end of the bubble's tail
  41568. @param y the y co-ordinate of end of the bubble's tail
  41569. @param message the text to display
  41570. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  41571. from its parent compnent. If this is 0 or less, it
  41572. will stay there until manually removed.
  41573. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  41574. mouse button is pressed (anywhere on the screen)
  41575. @param deleteSelfAfterUse if true, then the component will delete itself after
  41576. it becomes invisible
  41577. */
  41578. void showAt (int x, int y,
  41579. const String& message,
  41580. int numMillisecondsBeforeRemoving,
  41581. bool removeWhenMouseClicked = true,
  41582. bool deleteSelfAfterUse = false);
  41583. /** Shows a message bubble next to a particular component.
  41584. This shows the bubble with its stem pointing at the given component.
  41585. For details about exactly how it decides where to position itself, see
  41586. BubbleComponent::updatePosition().
  41587. @param component the component that you want to point at
  41588. @param message the text to display
  41589. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  41590. from its parent compnent. If this is 0 or less, it
  41591. will stay there until manually removed.
  41592. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  41593. mouse button is pressed (anywhere on the screen)
  41594. @param deleteSelfAfterUse if true, then the component will delete itself after
  41595. it becomes invisible
  41596. */
  41597. void showAt (Component* component,
  41598. const String& message,
  41599. int numMillisecondsBeforeRemoving,
  41600. bool removeWhenMouseClicked = true,
  41601. bool deleteSelfAfterUse = false);
  41602. /** @internal */
  41603. void getContentSize (int& w, int& h);
  41604. /** @internal */
  41605. void paintContent (Graphics& g, int w, int h);
  41606. /** @internal */
  41607. void timerCallback();
  41608. juce_UseDebuggingNewOperator
  41609. private:
  41610. int fadeOutLength, mouseClickCounter;
  41611. TextLayout textLayout;
  41612. int64 expiryTime;
  41613. bool deleteAfterUse;
  41614. void init (int numMillisecondsBeforeRemoving,
  41615. bool removeWhenMouseClicked,
  41616. bool deleteSelfAfterUse);
  41617. BubbleMessageComponent (const BubbleMessageComponent&);
  41618. BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  41619. };
  41620. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  41621. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  41622. #endif
  41623. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  41624. /*** Start of inlined file: juce_ColourSelector.h ***/
  41625. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  41626. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  41627. /**
  41628. A component that lets the user choose a colour.
  41629. This shows RGB sliders and a colourspace that the user can pick colours from.
  41630. This class is also a ChangeBroadcaster, so listeners can register to be told
  41631. when the colour changes.
  41632. */
  41633. class JUCE_API ColourSelector : public Component,
  41634. public ChangeBroadcaster,
  41635. protected SliderListener
  41636. {
  41637. public:
  41638. /** Options for the type of selector to show. These are passed into the constructor. */
  41639. enum ColourSelectorOptions
  41640. {
  41641. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  41642. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  41643. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  41644. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  41645. };
  41646. /** Creates a ColourSelector object.
  41647. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  41648. which of the selector's features should be visible.
  41649. The edgeGap value specifies the amount of space to leave around the edge.
  41650. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  41651. colourspace and hue selector components.
  41652. */
  41653. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  41654. int edgeGap = 4,
  41655. int gapAroundColourSpaceComponent = 7);
  41656. /** Destructor. */
  41657. ~ColourSelector();
  41658. /** Returns the colour that the user has currently selected.
  41659. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  41660. register to be told when the colour changes.
  41661. @see setCurrentColour
  41662. */
  41663. const Colour getCurrentColour() const;
  41664. /** Changes the colour that is currently being shown.
  41665. */
  41666. void setCurrentColour (const Colour& newColour);
  41667. /** Tells the selector how many preset colour swatches you want to have on the component.
  41668. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41669. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41670. their values.
  41671. */
  41672. virtual int getNumSwatches() const;
  41673. /** Called by the selector to find out the colour of one of the swatches.
  41674. Your subclass should return the colour of the swatch with the given index.
  41675. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41676. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41677. their values.
  41678. */
  41679. virtual const Colour getSwatchColour (int index) const;
  41680. /** Called by the selector when the user puts a new colour into one of the swatches.
  41681. Your subclass should change the colour of the swatch with the given index.
  41682. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  41683. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  41684. their values.
  41685. */
  41686. virtual void setSwatchColour (int index, const Colour& newColour) const;
  41687. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  41688. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41689. methods.
  41690. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41691. */
  41692. enum ColourIds
  41693. {
  41694. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  41695. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  41696. };
  41697. juce_UseDebuggingNewOperator
  41698. private:
  41699. class ColourSpaceView;
  41700. class HueSelectorComp;
  41701. class SwatchComponent;
  41702. friend class ColourSpaceView;
  41703. friend class HueSelectorComp;
  41704. Colour colour;
  41705. float h, s, v;
  41706. Slider* sliders[4];
  41707. ColourSpaceView* colourSpace;
  41708. HueSelectorComp* hueSelector;
  41709. OwnedArray <SwatchComponent> swatchComponents;
  41710. const int flags;
  41711. int topSpace, edgeGap;
  41712. void setHue (float newH);
  41713. void setSV (float newS, float newV);
  41714. void updateHSV();
  41715. void update();
  41716. void sliderValueChanged (Slider*);
  41717. void paint (Graphics& g);
  41718. void resized();
  41719. ColourSelector (const ColourSelector&);
  41720. ColourSelector& operator= (const ColourSelector&);
  41721. // this constructor is here temporarily to prevent old code compiling, because the parameters
  41722. // have changed - if you get an error here, update your code to use the new constructor instead..
  41723. // (xxx - note to self: remember to remove this at some point in the future)
  41724. ColourSelector (bool);
  41725. };
  41726. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  41727. /*** End of inlined file: juce_ColourSelector.h ***/
  41728. #endif
  41729. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  41730. #endif
  41731. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41732. /*** Start of inlined file: juce_MagnifierComponent.h ***/
  41733. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41734. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41735. /**
  41736. A component that contains another component, and can magnify or shrink it.
  41737. This component will continually update its size so that it fits the zoomed
  41738. version of the content component that you put inside it, so don't try to
  41739. change the size of this component directly - instead change that of the
  41740. content component.
  41741. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  41742. to remap mouse events correctly. This means that the content component won't
  41743. appear to be a direct child of this component, and instead will think its
  41744. on the desktop.
  41745. */
  41746. class JUCE_API MagnifierComponent : public Component
  41747. {
  41748. public:
  41749. /** Creates a MagnifierComponent.
  41750. This component will continually update its size so that it fits the zoomed
  41751. version of the content component that you put inside it, so don't try to
  41752. change the size of this component directly - instead change that of the
  41753. content component.
  41754. @param contentComponent the component to add as the magnified one
  41755. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  41756. be deleted when this component is deleted. If false,
  41757. it's the caller's responsibility to delete it later.
  41758. */
  41759. MagnifierComponent (Component* contentComponent,
  41760. bool deleteContentCompWhenNoLongerNeeded);
  41761. /** Destructor. */
  41762. ~MagnifierComponent();
  41763. /** Returns the current content component. */
  41764. Component* getContentComponent() const { return content; }
  41765. /** Changes the zoom level.
  41766. The scale factor must be greater than zero. Values less than 1 will shrink the
  41767. image; values greater than 1 will multiply its size by this amount.
  41768. When this is called, this component will change its size to fit the full extent
  41769. of the newly zoomed content.
  41770. */
  41771. void setScaleFactor (double newScaleFactor);
  41772. /** Returns the current zoom factor. */
  41773. double getScaleFactor() const { return scaleFactor; }
  41774. /** Changes the quality setting used to rescale the graphics.
  41775. */
  41776. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  41777. juce_UseDebuggingNewOperator
  41778. /** @internal */
  41779. void childBoundsChanged (Component*);
  41780. private:
  41781. Component* content;
  41782. Component* holderComp;
  41783. double scaleFactor;
  41784. ComponentPeer* peer;
  41785. bool deleteContent;
  41786. Graphics::ResamplingQuality quality;
  41787. MouseInputSource mouseSource;
  41788. void paint (Graphics& g);
  41789. void mouseDown (const MouseEvent& e);
  41790. void mouseUp (const MouseEvent& e);
  41791. void mouseDrag (const MouseEvent& e);
  41792. void mouseMove (const MouseEvent& e);
  41793. void mouseEnter (const MouseEvent& e);
  41794. void mouseExit (const MouseEvent& e);
  41795. void mouseWheelMove (const MouseEvent& e, float, float);
  41796. void passOnMouseEventToPeer (const MouseEvent& e);
  41797. int scaleInt (int n) const;
  41798. MagnifierComponent (const MagnifierComponent&);
  41799. MagnifierComponent& operator= (const MagnifierComponent&);
  41800. };
  41801. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  41802. /*** End of inlined file: juce_MagnifierComponent.h ***/
  41803. #endif
  41804. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  41805. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  41806. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  41807. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  41808. /**
  41809. A component that displays a piano keyboard, whose notes can be clicked on.
  41810. This component will mimic a physical midi keyboard, showing the current state of
  41811. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  41812. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  41813. Another feature is that the computer keyboard can also be used to play notes. By
  41814. default it maps the top two rows of a standard querty keyboard to the notes, but
  41815. these can be remapped if needed. It will only respond to keypresses when it has
  41816. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  41817. The component is also a ChangeBroadcaster, so if you want to be informed when the
  41818. keyboard is scrolled, you can register a ChangeListener for callbacks.
  41819. @see MidiKeyboardState
  41820. */
  41821. class JUCE_API MidiKeyboardComponent : public Component,
  41822. public MidiKeyboardStateListener,
  41823. public ChangeBroadcaster,
  41824. private Timer,
  41825. private AsyncUpdater
  41826. {
  41827. public:
  41828. /** The direction of the keyboard.
  41829. @see setOrientation
  41830. */
  41831. enum Orientation
  41832. {
  41833. horizontalKeyboard,
  41834. verticalKeyboardFacingLeft,
  41835. verticalKeyboardFacingRight,
  41836. };
  41837. /** Creates a MidiKeyboardComponent.
  41838. @param state the midi keyboard model that this component will represent
  41839. @param orientation whether the keyboard is horizonal or vertical
  41840. */
  41841. MidiKeyboardComponent (MidiKeyboardState& state,
  41842. Orientation orientation);
  41843. /** Destructor. */
  41844. ~MidiKeyboardComponent();
  41845. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  41846. on the component.
  41847. Values are 0 to 1.0, where 1.0 is the heaviest.
  41848. @see setMidiChannel
  41849. */
  41850. void setVelocity (float velocity, bool useMousePositionForVelocity);
  41851. /** Changes the midi channel number that will be used for events triggered by clicking
  41852. on the component.
  41853. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  41854. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  41855. Although this is the channel used for outgoing events, the component can display
  41856. incoming events from more than one channel - see setMidiChannelsToDisplay()
  41857. @see setVelocity
  41858. */
  41859. void setMidiChannel (int midiChannelNumber);
  41860. /** Returns the midi channel that the keyboard is using for midi messages.
  41861. @see setMidiChannel
  41862. */
  41863. int getMidiChannel() const throw() { return midiChannel; }
  41864. /** Sets a mask to indicate which incoming midi channels should be represented by
  41865. key movements.
  41866. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  41867. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  41868. in this mask, the on-screen keys will also go down.
  41869. By default, this mask is set to 0xffff (all channels displayed).
  41870. @see setMidiChannel
  41871. */
  41872. void setMidiChannelsToDisplay (int midiChannelMask);
  41873. /** Returns the current set of midi channels represented by the component.
  41874. This is the value that was set with setMidiChannelsToDisplay().
  41875. */
  41876. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  41877. /** Changes the width used to draw the white keys. */
  41878. void setKeyWidth (float widthInPixels);
  41879. /** Returns the width that was set by setKeyWidth(). */
  41880. float getKeyWidth() const throw() { return keyWidth; }
  41881. /** Changes the keyboard's current direction. */
  41882. void setOrientation (Orientation newOrientation);
  41883. /** Returns the keyboard's current direction. */
  41884. const Orientation getOrientation() const throw() { return orientation; }
  41885. /** Sets the range of midi notes that the keyboard will be limited to.
  41886. By default the range is 0 to 127 (inclusive), but you can limit this if you
  41887. only want a restricted set of the keys to be shown.
  41888. Note that the values here are inclusive and must be between 0 and 127.
  41889. */
  41890. void setAvailableRange (int lowestNote,
  41891. int highestNote);
  41892. /** Returns the first note in the available range.
  41893. @see setAvailableRange
  41894. */
  41895. int getRangeStart() const throw() { return rangeStart; }
  41896. /** Returns the last note in the available range.
  41897. @see setAvailableRange
  41898. */
  41899. int getRangeEnd() const throw() { return rangeEnd; }
  41900. /** If the keyboard extends beyond the size of the component, this will scroll
  41901. it to show the given key at the start.
  41902. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  41903. base class to send a callback to any ChangeListeners that have been registered.
  41904. */
  41905. void setLowestVisibleKey (int noteNumber);
  41906. /** Returns the number of the first key shown in the component.
  41907. @see setLowestVisibleKey
  41908. */
  41909. int getLowestVisibleKey() const throw() { return firstKey; }
  41910. /** Returns the length of the black notes.
  41911. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  41912. */
  41913. int getBlackNoteLength() const throw() { return blackNoteLength; }
  41914. /** If set to true, then scroll buttons will appear at either end of the keyboard
  41915. if there are too many notes to fit them all in the component at once.
  41916. */
  41917. void setScrollButtonsVisible (bool canScroll);
  41918. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  41919. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41920. methods.
  41921. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41922. */
  41923. enum ColourIds
  41924. {
  41925. whiteNoteColourId = 0x1005000,
  41926. blackNoteColourId = 0x1005001,
  41927. keySeparatorLineColourId = 0x1005002,
  41928. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  41929. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  41930. textLabelColourId = 0x1005005,
  41931. upDownButtonBackgroundColourId = 0x1005006,
  41932. upDownButtonArrowColourId = 0x1005007
  41933. };
  41934. /** Returns the position within the component of the left-hand edge of a key.
  41935. Depending on the keyboard's orientation, this may be a horizontal or vertical
  41936. distance, in either direction.
  41937. */
  41938. int getKeyStartPosition (const int midiNoteNumber) const;
  41939. /** Deletes all key-mappings.
  41940. @see setKeyPressForNote
  41941. */
  41942. void clearKeyMappings();
  41943. /** Maps a key-press to a given note.
  41944. @param key the key that should trigger the note
  41945. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  41946. be. The actual midi note that gets played will be
  41947. this value + (12 * the current base octave). To change
  41948. the base octave, see setKeyPressBaseOctave()
  41949. */
  41950. void setKeyPressForNote (const KeyPress& key,
  41951. int midiNoteOffsetFromC);
  41952. /** Removes any key-mappings for a given note.
  41953. For a description of what the note number means, see setKeyPressForNote().
  41954. */
  41955. void removeKeyPressForNote (int midiNoteOffsetFromC);
  41956. /** Changes the base note above which key-press-triggered notes are played.
  41957. The set of key-mappings that trigger notes can be moved up and down to cover
  41958. the entire scale using this method.
  41959. The value passed in is an octave number between 0 and 10 (inclusive), and
  41960. indicates which C is the base note to which the key-mapped notes are
  41961. relative.
  41962. */
  41963. void setKeyPressBaseOctave (int newOctaveNumber);
  41964. /** This sets the octave number which is shown as the octave number for middle C.
  41965. This affects only the default implementation of getWhiteNoteText(), which
  41966. passes this octave number to MidiMessage::getMidiNoteName() in order to
  41967. get the note text. See MidiMessage::getMidiNoteName() for more info about
  41968. the parameter.
  41969. By default this value is set to 3.
  41970. @see getOctaveForMiddleC
  41971. */
  41972. void setOctaveForMiddleC (int octaveNumForMiddleC);
  41973. /** This returns the value set by setOctaveForMiddleC().
  41974. @see setOctaveForMiddleC
  41975. */
  41976. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  41977. /** @internal */
  41978. void paint (Graphics& g);
  41979. /** @internal */
  41980. void resized();
  41981. /** @internal */
  41982. void mouseMove (const MouseEvent& e);
  41983. /** @internal */
  41984. void mouseDrag (const MouseEvent& e);
  41985. /** @internal */
  41986. void mouseDown (const MouseEvent& e);
  41987. /** @internal */
  41988. void mouseUp (const MouseEvent& e);
  41989. /** @internal */
  41990. void mouseEnter (const MouseEvent& e);
  41991. /** @internal */
  41992. void mouseExit (const MouseEvent& e);
  41993. /** @internal */
  41994. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  41995. /** @internal */
  41996. void timerCallback();
  41997. /** @internal */
  41998. bool keyStateChanged (bool isKeyDown);
  41999. /** @internal */
  42000. void focusLost (FocusChangeType cause);
  42001. /** @internal */
  42002. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  42003. /** @internal */
  42004. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  42005. /** @internal */
  42006. void handleAsyncUpdate();
  42007. /** @internal */
  42008. void colourChanged();
  42009. juce_UseDebuggingNewOperator
  42010. protected:
  42011. friend class MidiKeyboardUpDownButton;
  42012. /** Draws a white note in the given rectangle.
  42013. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42014. currently pressed down.
  42015. When doing this, be sure to note the keyboard's orientation.
  42016. */
  42017. virtual void drawWhiteNote (int midiNoteNumber,
  42018. Graphics& g,
  42019. int x, int y, int w, int h,
  42020. bool isDown, bool isOver,
  42021. const Colour& lineColour,
  42022. const Colour& textColour);
  42023. /** Draws a black note in the given rectangle.
  42024. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42025. currently pressed down.
  42026. When doing this, be sure to note the keyboard's orientation.
  42027. */
  42028. virtual void drawBlackNote (int midiNoteNumber,
  42029. Graphics& g,
  42030. int x, int y, int w, int h,
  42031. bool isDown, bool isOver,
  42032. const Colour& noteFillColour);
  42033. /** Allows text to be drawn on the white notes.
  42034. By default this is used to label the C in each octave, but could be used for other things.
  42035. @see setOctaveForMiddleC
  42036. */
  42037. virtual const String getWhiteNoteText (const int midiNoteNumber);
  42038. /** Draws the up and down buttons that change the base note. */
  42039. virtual void drawUpDownButton (Graphics& g, int w, int h,
  42040. const bool isMouseOver,
  42041. const bool isButtonPressed,
  42042. const bool movesOctavesUp);
  42043. /** Callback when the mouse is clicked on a key.
  42044. You could use this to do things like handle right-clicks on keys, etc.
  42045. Return true if you want the click to trigger the note, or false if you
  42046. want to handle it yourself and not have the note played.
  42047. @see mouseDraggedToKey
  42048. */
  42049. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  42050. /** Callback when the mouse is dragged from one key onto another.
  42051. @see mouseDownOnKey
  42052. */
  42053. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  42054. /** Calculates the positon of a given midi-note.
  42055. This can be overridden to create layouts with custom key-widths.
  42056. @param midiNoteNumber the note to find
  42057. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  42058. @param x the x position of the left-hand edge of the key (this method
  42059. always works in terms of a horizontal keyboard)
  42060. @param w the width of the key
  42061. */
  42062. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  42063. int& x, int& w) const;
  42064. private:
  42065. MidiKeyboardState& state;
  42066. int xOffset, blackNoteLength;
  42067. float keyWidth;
  42068. Orientation orientation;
  42069. int midiChannel, midiInChannelMask;
  42070. float velocity;
  42071. int noteUnderMouse, mouseDownNote;
  42072. BigInteger keysPressed, keysCurrentlyDrawnDown;
  42073. int rangeStart, rangeEnd, firstKey;
  42074. bool canScroll, mouseDragging, useMousePositionForVelocity;
  42075. Button* scrollDown;
  42076. Button* scrollUp;
  42077. Array <KeyPress> keyPresses;
  42078. Array <int> keyPressNotes;
  42079. int keyMappingOctave;
  42080. int octaveNumForMiddleC;
  42081. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  42082. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  42083. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  42084. void resetAnyKeysInUse();
  42085. void updateNoteUnderMouse (const Point<int>& pos);
  42086. void repaintNote (const int midiNoteNumber);
  42087. MidiKeyboardComponent (const MidiKeyboardComponent&);
  42088. MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  42089. };
  42090. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42091. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  42092. #endif
  42093. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42094. /*** Start of inlined file: juce_NSViewComponent.h ***/
  42095. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42096. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42097. #if ! DOXYGEN
  42098. class NSViewComponentInternal;
  42099. #endif
  42100. #if JUCE_MAC || DOXYGEN
  42101. /**
  42102. A Mac-specific class that can create and embed an NSView inside itself.
  42103. To use it, create one of these, put it in place and make sure it's visible in a
  42104. window, then use setView() to assign an NSView to it. The view will then be
  42105. moved and resized to follow the movements of this component.
  42106. Of course, since the view is a native object, it'll obliterate any
  42107. juce components that may overlap this component, but that's life.
  42108. */
  42109. class JUCE_API NSViewComponent : public Component
  42110. {
  42111. public:
  42112. /** Create an initially-empty container. */
  42113. NSViewComponent();
  42114. /** Destructor. */
  42115. ~NSViewComponent();
  42116. /** Assigns an NSView to this peer.
  42117. The view will be retained and released by this component for as long as
  42118. it is needed. To remove the current view, just call setView (0).
  42119. Note: a void* is used here to avoid including the cocoa headers as
  42120. part of the juce.h, but the method expects an NSView*.
  42121. */
  42122. void setView (void* nsView);
  42123. /** Returns the current NSView.
  42124. Note: a void* is returned here to avoid including the cocoa headers as
  42125. a requirement of juce.h, so you should just cast the object to an NSView*.
  42126. */
  42127. void* getView() const;
  42128. /** @internal */
  42129. void paint (Graphics& g);
  42130. juce_UseDebuggingNewOperator
  42131. private:
  42132. friend class NSViewComponentInternal;
  42133. ScopedPointer <NSViewComponentInternal> info;
  42134. NSViewComponent (const NSViewComponent&);
  42135. NSViewComponent& operator= (const NSViewComponent&);
  42136. };
  42137. #endif
  42138. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42139. /*** End of inlined file: juce_NSViewComponent.h ***/
  42140. #endif
  42141. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42142. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  42143. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42144. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42145. // this is used to disable OpenGL, and is defined in juce_Config.h
  42146. #if JUCE_OPENGL || DOXYGEN
  42147. /**
  42148. Represents the various properties of an OpenGL bitmap format.
  42149. @see OpenGLComponent::setPixelFormat
  42150. */
  42151. class JUCE_API OpenGLPixelFormat
  42152. {
  42153. public:
  42154. /** Creates an OpenGLPixelFormat.
  42155. The default constructor just initialises the object as a simple 8-bit
  42156. RGBA format.
  42157. */
  42158. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  42159. int alphaBits = 8,
  42160. int depthBufferBits = 16,
  42161. int stencilBufferBits = 0);
  42162. OpenGLPixelFormat (const OpenGLPixelFormat&);
  42163. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  42164. bool operator== (const OpenGLPixelFormat&) const;
  42165. int redBits; /**< The number of bits per pixel to use for the red channel. */
  42166. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  42167. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  42168. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  42169. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  42170. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  42171. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  42172. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  42173. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  42174. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  42175. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  42176. /** Returns a list of all the pixel formats that can be used in this system.
  42177. A reference component is needed in case there are multiple screens with different
  42178. capabilities - in which case, the one that the component is on will be used.
  42179. */
  42180. static void getAvailablePixelFormats (Component* component,
  42181. OwnedArray <OpenGLPixelFormat>& results);
  42182. juce_UseDebuggingNewOperator
  42183. };
  42184. /**
  42185. A base class for types of OpenGL context.
  42186. An OpenGLComponent will supply its own context for drawing in its window.
  42187. */
  42188. class JUCE_API OpenGLContext
  42189. {
  42190. public:
  42191. /** Destructor. */
  42192. virtual ~OpenGLContext();
  42193. /** Makes this context the currently active one. */
  42194. virtual bool makeActive() const throw() = 0;
  42195. /** If this context is currently active, it is disactivated. */
  42196. virtual bool makeInactive() const throw() = 0;
  42197. /** Returns true if this context is currently active. */
  42198. virtual bool isActive() const throw() = 0;
  42199. /** Swaps the buffers (if the context can do this). */
  42200. virtual void swapBuffers() = 0;
  42201. /** Sets whether the context checks the vertical sync before swapping.
  42202. The value is the number of frames to allow between buffer-swapping. This is
  42203. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  42204. and greater numbers indicate that it should swap less often.
  42205. Returns true if it sets the value successfully.
  42206. */
  42207. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  42208. /** Returns the current swap-sync interval.
  42209. See setSwapInterval() for info about the value returned.
  42210. */
  42211. virtual int getSwapInterval() const = 0;
  42212. /** Returns the pixel format being used by this context. */
  42213. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  42214. /** For windowed contexts, this moves the context within the bounds of
  42215. its parent window.
  42216. */
  42217. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  42218. /** For windowed contexts, this triggers a repaint of the window.
  42219. (Not relevent on all platforms).
  42220. */
  42221. virtual void repaint() = 0;
  42222. /** Returns an OS-dependent handle to the raw GL context.
  42223. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  42224. a GLXContext.
  42225. */
  42226. virtual void* getRawContext() const throw() = 0;
  42227. /** Returns the context that's currently in active use by the calling thread.
  42228. Returns 0 if there isn't an active context.
  42229. */
  42230. static OpenGLContext* getCurrentContext();
  42231. juce_UseDebuggingNewOperator
  42232. protected:
  42233. OpenGLContext() throw();
  42234. };
  42235. /**
  42236. A component that contains an OpenGL canvas.
  42237. Override this, add it to whatever component you want to, and use the renderOpenGL()
  42238. method to draw its contents.
  42239. */
  42240. class JUCE_API OpenGLComponent : public Component
  42241. {
  42242. public:
  42243. /** Used to select the type of openGL API to use, if more than one choice is available
  42244. on a particular platform.
  42245. */
  42246. enum OpenGLType
  42247. {
  42248. openGLDefault = 0,
  42249. #if JUCE_IPHONE
  42250. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  42251. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  42252. #endif
  42253. };
  42254. /** Creates an OpenGLComponent. */
  42255. OpenGLComponent (OpenGLType type = openGLDefault);
  42256. /** Destructor. */
  42257. ~OpenGLComponent();
  42258. /** Changes the pixel format used by this component.
  42259. @see OpenGLPixelFormat::getAvailablePixelFormats()
  42260. */
  42261. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  42262. /** Returns the pixel format that this component is currently using. */
  42263. const OpenGLPixelFormat getPixelFormat() const;
  42264. /** Specifies an OpenGL context which should be shared with the one that this
  42265. component is using.
  42266. This is an OpenGL feature that lets two contexts share their texture data.
  42267. Note that this pointer is stored by the component, and when the component
  42268. needs to recreate its internal context for some reason, the same context
  42269. will be used again to share lists. So if you pass a context in here,
  42270. don't delete the context while this component is still using it! You can
  42271. call shareWith (0) to stop this component from sharing with it.
  42272. */
  42273. void shareWith (OpenGLContext* contextToShareListsWith);
  42274. /** Returns the context that this component is sharing with.
  42275. @see shareWith
  42276. */
  42277. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  42278. /** Flips the openGL buffers over. */
  42279. void swapBuffers();
  42280. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  42281. When this is called, makeCurrentContextActive() will already have been called
  42282. for you, so you just need to draw.
  42283. */
  42284. virtual void renderOpenGL() = 0;
  42285. /** This method is called when the component creates a new OpenGL context.
  42286. A new context may be created when the component is first used, or when it
  42287. is moved to a different window, or when the window is hidden and re-shown,
  42288. etc.
  42289. You can use this callback as an opportunity to set up things like textures
  42290. that your context needs.
  42291. New contexts are created on-demand by the makeCurrentContextActive() method - so
  42292. if the context is deleted, e.g. by changing the pixel format or window, no context
  42293. will be created until the next call to makeCurrentContextActive(), which will
  42294. synchronously create one and call this method. This means that if you're using
  42295. a non-GUI thread for rendering, you can make sure this method is be called by
  42296. your renderer thread.
  42297. When this callback happens, the context will already have been made current
  42298. using the makeCurrentContextActive() method, so there's no need to call it
  42299. again in your code.
  42300. */
  42301. virtual void newOpenGLContextCreated() = 0;
  42302. /** Returns the context that will draw into this component.
  42303. This may return 0 if the component is currently invisible or hasn't currently
  42304. got a context. The context object can be deleted and a new one created during
  42305. the lifetime of this component, and there may be times when it doesn't have one.
  42306. @see newOpenGLContextCreated()
  42307. */
  42308. OpenGLContext* getCurrentContext() const throw() { return context; }
  42309. /** Makes this component the current openGL context.
  42310. You might want to use this in things like your resize() method, before calling
  42311. GL commands.
  42312. If this returns false, then the context isn't active, so you should avoid
  42313. making any calls.
  42314. This call may actually create a context if one isn't currently initialised. If
  42315. it does this, it will also synchronously call the newOpenGLContextCreated()
  42316. method to let you initialise it as necessary.
  42317. @see OpenGLContext::makeActive
  42318. */
  42319. bool makeCurrentContextActive();
  42320. /** Stops the current component being the active OpenGL context.
  42321. This is the opposite of makeCurrentContextActive()
  42322. @see OpenGLContext::makeInactive
  42323. */
  42324. void makeCurrentContextInactive();
  42325. /** Returns true if this component is the active openGL context for the
  42326. current thread.
  42327. @see OpenGLContext::isActive
  42328. */
  42329. bool isActiveContext() const throw();
  42330. /** Calls the rendering callback, and swaps the buffers afterwards.
  42331. This is called automatically by paint() when the component needs to be rendered.
  42332. It can be overridden if you need to decouple the rendering from the paint callback
  42333. and render with a custom thread.
  42334. Returns true if the operation succeeded.
  42335. */
  42336. virtual bool renderAndSwapBuffers();
  42337. /** This returns a critical section that can be used to lock the current context.
  42338. Because the context that is used by this component can change, e.g. when the
  42339. component is shown or hidden, then if you're rendering to it on a background
  42340. thread, this allows you to lock the context for the duration of your rendering
  42341. routine.
  42342. */
  42343. CriticalSection& getContextLock() throw() { return contextLock; }
  42344. /** @internal */
  42345. void paint (Graphics& g);
  42346. /** Returns the native handle of an embedded heavyweight window, if there is one.
  42347. E.g. On windows, this will return the HWND of the sub-window containing
  42348. the opengl context, on the mac it'll be the NSOpenGLView.
  42349. */
  42350. void* getNativeWindowHandle() const;
  42351. juce_UseDebuggingNewOperator
  42352. private:
  42353. const OpenGLType type;
  42354. class OpenGLComponentWatcher;
  42355. friend class OpenGLComponentWatcher;
  42356. friend class ScopedPointer <OpenGLComponentWatcher>;
  42357. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  42358. ScopedPointer <OpenGLContext> context;
  42359. OpenGLContext* contextToShareListsWith;
  42360. CriticalSection contextLock;
  42361. OpenGLPixelFormat preferredPixelFormat;
  42362. bool needToUpdateViewport;
  42363. OpenGLContext* createContext();
  42364. void deleteContext();
  42365. void updateContextPosition();
  42366. void internalRepaint (int x, int y, int w, int h);
  42367. OpenGLComponent (const OpenGLComponent&);
  42368. OpenGLComponent& operator= (const OpenGLComponent&);
  42369. };
  42370. #endif
  42371. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42372. /*** End of inlined file: juce_OpenGLComponent.h ***/
  42373. #endif
  42374. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42375. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  42376. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42377. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42378. /**
  42379. A component with a set of buttons at the top for changing between pages of
  42380. preferences.
  42381. This is just a handy way of writing a Mac-style preferences panel where you
  42382. have a row of buttons along the top for the different preference categories,
  42383. each button having an icon above its name. Clicking these will show an
  42384. appropriate prefs page below it.
  42385. You can either put one of these inside your own component, or just use the
  42386. showInDialogBox() method to show it in a window and run it modally.
  42387. To use it, just add a set of named pages with the addSettingsPage() method,
  42388. and implement the createComponentForPage() method to create suitable components
  42389. for each of these pages.
  42390. */
  42391. class JUCE_API PreferencesPanel : public Component,
  42392. private ButtonListener
  42393. {
  42394. public:
  42395. /** Creates an empty panel.
  42396. Use addSettingsPage() to add some pages to it in your constructor.
  42397. */
  42398. PreferencesPanel();
  42399. /** Destructor. */
  42400. ~PreferencesPanel();
  42401. /** Creates a page using a set of drawables to define the page's icon.
  42402. Note that the other version of this method is much easier if you're using
  42403. an image instead of a custom drawable.
  42404. @param pageTitle the name of this preferences page - you'll need to
  42405. make sure your createComponentForPage() method creates
  42406. a suitable component when it is passed this name
  42407. @param normalIcon the drawable to display in the page's button normally
  42408. @param overIcon the drawable to display in the page's button when the mouse is over
  42409. @param downIcon the drawable to display in the page's button when the button is down
  42410. @see DrawableButton
  42411. */
  42412. void addSettingsPage (const String& pageTitle,
  42413. const Drawable* normalIcon,
  42414. const Drawable* overIcon,
  42415. const Drawable* downIcon);
  42416. /** Creates a page using a set of drawables to define the page's icon.
  42417. The other version of this method gives you more control over the icon, but this
  42418. one is much easier if you're just loading it from a file.
  42419. @param pageTitle the name of this preferences page - you'll need to
  42420. make sure your createComponentForPage() method creates
  42421. a suitable component when it is passed this name
  42422. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  42423. For this to look good, you'll probably want to use a nice
  42424. transparent png file.
  42425. @param imageDataSize the size of the image data, in bytes
  42426. */
  42427. void addSettingsPage (const String& pageTitle,
  42428. const char* imageData,
  42429. int imageDataSize);
  42430. /** Utility method to display this panel in a DialogWindow.
  42431. Calling this will create a DialogWindow containing this panel with the
  42432. given size and title, and will run it modally, returning when the user
  42433. closes the dialog box.
  42434. */
  42435. void showInDialogBox (const String& dialogtitle,
  42436. int dialogWidth,
  42437. int dialogHeight,
  42438. const Colour& backgroundColour = Colours::white);
  42439. /** Subclasses must override this to return a component for each preferences page.
  42440. The subclass should return a pointer to a new component representing the named
  42441. page, which the panel will then display.
  42442. The panel will delete the component later when the user goes to another page
  42443. or deletes the panel.
  42444. */
  42445. virtual Component* createComponentForPage (const String& pageName) = 0;
  42446. /** Changes the current page being displayed. */
  42447. void setCurrentPage (const String& pageName);
  42448. /** @internal */
  42449. void resized();
  42450. /** @internal */
  42451. void paint (Graphics& g);
  42452. /** @internal */
  42453. void buttonClicked (Button* button);
  42454. juce_UseDebuggingNewOperator
  42455. private:
  42456. String currentPageName;
  42457. ScopedPointer <Component> currentPage;
  42458. int buttonSize;
  42459. PreferencesPanel (const PreferencesPanel&);
  42460. PreferencesPanel& operator= (const PreferencesPanel&);
  42461. };
  42462. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42463. /*** End of inlined file: juce_PreferencesPanel.h ***/
  42464. #endif
  42465. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42466. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  42467. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42468. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42469. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  42470. // amalgamated build)
  42471. #if JUCE_WINDOWS
  42472. typedef ActiveXControlComponent QTCompBaseClass;
  42473. #elif JUCE_MAC
  42474. typedef NSViewComponent QTCompBaseClass;
  42475. #endif
  42476. // this is used to disable QuickTime, and is defined in juce_Config.h
  42477. #if JUCE_QUICKTIME || DOXYGEN
  42478. /**
  42479. A window that can play back a QuickTime movie.
  42480. */
  42481. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  42482. {
  42483. public:
  42484. /** Creates a QuickTimeMovieComponent, initially blank.
  42485. Use the loadMovie() method to load a movie once you've added the
  42486. component to a window, (or put it on the desktop as a heavyweight window).
  42487. Loading a movie when the component isn't visible can cause problems, as
  42488. QuickTime needs a window handle to initialise properly.
  42489. */
  42490. QuickTimeMovieComponent();
  42491. /** Destructor. */
  42492. ~QuickTimeMovieComponent();
  42493. /** Returns true if QT is installed and working on this machine.
  42494. */
  42495. static bool isQuickTimeAvailable() throw();
  42496. /** Tries to load a QuickTime movie from a file into the player.
  42497. It's best to call this function once you've added the component to a window,
  42498. (or put it on the desktop as a heavyweight window). Loading a movie when the
  42499. component isn't visible can cause problems, because QuickTime needs a window
  42500. handle to do its stuff.
  42501. @param movieFile the .mov file to open
  42502. @param isControllerVisible whether to show a controller bar at the bottom
  42503. @returns true if the movie opens successfully
  42504. */
  42505. bool loadMovie (const File& movieFile,
  42506. bool isControllerVisible);
  42507. /** Tries to load a QuickTime movie from a URL into the player.
  42508. It's best to call this function once you've added the component to a window,
  42509. (or put it on the desktop as a heavyweight window). Loading a movie when the
  42510. component isn't visible can cause problems, because QuickTime needs a window
  42511. handle to do its stuff.
  42512. @param movieURL the .mov file to open
  42513. @param isControllerVisible whether to show a controller bar at the bottom
  42514. @returns true if the movie opens successfully
  42515. */
  42516. bool loadMovie (const URL& movieURL,
  42517. bool isControllerVisible);
  42518. /** Tries to load a QuickTime movie from a stream into the player.
  42519. It's best to call this function once you've added the component to a window,
  42520. (or put it on the desktop as a heavyweight window). Loading a movie when the
  42521. component isn't visible can cause problems, because QuickTime needs a window
  42522. handle to do its stuff.
  42523. @param movieStream a stream containing a .mov file. The component may try
  42524. to read the whole stream before playing, rather than
  42525. streaming from it.
  42526. @param isControllerVisible whether to show a controller bar at the bottom
  42527. @returns true if the movie opens successfully
  42528. */
  42529. bool loadMovie (InputStream* movieStream,
  42530. bool isControllerVisible);
  42531. /** Closes the movie, if one is open. */
  42532. void closeMovie();
  42533. /** Returns the movie file that is currently open.
  42534. If there isn't one, this returns File::nonexistent
  42535. */
  42536. const File getCurrentMovieFile() const;
  42537. /** Returns true if there's currently a movie open. */
  42538. bool isMovieOpen() const;
  42539. /** Returns the length of the movie, in seconds. */
  42540. double getMovieDuration() const;
  42541. /** Returns the movie's natural size, in pixels.
  42542. You can use this to resize the component to show the movie at its preferred
  42543. scale.
  42544. If no movie is loaded, the size returned will be 0 x 0.
  42545. */
  42546. void getMovieNormalSize (int& width, int& height) const;
  42547. /** This will position the component within a given area, keeping its aspect
  42548. ratio correct according to the movie's normal size.
  42549. The component will be made as large as it can go within the space, and will
  42550. be aligned according to the justification value if this means there are gaps at
  42551. the top or sides.
  42552. */
  42553. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  42554. const RectanglePlacement& placement);
  42555. /** Starts the movie playing. */
  42556. void play();
  42557. /** Stops the movie playing. */
  42558. void stop();
  42559. /** Returns true if the movie is currently playing. */
  42560. bool isPlaying() const;
  42561. /** Moves the movie's position back to the start. */
  42562. void goToStart();
  42563. /** Sets the movie's position to a given time. */
  42564. void setPosition (double seconds);
  42565. /** Returns the current play position of the movie. */
  42566. double getPosition() const;
  42567. /** Changes the movie playback rate.
  42568. A value of 1 is normal speed, greater values play it proportionately faster,
  42569. smaller values play it slower.
  42570. */
  42571. void setSpeed (float newSpeed);
  42572. /** Changes the movie's playback volume.
  42573. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  42574. */
  42575. void setMovieVolume (float newVolume);
  42576. /** Returns the movie's playback volume.
  42577. @returns the volume in the range 0 (silent) to 1.0 (full)
  42578. */
  42579. float getMovieVolume() const;
  42580. /** Tells the movie whether it should loop. */
  42581. void setLooping (bool shouldLoop);
  42582. /** Returns true if the movie is currently looping.
  42583. @see setLooping
  42584. */
  42585. bool isLooping() const;
  42586. /** True if the native QuickTime controller bar is shown in the window.
  42587. @see loadMovie
  42588. */
  42589. bool isControllerVisible() const;
  42590. /** @internal */
  42591. void paint (Graphics& g);
  42592. juce_UseDebuggingNewOperator
  42593. private:
  42594. File movieFile;
  42595. bool movieLoaded, controllerVisible, looping;
  42596. #if JUCE_WINDOWS
  42597. void parentHierarchyChanged();
  42598. void visibilityChanged();
  42599. void createControlIfNeeded();
  42600. bool isControlCreated() const;
  42601. class Pimpl;
  42602. friend class ScopedPointer <Pimpl>;
  42603. ScopedPointer <Pimpl> pimpl;
  42604. #else
  42605. void* movie;
  42606. #endif
  42607. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  42608. QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  42609. };
  42610. #endif
  42611. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  42612. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  42613. #endif
  42614. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42615. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  42616. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42617. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42618. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  42619. /**
  42620. On Windows only, this component sits in the taskbar tray as a small icon.
  42621. To use it, just create one of these components, but don't attempt to make it
  42622. visible, add it to a parent, or put it on the desktop.
  42623. You can then call setIconImage() to create an icon for it in the taskbar.
  42624. To change the icon's tooltip, you can use setIconTooltip().
  42625. To respond to mouse-events, you can override the normal mouseDown(),
  42626. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  42627. position will not be valid, you can use this to respond to clicks. Traditionally
  42628. you'd use a left-click to show your application's window, and a right-click
  42629. to show a pop-up menu.
  42630. */
  42631. class JUCE_API SystemTrayIconComponent : public Component
  42632. {
  42633. public:
  42634. SystemTrayIconComponent();
  42635. /** Destructor. */
  42636. ~SystemTrayIconComponent();
  42637. /** Changes the image shown in the taskbar.
  42638. */
  42639. void setIconImage (const Image& newImage);
  42640. /** Changes the tooltip that Windows shows above the icon. */
  42641. void setIconTooltip (const String& tooltip);
  42642. #if JUCE_LINUX
  42643. /** @internal */
  42644. void paint (Graphics& g);
  42645. #endif
  42646. juce_UseDebuggingNewOperator
  42647. private:
  42648. SystemTrayIconComponent (const SystemTrayIconComponent&);
  42649. SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  42650. };
  42651. #endif
  42652. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  42653. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  42654. #endif
  42655. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42656. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  42657. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42658. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42659. #if JUCE_WEB_BROWSER || DOXYGEN
  42660. #if ! DOXYGEN
  42661. class WebBrowserComponentInternal;
  42662. #endif
  42663. /**
  42664. A component that displays an embedded web browser.
  42665. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  42666. Windows, probably IE.
  42667. */
  42668. class JUCE_API WebBrowserComponent : public Component
  42669. {
  42670. public:
  42671. /** Creates a WebBrowserComponent.
  42672. Once it's created and visible, send the browser to a URL using goToURL().
  42673. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  42674. component is taken offscreen, it'll clear the current page
  42675. and replace it with a blank page - this can be handy to stop
  42676. the browser using resources in the background when it's not
  42677. actually being used.
  42678. */
  42679. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  42680. /** Destructor. */
  42681. ~WebBrowserComponent();
  42682. /** Sends the browser to a particular URL.
  42683. @param url the URL to go to.
  42684. @param headers an optional set of parameters to put in the HTTP header. If
  42685. you supply this, it should be a set of string in the form
  42686. "HeaderKey: HeaderValue"
  42687. @param postData an optional block of data that will be attached to the HTTP
  42688. POST request
  42689. */
  42690. void goToURL (const String& url,
  42691. const StringArray* headers = 0,
  42692. const MemoryBlock* postData = 0);
  42693. /** Stops the current page loading.
  42694. */
  42695. void stop();
  42696. /** Sends the browser back one page.
  42697. */
  42698. void goBack();
  42699. /** Sends the browser forward one page.
  42700. */
  42701. void goForward();
  42702. /** Refreshes the browser.
  42703. */
  42704. void refresh();
  42705. /** This callback is called when the browser is about to navigate
  42706. to a new location.
  42707. You can override this method to perform some action when the user
  42708. tries to go to a particular URL. To allow the operation to carry on,
  42709. return true, or return false to stop the navigation happening.
  42710. */
  42711. virtual bool pageAboutToLoad (const String& newURL);
  42712. /** @internal */
  42713. void paint (Graphics& g);
  42714. /** @internal */
  42715. void resized();
  42716. /** @internal */
  42717. void parentHierarchyChanged();
  42718. /** @internal */
  42719. void visibilityChanged();
  42720. juce_UseDebuggingNewOperator
  42721. private:
  42722. WebBrowserComponentInternal* browser;
  42723. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  42724. String lastURL;
  42725. StringArray lastHeaders;
  42726. MemoryBlock lastPostData;
  42727. void reloadLastURL();
  42728. void checkWindowAssociation();
  42729. WebBrowserComponent (const WebBrowserComponent&);
  42730. WebBrowserComponent& operator= (const WebBrowserComponent&);
  42731. };
  42732. #endif
  42733. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  42734. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  42735. #endif
  42736. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  42737. #endif
  42738. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  42739. /*** Start of inlined file: juce_ComponentPeer.h ***/
  42740. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  42741. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  42742. class ComponentBoundsConstrainer;
  42743. /**
  42744. The base class for window objects that wrap a component as a real operating
  42745. system object.
  42746. This is an abstract base class - the platform specific code contains default
  42747. implementations of it that create and manage windows.
  42748. @see Component::createNewPeer
  42749. */
  42750. class JUCE_API ComponentPeer
  42751. {
  42752. public:
  42753. /** A combination of these flags is passed to the ComponentPeer constructor. */
  42754. enum StyleFlags
  42755. {
  42756. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  42757. entry on the taskbar (ignored on MacOSX) */
  42758. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  42759. tooltip, etc. */
  42760. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  42761. through it (may not be possible on some platforms). */
  42762. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  42763. title bar and frame\. if not specified, the window will be
  42764. borderless. */
  42765. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  42766. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  42767. minimise button on it. */
  42768. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  42769. maximise button on it. */
  42770. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  42771. close button on it. */
  42772. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  42773. not be possible on all platforms). */
  42774. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  42775. do its own repainting, but only to repaint when the
  42776. performAnyPendingRepaintsNow() method is called. */
  42777. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  42778. be used for things like plugin windows, to stop them interfering
  42779. with the host's shortcut keys */
  42780. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  42781. };
  42782. /** Creates a peer.
  42783. The component is the one that we intend to represent, and the style flags are
  42784. a combination of the values in the StyleFlags enum
  42785. */
  42786. ComponentPeer (Component* component, int styleFlags);
  42787. /** Destructor. */
  42788. virtual ~ComponentPeer();
  42789. /** Returns the component being represented by this peer. */
  42790. Component* getComponent() const throw() { return component; }
  42791. /** Returns the set of style flags that were set when the window was created.
  42792. @see Component::addToDesktop
  42793. */
  42794. int getStyleFlags() const throw() { return styleFlags; }
  42795. /** Returns the raw handle to whatever kind of window is being used.
  42796. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  42797. but rememeber there's no guarantees what you'll get back.
  42798. */
  42799. virtual void* getNativeHandle() const = 0;
  42800. /** Shows or hides the window. */
  42801. virtual void setVisible (bool shouldBeVisible) = 0;
  42802. /** Changes the title of the window. */
  42803. virtual void setTitle (const String& title) = 0;
  42804. /** Moves the window without changing its size.
  42805. If the native window is contained in another window, then the co-ordinates are
  42806. relative to the parent window's origin, not the screen origin.
  42807. This should result in a callback to handleMovedOrResized().
  42808. */
  42809. virtual void setPosition (int x, int y) = 0;
  42810. /** Resizes the window without changing its position.
  42811. This should result in a callback to handleMovedOrResized().
  42812. */
  42813. virtual void setSize (int w, int h) = 0;
  42814. /** Moves and resizes the window.
  42815. If the native window is contained in another window, then the co-ordinates are
  42816. relative to the parent window's origin, not the screen origin.
  42817. This should result in a callback to handleMovedOrResized().
  42818. */
  42819. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  42820. /** Returns the current position and size of the window.
  42821. If the native window is contained in another window, then the co-ordinates are
  42822. relative to the parent window's origin, not the screen origin.
  42823. */
  42824. virtual const Rectangle<int> getBounds() const = 0;
  42825. /** Returns the x-position of this window, relative to the screen's origin. */
  42826. virtual const Point<int> getScreenPosition() const = 0;
  42827. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  42828. virtual const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) = 0;
  42829. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  42830. virtual const Point<int> globalPositionToRelative (const Point<int>& screenPosition) = 0;
  42831. /** Minimises the window. */
  42832. virtual void setMinimised (bool shouldBeMinimised) = 0;
  42833. /** True if the window is currently minimised. */
  42834. virtual bool isMinimised() const = 0;
  42835. /** Enable/disable fullscreen mode for the window. */
  42836. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  42837. /** True if the window is currently full-screen. */
  42838. virtual bool isFullScreen() const = 0;
  42839. /** Sets the size to restore to if fullscreen mode is turned off. */
  42840. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  42841. /** Returns the size to restore to if fullscreen mode is turned off. */
  42842. const Rectangle<int>& getNonFullScreenBounds() const throw();
  42843. /** Attempts to change the icon associated with this window.
  42844. */
  42845. virtual void setIcon (const Image& newIcon) = 0;
  42846. /** Sets a constrainer to use if the peer can resize itself.
  42847. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  42848. */
  42849. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  42850. /** Returns the current constrainer, if one has been set. */
  42851. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  42852. /** Checks if a point is in the window.
  42853. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  42854. is false, then this returns false if the point is actually inside a child of this
  42855. window.
  42856. */
  42857. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  42858. /** Returns the size of the window frame that's around this window.
  42859. Whether or not the window has a normal window frame depends on the flags
  42860. that were set when the window was created by Component::addToDesktop()
  42861. */
  42862. virtual const BorderSize getFrameSize() const = 0;
  42863. /** This is called when the window's bounds change.
  42864. A peer implementation must call this when the window is moved and resized, so that
  42865. this method can pass the message on to the component.
  42866. */
  42867. void handleMovedOrResized();
  42868. /** This is called if the screen resolution changes.
  42869. A peer implementation must call this if the monitor arrangement changes or the available
  42870. screen size changes.
  42871. */
  42872. void handleScreenSizeChange();
  42873. /** This is called to repaint the component into the given context. */
  42874. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  42875. /** Sets this window to either be always-on-top or normal.
  42876. Some kinds of window might not be able to do this, so should return false.
  42877. */
  42878. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  42879. /** Brings the window to the top, optionally also giving it focus. */
  42880. virtual void toFront (bool makeActive) = 0;
  42881. /** Moves the window to be just behind another one. */
  42882. virtual void toBehind (ComponentPeer* other) = 0;
  42883. /** Called when the window is brought to the front, either by the OS or by a call
  42884. to toFront().
  42885. */
  42886. void handleBroughtToFront();
  42887. /** True if the window has the keyboard focus. */
  42888. virtual bool isFocused() const = 0;
  42889. /** Tries to give the window keyboard focus. */
  42890. virtual void grabFocus() = 0;
  42891. /** Tells the window that text input may be required at the given position.
  42892. This may cause things like a virtual on-screen keyboard to appear, depending
  42893. on the OS.
  42894. */
  42895. virtual void textInputRequired (const Point<int>& position) = 0;
  42896. /** Called when the window gains keyboard focus. */
  42897. void handleFocusGain();
  42898. /** Called when the window loses keyboard focus. */
  42899. void handleFocusLoss();
  42900. Component* getLastFocusedSubcomponent() const throw();
  42901. /** Called when a key is pressed.
  42902. For keycode info, see the KeyPress class.
  42903. Returns true if the keystroke was used.
  42904. */
  42905. bool handleKeyPress (int keyCode,
  42906. juce_wchar textCharacter);
  42907. /** Called whenever a key is pressed or released.
  42908. Returns true if the keystroke was used.
  42909. */
  42910. bool handleKeyUpOrDown (bool isKeyDown);
  42911. /** Called whenever a modifier key is pressed or released. */
  42912. void handleModifierKeysChange();
  42913. /** Returns the currently focused TextInputTarget, or null if none is found. */
  42914. TextInputTarget* findCurrentTextInputTarget();
  42915. /** Invalidates a region of the window to be repainted asynchronously. */
  42916. virtual void repaint (const Rectangle<int>& area) = 0;
  42917. /** This can be called (from the message thread) to cause the immediate redrawing
  42918. of any areas of this window that need repainting.
  42919. You shouldn't ever really need to use this, it's mainly for special purposes
  42920. like supporting audio plugins where the host's event loop is out of our control.
  42921. */
  42922. virtual void performAnyPendingRepaintsNow() = 0;
  42923. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  42924. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  42925. void handleUserClosingWindow();
  42926. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  42927. void handleFileDragExit (const StringArray& files);
  42928. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  42929. /** Resets the masking region.
  42930. The subclass should call this every time it's about to call the handlePaint
  42931. method.
  42932. @see addMaskedRegion
  42933. */
  42934. void clearMaskedRegion();
  42935. /** Adds a rectangle to the set of areas not to paint over.
  42936. A component can call this on its peer during its paint() method, to signal
  42937. that the painting code should ignore a given region. The reason
  42938. for this is to stop embedded windows (such as OpenGL) getting painted over.
  42939. The masked region is cleared each time before a paint happens, so a component
  42940. will have to make sure it calls this every time it's painted.
  42941. */
  42942. void addMaskedRegion (int x, int y, int w, int h);
  42943. /** Returns the number of currently-active peers.
  42944. @see getPeer
  42945. */
  42946. static int getNumPeers() throw();
  42947. /** Returns one of the currently-active peers.
  42948. @see getNumPeers
  42949. */
  42950. static ComponentPeer* getPeer (int index) throw();
  42951. /** Checks if this peer object is valid.
  42952. @see getNumPeers
  42953. */
  42954. static bool isValidPeer (const ComponentPeer* peer) throw();
  42955. static void bringModalComponentToFront();
  42956. virtual const StringArray getAvailableRenderingEngines() throw();
  42957. virtual int getCurrentRenderingEngine() throw();
  42958. virtual void setCurrentRenderingEngine (int index) throw();
  42959. juce_UseDebuggingNewOperator
  42960. protected:
  42961. Component* const component;
  42962. const int styleFlags;
  42963. RectangleList maskedRegion;
  42964. Rectangle<int> lastNonFullscreenBounds;
  42965. uint32 lastPaintTime;
  42966. ComponentBoundsConstrainer* constrainer;
  42967. static void updateCurrentModifiers() throw();
  42968. private:
  42969. Component::SafePointer<Component> lastFocusedComponent, dragAndDropTargetComponent;
  42970. Component* lastDragAndDropCompUnderMouse;
  42971. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  42972. friend class Component;
  42973. static ComponentPeer* getPeerFor (const Component* component) throw();
  42974. void setLastDragDropTarget (Component* comp);
  42975. ComponentPeer (const ComponentPeer&);
  42976. ComponentPeer& operator= (const ComponentPeer&);
  42977. };
  42978. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  42979. /*** End of inlined file: juce_ComponentPeer.h ***/
  42980. #endif
  42981. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  42982. /*** Start of inlined file: juce_DialogWindow.h ***/
  42983. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  42984. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  42985. /**
  42986. A dialog-box style window.
  42987. This class is a convenient way of creating a DocumentWindow with a close button
  42988. that can be triggered by pressing the escape key.
  42989. Any of the methods available to a DocumentWindow or ResizableWindow are also
  42990. available to this, so it can be made resizable, have a menu bar, etc.
  42991. To add items to the box, see the ResizableWindow::setContentComponent() method.
  42992. Don't add components directly to this class - always put them in a content component!
  42993. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  42994. the user clicking the close button - for more info, see the DocumentWindow
  42995. help.
  42996. @see DocumentWindow, ResizableWindow
  42997. */
  42998. class JUCE_API DialogWindow : public DocumentWindow
  42999. {
  43000. public:
  43001. /** Creates a DialogWindow.
  43002. @param name the name to give the component - this is also
  43003. the title shown at the top of the window. To change
  43004. this later, use setName()
  43005. @param backgroundColour the colour to use for filling the window's background.
  43006. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43007. close button to be triggered
  43008. @param addToDesktop if true, the window will be automatically added to the
  43009. desktop; if false, you can use it as a child component
  43010. */
  43011. DialogWindow (const String& name,
  43012. const Colour& backgroundColour,
  43013. bool escapeKeyTriggersCloseButton,
  43014. bool addToDesktop = true);
  43015. /** Destructor.
  43016. If a content component has been set with setContentComponent(), it
  43017. will be deleted.
  43018. */
  43019. ~DialogWindow();
  43020. /** Easy way of quickly showing a dialog box containing a given component.
  43021. This will open and display a DialogWindow containing a given component, returning
  43022. when the user clicks its close button.
  43023. It returns the value that was returned by the dialog box's runModalLoop() call.
  43024. To close the dialog programatically, you should call exitModalState (returnValue) on
  43025. the DialogWindow that is created. To find a pointer to this window from your
  43026. contentComponent, you can do something like this:
  43027. @code
  43028. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  43029. if (dw != 0)
  43030. dw->exitModalState (1234);
  43031. @endcode
  43032. @param dialogTitle the dialog box's title
  43033. @param contentComponent the content component for the dialog box. Make sure
  43034. that this has been set to the size you want it to
  43035. be before calling this method. The component won't
  43036. be deleted by this call, so you can re-use it or delete
  43037. it afterwards
  43038. @param componentToCentreAround if this is non-zero, it indicates a component that
  43039. you'd like to show this dialog box in front of. See the
  43040. DocumentWindow::centreAroundComponent() method for more
  43041. info on this parameter
  43042. @param backgroundColour a colour to use for the dialog box's background colour
  43043. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43044. close button to be triggered
  43045. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  43046. a corner resizer
  43047. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  43048. to use a border or corner resizer component. See ResizableWindow::setResizable()
  43049. */
  43050. static int showModalDialog (const String& dialogTitle,
  43051. Component* contentComponent,
  43052. Component* componentToCentreAround,
  43053. const Colour& backgroundColour,
  43054. bool escapeKeyTriggersCloseButton,
  43055. bool shouldBeResizable = false,
  43056. bool useBottomRightCornerResizer = false);
  43057. juce_UseDebuggingNewOperator
  43058. protected:
  43059. /** @internal */
  43060. void resized();
  43061. private:
  43062. bool escapeKeyTriggersCloseButton;
  43063. DialogWindow (const DialogWindow&);
  43064. DialogWindow& operator= (const DialogWindow&);
  43065. };
  43066. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  43067. /*** End of inlined file: juce_DialogWindow.h ***/
  43068. #endif
  43069. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43070. #endif
  43071. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43072. #endif
  43073. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43074. /*** Start of inlined file: juce_SplashScreen.h ***/
  43075. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43076. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  43077. /** A component for showing a splash screen while your app starts up.
  43078. This will automatically position itself, and delete itself when the app has
  43079. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  43080. this).
  43081. To use it, just create one of these in your JUCEApplication::initialise() method,
  43082. call its show() method and let the object delete itself later.
  43083. E.g. @code
  43084. void MyApp::initialise (const String& commandLine)
  43085. {
  43086. SplashScreen* splash = new SplashScreen();
  43087. splash->show ("welcome to my app",
  43088. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  43089. 4000, false);
  43090. .. no need to delete the splash screen - it'll do that itself.
  43091. }
  43092. @endcode
  43093. */
  43094. class JUCE_API SplashScreen : public Component,
  43095. public Timer,
  43096. private DeletedAtShutdown
  43097. {
  43098. public:
  43099. /** Creates a SplashScreen object.
  43100. After creating one of these (or your subclass of it), call one of the show()
  43101. methods to display it.
  43102. */
  43103. SplashScreen();
  43104. /** Destructor. */
  43105. ~SplashScreen();
  43106. /** Creates a SplashScreen object that will display an image.
  43107. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43108. screen. This method will also dispatch any pending messages to make sure that when
  43109. it returns, the splash screen has been completely drawn, and your initialisation
  43110. code can carry on.
  43111. @param title the name to give the component
  43112. @param backgroundImage an image to draw on the component. The component's size
  43113. will be set to the size of this image, and if the image is
  43114. semi-transparent, the component will be made semi-transparent
  43115. too. This image will be deleted (or released from the ImageCache
  43116. if that's how it was created) by the splash screen object when
  43117. it is itself deleted.
  43118. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43119. should stay visible for. If the initialisation takes longer than
  43120. this time, the splash screen will wait for it to finish before
  43121. disappearing, but if initialisation is very quick, this lets
  43122. you make sure that people get a good look at your splash.
  43123. @param useDropShadow if true, the window will have a drop shadow
  43124. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43125. the mouse (anywhere)
  43126. */
  43127. void show (const String& title,
  43128. Image* backgroundImage,
  43129. int minimumTimeToDisplayFor,
  43130. bool useDropShadow,
  43131. bool removeOnMouseClick = true);
  43132. /** Creates a SplashScreen object with a specified size.
  43133. For a custom splash screen, you can use this method to display it at a certain size
  43134. and then override the paint() method yourself to do whatever's necessary.
  43135. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43136. screen. This method will also dispatch any pending messages to make sure that when
  43137. it returns, the splash screen has been completely drawn, and your initialisation
  43138. code can carry on.
  43139. @param title the name to give the component
  43140. @param width the width to use
  43141. @param height the height to use
  43142. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43143. should stay visible for. If the initialisation takes longer than
  43144. this time, the splash screen will wait for it to finish before
  43145. disappearing, but if initialisation is very quick, this lets
  43146. you make sure that people get a good look at your splash.
  43147. @param useDropShadow if true, the window will have a drop shadow
  43148. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43149. the mouse (anywhere)
  43150. */
  43151. void show (const String& title,
  43152. int width,
  43153. int height,
  43154. int minimumTimeToDisplayFor,
  43155. bool useDropShadow,
  43156. bool removeOnMouseClick = true);
  43157. /** @internal */
  43158. void paint (Graphics& g);
  43159. /** @internal */
  43160. void timerCallback();
  43161. juce_UseDebuggingNewOperator
  43162. private:
  43163. Image* backgroundImage;
  43164. Time earliestTimeToDelete;
  43165. int originalClickCounter;
  43166. SplashScreen (const SplashScreen&);
  43167. SplashScreen& operator= (const SplashScreen&);
  43168. };
  43169. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  43170. /*** End of inlined file: juce_SplashScreen.h ***/
  43171. #endif
  43172. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43173. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  43174. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43175. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43176. /**
  43177. A thread that automatically pops up a modal dialog box with a progress bar
  43178. and cancel button while it's busy running.
  43179. These are handy for performing some sort of task while giving the user feedback
  43180. about how long there is to go, etc.
  43181. E.g. @code
  43182. class MyTask : public ThreadWithProgressWindow
  43183. {
  43184. public:
  43185. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  43186. {
  43187. }
  43188. ~MyTask()
  43189. {
  43190. }
  43191. void run()
  43192. {
  43193. for (int i = 0; i < thingsToDo; ++i)
  43194. {
  43195. // must check this as often as possible, because this is
  43196. // how we know if the user's pressed 'cancel'
  43197. if (threadShouldExit())
  43198. break;
  43199. // this will update the progress bar on the dialog box
  43200. setProgress (i / (double) thingsToDo);
  43201. // ... do the business here...
  43202. }
  43203. }
  43204. };
  43205. void doTheTask()
  43206. {
  43207. MyTask m;
  43208. if (m.runThread())
  43209. {
  43210. // thread finished normally..
  43211. }
  43212. else
  43213. {
  43214. // user pressed the cancel button..
  43215. }
  43216. }
  43217. @endcode
  43218. @see Thread, AlertWindow
  43219. */
  43220. class JUCE_API ThreadWithProgressWindow : public Thread,
  43221. private Timer
  43222. {
  43223. public:
  43224. /** Creates the thread.
  43225. Initially, the dialog box won't be visible, it'll only appear when the
  43226. runThread() method is called.
  43227. @param windowTitle the title to go at the top of the dialog box
  43228. @param hasProgressBar whether the dialog box should have a progress bar (see
  43229. setProgress() )
  43230. @param hasCancelButton whether the dialog box should have a cancel button
  43231. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  43232. the thread to stop before killing it forcibly (see
  43233. Thread::stopThread() )
  43234. @param cancelButtonText the text that should be shown in the cancel button
  43235. (if it has one)
  43236. */
  43237. ThreadWithProgressWindow (const String& windowTitle,
  43238. bool hasProgressBar,
  43239. bool hasCancelButton,
  43240. int timeOutMsWhenCancelling = 10000,
  43241. const String& cancelButtonText = "Cancel");
  43242. /** Destructor. */
  43243. ~ThreadWithProgressWindow();
  43244. /** Starts the thread and waits for it to finish.
  43245. This will start the thread, make the dialog box appear, and wait until either
  43246. the thread finishes normally, or until the cancel button is pressed.
  43247. Before returning, the dialog box will be hidden.
  43248. @param threadPriority the priority to use when starting the thread - see
  43249. Thread::startThread() for values
  43250. @returns true if the thread finished normally; false if the user pressed cancel
  43251. */
  43252. bool runThread (int threadPriority = 5);
  43253. /** The thread should call this periodically to update the position of the progress bar.
  43254. @param newProgress the progress, from 0.0 to 1.0
  43255. @see setStatusMessage
  43256. */
  43257. void setProgress (double newProgress);
  43258. /** The thread can call this to change the message that's displayed in the dialog box.
  43259. */
  43260. void setStatusMessage (const String& newStatusMessage);
  43261. /** Returns the AlertWindow that is being used.
  43262. */
  43263. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  43264. juce_UseDebuggingNewOperator
  43265. private:
  43266. void timerCallback();
  43267. double progress;
  43268. ScopedPointer <AlertWindow> alertWindow;
  43269. String message;
  43270. CriticalSection messageLock;
  43271. const int timeOutMsWhenCancelling;
  43272. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  43273. ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  43274. };
  43275. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43276. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  43277. #endif
  43278. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  43279. #endif
  43280. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  43281. #endif
  43282. #ifndef __JUCE_COLOUR_JUCEHEADER__
  43283. #endif
  43284. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  43285. #endif
  43286. #ifndef __JUCE_COLOURS_JUCEHEADER__
  43287. #endif
  43288. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  43289. #endif
  43290. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43291. /*** Start of inlined file: juce_EdgeTable.h ***/
  43292. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43293. #define __JUCE_EDGETABLE_JUCEHEADER__
  43294. class Path;
  43295. class Image;
  43296. /**
  43297. A table of horizontal scan-line segments - used for rasterising Paths.
  43298. @see Path, Graphics
  43299. */
  43300. class JUCE_API EdgeTable
  43301. {
  43302. public:
  43303. /** Creates an edge table containing a path.
  43304. A table is created with a fixed vertical range, and only sections of the path
  43305. which lie within this range will be added to the table.
  43306. @param clipLimits only the region of the path that lies within this area will be added
  43307. @param pathToAdd the path to add to the table
  43308. @param transform a transform to apply to the path being added
  43309. */
  43310. EdgeTable (const Rectangle<int>& clipLimits,
  43311. const Path& pathToAdd,
  43312. const AffineTransform& transform);
  43313. /** Creates an edge table containing a rectangle.
  43314. */
  43315. EdgeTable (const Rectangle<int>& rectangleToAdd);
  43316. /** Creates an edge table containing a rectangle list.
  43317. */
  43318. EdgeTable (const RectangleList& rectanglesToAdd);
  43319. /** Creates an edge table containing a rectangle.
  43320. */
  43321. EdgeTable (const Rectangle<float>& rectangleToAdd);
  43322. /** Creates a copy of another edge table. */
  43323. EdgeTable (const EdgeTable& other);
  43324. /** Copies from another edge table. */
  43325. EdgeTable& operator= (const EdgeTable& other);
  43326. /** Destructor. */
  43327. ~EdgeTable();
  43328. void clipToRectangle (const Rectangle<int>& r) throw();
  43329. void excludeRectangle (const Rectangle<int>& r) throw();
  43330. void clipToEdgeTable (const EdgeTable& other);
  43331. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw();
  43332. bool isEmpty() throw();
  43333. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  43334. void translate (float dx, int dy) throw();
  43335. /** Reduces the amount of space the table has allocated.
  43336. This will shrink the table down to use as little memory as possible - useful for
  43337. read-only tables that get stored and re-used for rendering.
  43338. */
  43339. void optimiseTable() throw();
  43340. /** Iterates the lines in the table, for rendering.
  43341. This function will iterate each line in the table, and call a user-defined class
  43342. to render each pixel or continuous line of pixels that the table contains.
  43343. @param iterationCallback this templated class must contain the following methods:
  43344. @code
  43345. inline void setEdgeTableYPos (int y);
  43346. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  43347. inline void handleEdgeTablePixelFull (int x) const;
  43348. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  43349. inline void handleEdgeTableLineFull (int x, int width) const;
  43350. @endcode
  43351. (these don't necessarily have to be 'const', but it might help it go faster)
  43352. */
  43353. template <class EdgeTableIterationCallback>
  43354. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  43355. {
  43356. const int* lineStart = table;
  43357. for (int y = 0; y < bounds.getHeight(); ++y)
  43358. {
  43359. const int* line = lineStart;
  43360. lineStart += lineStrideElements;
  43361. int numPoints = line[0];
  43362. if (--numPoints > 0)
  43363. {
  43364. int x = *++line;
  43365. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  43366. int levelAccumulator = 0;
  43367. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  43368. while (--numPoints >= 0)
  43369. {
  43370. const int level = *++line;
  43371. jassert (((unsigned int) level) < (unsigned int) 256);
  43372. const int endX = *++line;
  43373. jassert (endX >= x);
  43374. const int endOfRun = (endX >> 8);
  43375. if (endOfRun == (x >> 8))
  43376. {
  43377. // small segment within the same pixel, so just save it for the next
  43378. // time round..
  43379. levelAccumulator += (endX - x) * level;
  43380. }
  43381. else
  43382. {
  43383. // plot the fist pixel of this segment, including any accumulated
  43384. // levels from smaller segments that haven't been drawn yet
  43385. levelAccumulator += (0xff - (x & 0xff)) * level;
  43386. levelAccumulator >>= 8;
  43387. x >>= 8;
  43388. if (levelAccumulator > 0)
  43389. {
  43390. if (levelAccumulator >> 8)
  43391. iterationCallback.handleEdgeTablePixelFull (x);
  43392. else
  43393. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  43394. }
  43395. // if there's a run of similar pixels, do it all in one go..
  43396. if (level > 0)
  43397. {
  43398. jassert (endOfRun <= bounds.getRight());
  43399. const int numPix = endOfRun - ++x;
  43400. if (numPix > 0)
  43401. iterationCallback.handleEdgeTableLine (x, numPix, level);
  43402. }
  43403. // save the bit at the end to be drawn next time round the loop.
  43404. levelAccumulator = (endX & 0xff) * level;
  43405. }
  43406. x = endX;
  43407. }
  43408. levelAccumulator >>= 8;
  43409. if (levelAccumulator > 0)
  43410. {
  43411. x >>= 8;
  43412. jassert (x >= bounds.getX() && x < bounds.getRight());
  43413. if (levelAccumulator >> 8)
  43414. iterationCallback.handleEdgeTablePixelFull (x);
  43415. else
  43416. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  43417. }
  43418. }
  43419. }
  43420. }
  43421. juce_UseDebuggingNewOperator
  43422. private:
  43423. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  43424. HeapBlock<int> table;
  43425. Rectangle<int> bounds;
  43426. int maxEdgesPerLine, lineStrideElements;
  43427. bool needToCheckEmptinesss;
  43428. void addEdgePoint (int x, int y, int winding) throw();
  43429. void remapTableForNumEdges (int newNumEdgesPerLine) throw();
  43430. void intersectWithEdgeTableLine (int y, const int* otherLine) throw();
  43431. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  43432. void sanitiseLevels (bool useNonZeroWinding) throw();
  43433. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  43434. };
  43435. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  43436. /*** End of inlined file: juce_EdgeTable.h ***/
  43437. #endif
  43438. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  43439. #endif
  43440. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  43441. #endif
  43442. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  43443. #endif
  43444. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43445. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  43446. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43447. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43448. /**
  43449. Interface class for graphics context objects, used internally by the Graphics class.
  43450. Users are not supposed to create instances of this class directly - do your drawing
  43451. via the Graphics object instead.
  43452. It's a base class for different types of graphics context, that may perform software-based
  43453. or OS-accelerated rendering.
  43454. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  43455. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  43456. context.
  43457. */
  43458. class JUCE_API LowLevelGraphicsContext
  43459. {
  43460. protected:
  43461. LowLevelGraphicsContext();
  43462. public:
  43463. virtual ~LowLevelGraphicsContext();
  43464. /** Returns true if this device is vector-based, e.g. a printer. */
  43465. virtual bool isVectorDevice() const = 0;
  43466. /** Moves the origin to a new position.
  43467. The co-ords are relative to the current origin, and indicate the new position
  43468. of (0, 0).
  43469. */
  43470. virtual void setOrigin (int x, int y) = 0;
  43471. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  43472. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  43473. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  43474. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  43475. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform) = 0;
  43476. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  43477. virtual const Rectangle<int> getClipBounds() const = 0;
  43478. virtual bool isClipEmpty() const = 0;
  43479. virtual void saveState() = 0;
  43480. virtual void restoreState() = 0;
  43481. virtual void setFill (const FillType& fillType) = 0;
  43482. virtual void setOpacity (float newOpacity) = 0;
  43483. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  43484. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  43485. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  43486. virtual void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  43487. const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  43488. virtual void drawLine (const Line <float>& line) = 0;
  43489. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  43490. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  43491. virtual void setFont (const Font& newFont) = 0;
  43492. virtual const Font getFont() = 0;
  43493. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  43494. };
  43495. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  43496. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  43497. #endif
  43498. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43499. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  43500. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43501. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43502. /**
  43503. An implementation of LowLevelGraphicsContext that turns the drawing operations
  43504. into a PostScript document.
  43505. */
  43506. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  43507. {
  43508. public:
  43509. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  43510. const String& documentTitle,
  43511. int totalWidth,
  43512. int totalHeight);
  43513. ~LowLevelGraphicsPostScriptRenderer();
  43514. bool isVectorDevice() const;
  43515. void setOrigin (int x, int y);
  43516. bool clipToRectangle (const Rectangle<int>& r);
  43517. bool clipToRectangleList (const RectangleList& clipRegion);
  43518. void excludeClipRectangle (const Rectangle<int>& r);
  43519. void clipToPath (const Path& path, const AffineTransform& transform);
  43520. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  43521. void saveState();
  43522. void restoreState();
  43523. bool clipRegionIntersects (const Rectangle<int>& r);
  43524. const Rectangle<int> getClipBounds() const;
  43525. bool isClipEmpty() const;
  43526. void setFill (const FillType& fillType);
  43527. void setOpacity (float opacity);
  43528. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  43529. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  43530. void fillPath (const Path& path, const AffineTransform& transform);
  43531. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  43532. const AffineTransform& transform, bool fillEntireClipAsTiles);
  43533. void drawLine (const Line <float>& line);
  43534. void drawVerticalLine (int x, float top, float bottom);
  43535. void drawHorizontalLine (int x, float top, float bottom);
  43536. const Font getFont();
  43537. void setFont (const Font& newFont);
  43538. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  43539. juce_UseDebuggingNewOperator
  43540. protected:
  43541. OutputStream& out;
  43542. int totalWidth, totalHeight;
  43543. bool needToClip;
  43544. Colour lastColour;
  43545. struct SavedState
  43546. {
  43547. SavedState();
  43548. ~SavedState();
  43549. RectangleList clip;
  43550. int xOffset, yOffset;
  43551. FillType fillType;
  43552. Font font;
  43553. private:
  43554. SavedState& operator= (const SavedState&);
  43555. };
  43556. OwnedArray <SavedState> stateStack;
  43557. void writeClip();
  43558. void writeColour (const Colour& colour);
  43559. void writePath (const Path& path) const;
  43560. void writeXY (float x, float y) const;
  43561. void writeTransform (const AffineTransform& trans) const;
  43562. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  43563. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  43564. LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  43565. };
  43566. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  43567. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  43568. #endif
  43569. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43570. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  43571. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43572. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43573. /**
  43574. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  43575. its rendering in memory.
  43576. User code is not supposed to create instances of this class directly - do all your
  43577. rendering via the Graphics class instead.
  43578. */
  43579. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  43580. {
  43581. public:
  43582. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn);
  43583. LowLevelGraphicsSoftwareRenderer (Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  43584. ~LowLevelGraphicsSoftwareRenderer();
  43585. bool isVectorDevice() const;
  43586. void setOrigin (int x, int y);
  43587. bool clipToRectangle (const Rectangle<int>& r);
  43588. bool clipToRectangleList (const RectangleList& clipRegion);
  43589. void excludeClipRectangle (const Rectangle<int>& r);
  43590. void clipToPath (const Path& path, const AffineTransform& transform);
  43591. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  43592. bool clipRegionIntersects (const Rectangle<int>& r);
  43593. const Rectangle<int> getClipBounds() const;
  43594. bool isClipEmpty() const;
  43595. void saveState();
  43596. void restoreState();
  43597. void setFill (const FillType& fillType);
  43598. void setOpacity (float opacity);
  43599. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  43600. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  43601. void fillPath (const Path& path, const AffineTransform& transform);
  43602. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  43603. const AffineTransform& transform, bool fillEntireClipAsTiles);
  43604. void drawLine (const Line <float>& line);
  43605. void drawVerticalLine (int x, float top, float bottom);
  43606. void drawHorizontalLine (int x, float top, float bottom);
  43607. void setFont (const Font& newFont);
  43608. const Font getFont();
  43609. void drawGlyph (int glyphNumber, float x, float y);
  43610. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  43611. juce_UseDebuggingNewOperator
  43612. protected:
  43613. Image& image;
  43614. class GlyphCache;
  43615. class CachedGlyph;
  43616. class SavedState;
  43617. friend class ScopedPointer <SavedState>;
  43618. friend class OwnedArray <SavedState>;
  43619. friend class OwnedArray <CachedGlyph>;
  43620. ScopedPointer <SavedState> currentState;
  43621. OwnedArray <SavedState> stateStack;
  43622. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  43623. LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  43624. };
  43625. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  43626. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  43627. #endif
  43628. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  43629. #endif
  43630. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  43631. #endif
  43632. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  43633. /*** Start of inlined file: juce_DrawableComposite.h ***/
  43634. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  43635. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  43636. /**
  43637. A drawable object which acts as a container for a set of other Drawables.
  43638. @see Drawable
  43639. */
  43640. class JUCE_API DrawableComposite : public Drawable,
  43641. public RelativeCoordinate::NamedCoordinateFinder
  43642. {
  43643. public:
  43644. /** Creates a composite Drawable. */
  43645. DrawableComposite();
  43646. /** Creates a copy of a DrawableComposite. */
  43647. DrawableComposite (const DrawableComposite& other);
  43648. /** Destructor. */
  43649. virtual ~DrawableComposite();
  43650. /** Adds a new sub-drawable to this one.
  43651. This passes in a Drawable pointer for this object to look after. To add a copy
  43652. of a drawable, use the form of this method that takes a Drawable reference instead.
  43653. @param drawable the object to add - this will be deleted automatically
  43654. when no longer needed, so the caller mustn't keep any
  43655. pointers to it.
  43656. @param index where to insert it in the list of drawables. 0 is the back,
  43657. -1 is the front, or any value from 0 and getNumDrawables()
  43658. can be used
  43659. @see removeDrawable
  43660. */
  43661. void insertDrawable (Drawable* drawable, int index = -1);
  43662. /** Adds a new sub-drawable to this one.
  43663. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  43664. for this object to look after, use the form of this method that takes a Drawable
  43665. pointer instead.
  43666. @param drawable the object to add - an internal copy will be made of this object
  43667. @param index where to insert it in the list of drawables. 0 is the back,
  43668. -1 is the front, or any value from 0 and getNumDrawables()
  43669. can be used
  43670. @see removeDrawable
  43671. */
  43672. void insertDrawable (const Drawable& drawable, int index = -1);
  43673. /** Deletes one of the Drawable objects.
  43674. @param index the index of the drawable to delete, between 0
  43675. and (getNumDrawables() - 1).
  43676. @param deleteDrawable if this is true, the drawable that is removed will also
  43677. be deleted. If false, it'll just be removed.
  43678. @see insertDrawable, getNumDrawables
  43679. */
  43680. void removeDrawable (int index, bool deleteDrawable = true);
  43681. /** Returns the number of drawables contained inside this one.
  43682. @see getDrawable
  43683. */
  43684. int getNumDrawables() const throw() { return drawables.size(); }
  43685. /** Returns one of the drawables that are contained in this one.
  43686. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  43687. to find it.
  43688. The pointer returned is managed by this object and will be deleted when no longer
  43689. needed, so be careful what you do with it.
  43690. @see getNumDrawables
  43691. */
  43692. Drawable* getDrawable (int index) const throw() { return drawables [index]; }
  43693. /** Brings one of the Drawables to the front.
  43694. @param index the index of the drawable to move, between 0
  43695. and (getNumDrawables() - 1).
  43696. @see insertDrawable, getNumDrawables
  43697. */
  43698. void bringToFront (int index);
  43699. /** Sets the transform to be applied to this drawable, by defining the positions
  43700. where three anchor points should end up in the target rendering space.
  43701. @param targetPositionForOrigin the position that the local coordinate (0, 0) should be
  43702. mapped onto when rendering this object.
  43703. @param targetPositionForX1Y0 the position that the local coordinate (1, 0) should be
  43704. mapped onto when rendering this object.
  43705. @param targetPositionForX0Y1 the position that the local coordinate (0, 1) should be
  43706. mapped onto when rendering this object.
  43707. */
  43708. void setTransform (const RelativePoint& targetPositionForOrigin,
  43709. const RelativePoint& targetPositionForX1Y0,
  43710. const RelativePoint& targetPositionForX0Y1);
  43711. /** Returns the position to which the local coordinate (0, 0) should be remapped in the target
  43712. coordinate space when rendering this object.
  43713. @see setTransform
  43714. */
  43715. const RelativePoint& getTargetPositionForOrigin() const throw() { return controlPoints[0]; }
  43716. /** Returns the position to which the local coordinate (1, 0) should be remapped in the target
  43717. coordinate space when rendering this object.
  43718. @see setTransform
  43719. */
  43720. const RelativePoint& getTargetPositionForX1Y0() const throw() { return controlPoints[1]; }
  43721. /** Returns the position to which the local coordinate (0, 1) should be remapped in the target
  43722. coordinate space when rendering this object.
  43723. @see setTransform
  43724. */
  43725. const RelativePoint& getTargetPositionForX0Y1() const throw() { return controlPoints[2]; }
  43726. struct Marker
  43727. {
  43728. Marker (const Marker&);
  43729. Marker (const String& name, const RelativeCoordinate& position, bool isOnXAxis);
  43730. bool operator!= (const Marker&) const throw();
  43731. String name;
  43732. RelativeCoordinate position;
  43733. bool isOnXAxis;
  43734. };
  43735. int getNumMarkers (bool xAxis) const throw();
  43736. const Marker* getMarker (int index) const throw();
  43737. void setMarker (const String& name, bool xAxis, const RelativeCoordinate& position);
  43738. void removeMarker (int index);
  43739. /** @internal */
  43740. void render (const Drawable::RenderingContext& context) const;
  43741. /** @internal */
  43742. const Rectangle<float> getBounds() const;
  43743. /** @internal */
  43744. bool hitTest (float x, float y) const;
  43745. /** @internal */
  43746. Drawable* createCopy() const;
  43747. /** @internal */
  43748. void invalidatePoints();
  43749. /** @internal */
  43750. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  43751. /** @internal */
  43752. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  43753. /** @internal */
  43754. static const Identifier valueTreeType;
  43755. /** @internal */
  43756. const Identifier getValueTreeType() const { return valueTreeType; }
  43757. /** @internal */
  43758. const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const;
  43759. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  43760. class ValueTreeWrapper : public ValueTreeWrapperBase
  43761. {
  43762. public:
  43763. ValueTreeWrapper (const ValueTree& state);
  43764. int getNumDrawables() const;
  43765. const ValueTree getDrawableState (int index) const;
  43766. void addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager);
  43767. void moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager);
  43768. void removeDrawable (int index, UndoManager* undoManager);
  43769. const RelativePoint getTargetPositionForOrigin() const;
  43770. void setTargetPositionForOrigin (const RelativePoint& newPoint, UndoManager* undoManager);
  43771. const RelativePoint getTargetPositionForX1Y0() const;
  43772. void setTargetPositionForX1Y0 (const RelativePoint& newPoint, UndoManager* undoManager);
  43773. const RelativePoint getTargetPositionForX0Y1() const;
  43774. void setTargetPositionForX0Y1 (const RelativePoint& newPoint, UndoManager* undoManager);
  43775. int getNumMarkers() const;
  43776. const Marker getMarker (int index) const;
  43777. void setMarker (const String& name, bool xAxis, const RelativeCoordinate& position, UndoManager* undoManager);
  43778. void removeMarker (int index, UndoManager* undoManager);
  43779. private:
  43780. static const Identifier topLeft, topRight, bottomLeft, childGroupTag, markerGroupTag,
  43781. markerTag, nameProperty, xAxisProperty, posProperty;
  43782. ValueTree getChildList() const;
  43783. ValueTree getChildListCreating (UndoManager* undoManager);
  43784. ValueTree getMarkerList() const;
  43785. ValueTree getMarkerListCreating (UndoManager* undoManager);
  43786. };
  43787. juce_UseDebuggingNewOperator
  43788. private:
  43789. OwnedArray <Drawable> drawables;
  43790. RelativePoint controlPoints[3];
  43791. OwnedArray <Marker> markers;
  43792. const Rectangle<float> getUntransformedBounds() const;
  43793. const AffineTransform calculateTransform() const;
  43794. DrawableComposite& operator= (const DrawableComposite&);
  43795. };
  43796. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  43797. /*** End of inlined file: juce_DrawableComposite.h ***/
  43798. #endif
  43799. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  43800. /*** Start of inlined file: juce_DrawableImage.h ***/
  43801. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  43802. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  43803. /**
  43804. A drawable object which is a bitmap image.
  43805. @see Drawable
  43806. */
  43807. class JUCE_API DrawableImage : public Drawable
  43808. {
  43809. public:
  43810. DrawableImage();
  43811. DrawableImage (const DrawableImage& other);
  43812. /** Destructor. */
  43813. virtual ~DrawableImage();
  43814. /** Sets the image that this drawable will render.
  43815. An internal copy is made of the image passed-in. If you want to provide an
  43816. image that this object can take charge of without needing to create a copy,
  43817. use the other setImage() method.
  43818. */
  43819. void setImage (const Image& imageToCopy);
  43820. /** Sets the image that this drawable will render.
  43821. A good way to use this is with the ImageCache - if you create an image
  43822. with ImageCache and pass it in here with releaseWhenNotNeeded = true, then
  43823. it'll be released neatly with its reference count being decreased.
  43824. @param imageToUse the image to render (may be a null pointer)
  43825. @param releaseWhenNotNeeded if false, a simple pointer is kept to the image; if true,
  43826. then the image will be deleted when this object no longer
  43827. needs it - unless the image was created by the ImageCache,
  43828. in which case it will be released with ImageCache::release().
  43829. */
  43830. void setImage (Image* imageToUse, bool releaseWhenNotNeeded);
  43831. /** Returns the current image. */
  43832. Image* getImage() const throw() { return image; }
  43833. /** Sets the opacity to use when drawing the image. */
  43834. void setOpacity (float newOpacity);
  43835. /** Returns the image's opacity. */
  43836. float getOpacity() const throw() { return opacity; }
  43837. /** Sets a colour to draw over the image's alpha channel.
  43838. By default this is transparent so isn't drawn, but if you set a non-transparent
  43839. colour here, then it will be overlaid on the image, using the image's alpha
  43840. channel as a mask.
  43841. This is handy for doing things like darkening or lightening an image by overlaying
  43842. it with semi-transparent black or white.
  43843. */
  43844. void setOverlayColour (const Colour& newOverlayColour);
  43845. /** Returns the overlay colour. */
  43846. const Colour& getOverlayColour() const throw() { return overlayColour; }
  43847. /** Sets the transform to be applied to this image, by defining the positions
  43848. where three anchor points should end up in the target rendering space.
  43849. @param imageTopLeftPosition the position that the image's top-left corner should be mapped to
  43850. in the target coordinate space.
  43851. @param imageTopRightPosition the position that the image's top-right corner should be mapped to
  43852. in the target coordinate space.
  43853. @param imageBottomLeftPosition the position that the image's bottom-left corner should be mapped to
  43854. in the target coordinate space.
  43855. */
  43856. void setTransform (const RelativePoint& imageTopLeftPosition,
  43857. const RelativePoint& imageTopRightPosition,
  43858. const RelativePoint& imageBottomLeftPosition);
  43859. /** Returns the position to which the image's top-left corner should be remapped in the target
  43860. coordinate space when rendering this object.
  43861. @see setTransform
  43862. */
  43863. const RelativePoint& getTargetPositionForTopLeft() const throw() { return controlPoints[0]; }
  43864. /** Returns the position to which the image's top-right corner should be remapped in the target
  43865. coordinate space when rendering this object.
  43866. @see setTransform
  43867. */
  43868. const RelativePoint& getTargetPositionForTopRight() const throw() { return controlPoints[1]; }
  43869. /** Returns the position to which the image's bottom-left corner should be remapped in the target
  43870. coordinate space when rendering this object.
  43871. @see setTransform
  43872. */
  43873. const RelativePoint& getTargetPositionForBottomLeft() const throw() { return controlPoints[2]; }
  43874. /** @internal */
  43875. void render (const Drawable::RenderingContext& context) const;
  43876. /** @internal */
  43877. const Rectangle<float> getBounds() const;
  43878. /** @internal */
  43879. bool hitTest (float x, float y) const;
  43880. /** @internal */
  43881. Drawable* createCopy() const;
  43882. /** @internal */
  43883. void invalidatePoints();
  43884. /** @internal */
  43885. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  43886. /** @internal */
  43887. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  43888. /** @internal */
  43889. static const Identifier valueTreeType;
  43890. /** @internal */
  43891. const Identifier getValueTreeType() const { return valueTreeType; }
  43892. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  43893. class ValueTreeWrapper : public ValueTreeWrapperBase
  43894. {
  43895. public:
  43896. ValueTreeWrapper (const ValueTree& state);
  43897. const var getImageIdentifier() const;
  43898. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  43899. float getOpacity() const;
  43900. void setOpacity (float newOpacity, UndoManager* undoManager);
  43901. const Colour getOverlayColour() const;
  43902. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  43903. const RelativePoint getTargetPositionForTopLeft() const;
  43904. void setTargetPositionForTopLeft (const RelativePoint& newPoint, UndoManager* undoManager);
  43905. const RelativePoint getTargetPositionForTopRight() const;
  43906. void setTargetPositionForTopRight (const RelativePoint& newPoint, UndoManager* undoManager);
  43907. const RelativePoint getTargetPositionForBottomLeft() const;
  43908. void setTargetPositionForBottomLeft (const RelativePoint& newPoint, UndoManager* undoManager);
  43909. private:
  43910. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  43911. };
  43912. juce_UseDebuggingNewOperator
  43913. private:
  43914. Image* image;
  43915. bool canDeleteImage;
  43916. float opacity;
  43917. Colour overlayColour;
  43918. RelativePoint controlPoints[3];
  43919. const AffineTransform calculateTransform() const;
  43920. DrawableImage& operator= (const DrawableImage&);
  43921. };
  43922. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  43923. /*** End of inlined file: juce_DrawableImage.h ***/
  43924. #endif
  43925. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  43926. /*** Start of inlined file: juce_DrawablePath.h ***/
  43927. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  43928. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  43929. /**
  43930. A drawable object which renders a filled or outlined shape.
  43931. @see Drawable
  43932. */
  43933. class JUCE_API DrawablePath : public Drawable
  43934. {
  43935. public:
  43936. /** Creates a DrawablePath. */
  43937. DrawablePath();
  43938. DrawablePath (const DrawablePath& other);
  43939. /** Destructor. */
  43940. virtual ~DrawablePath();
  43941. /** Changes the path that will be drawn.
  43942. @see setFillColour, setStrokeType
  43943. */
  43944. void setPath (const Path& newPath);
  43945. /** Sets a fill type for the path.
  43946. This colour is used to fill the path - if you don't want the path to be
  43947. filled (e.g. if you're just drawing an outline), set this to a transparent
  43948. colour.
  43949. @see setPath, setStrokeFill
  43950. */
  43951. void setFill (const FillType& newFill);
  43952. /** Returns the current fill type.
  43953. @see setFill
  43954. */
  43955. const FillType& getFill() const throw() { return mainFill; }
  43956. /** Sets the fill type with which the outline will be drawn.
  43957. @see setFill
  43958. */
  43959. void setStrokeFill (const FillType& newStrokeFill);
  43960. /** Returns the current stroke fill.
  43961. @see setStrokeFill
  43962. */
  43963. const FillType& getStrokeFill() const throw() { return strokeFill; }
  43964. /** Changes the properties of the outline that will be drawn around the path.
  43965. If the stroke has 0 thickness, no stroke will be drawn.
  43966. @see setStrokeThickness, setStrokeColour
  43967. */
  43968. void setStrokeType (const PathStrokeType& newStrokeType);
  43969. /** Changes the stroke thickness.
  43970. This is a shortcut for calling setStrokeType.
  43971. */
  43972. void setStrokeThickness (float newThickness);
  43973. /** Returns the current outline style. */
  43974. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  43975. /** Returns the current path. */
  43976. const Path& getPath() const;
  43977. /** Returns the current path for the outline. */
  43978. const Path& getStrokePath() const;
  43979. /** @internal */
  43980. void render (const Drawable::RenderingContext& context) const;
  43981. /** @internal */
  43982. const Rectangle<float> getBounds() const;
  43983. /** @internal */
  43984. bool hitTest (float x, float y) const;
  43985. /** @internal */
  43986. Drawable* createCopy() const;
  43987. /** @internal */
  43988. void invalidatePoints();
  43989. /** @internal */
  43990. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  43991. /** @internal */
  43992. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  43993. /** @internal */
  43994. static const Identifier valueTreeType;
  43995. /** @internal */
  43996. const Identifier getValueTreeType() const { return valueTreeType; }
  43997. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  43998. class ValueTreeWrapper : public ValueTreeWrapperBase
  43999. {
  44000. public:
  44001. ValueTreeWrapper (const ValueTree& state);
  44002. const FillType getMainFill() const;
  44003. void setMainFill (const FillType& newFill, UndoManager* undoManager);
  44004. const FillType getStrokeFill() const;
  44005. void setStrokeFill (const FillType& newFill, UndoManager* undoManager);
  44006. const PathStrokeType getStrokeType() const;
  44007. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager);
  44008. void getPath (RelativePointPath& path) const;
  44009. void setPath (const String& newPath, UndoManager* undoManager);
  44010. private:
  44011. static const Identifier fill, stroke, jointStyle, capStyle, strokeWidth, path;
  44012. };
  44013. juce_UseDebuggingNewOperator
  44014. private:
  44015. FillType mainFill, strokeFill;
  44016. PathStrokeType strokeType;
  44017. ScopedPointer<RelativePointPath> relativePath;
  44018. mutable Path path, stroke;
  44019. mutable bool pathNeedsUpdating, strokeNeedsUpdating;
  44020. void updatePath() const;
  44021. void updateStroke() const;
  44022. bool isStrokeVisible() const throw();
  44023. DrawablePath& operator= (const DrawablePath&);
  44024. };
  44025. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  44026. /*** End of inlined file: juce_DrawablePath.h ***/
  44027. #endif
  44028. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44029. /*** Start of inlined file: juce_DrawableText.h ***/
  44030. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44031. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  44032. /**
  44033. A drawable object which renders a line of text.
  44034. @see Drawable
  44035. */
  44036. class JUCE_API DrawableText : public Drawable
  44037. {
  44038. public:
  44039. /** Creates a DrawableText object. */
  44040. DrawableText();
  44041. DrawableText (const DrawableText& other);
  44042. /** Destructor. */
  44043. virtual ~DrawableText();
  44044. /** Sets the block of text to render */
  44045. void setText (const GlyphArrangement& newText);
  44046. /** Sets a single line of text to render.
  44047. This is a convenient method of adding a single line - for
  44048. more complex text, use the setText() that takes a
  44049. GlyphArrangement instead.
  44050. */
  44051. void setText (const String& newText, const Font& fontToUse);
  44052. /** Returns the text arrangement that was set with setText(). */
  44053. const GlyphArrangement& getText() const throw() { return text; }
  44054. /** Sets the colour of the text. */
  44055. void setColour (const Colour& newColour);
  44056. /** Returns the current text colour. */
  44057. const Colour& getColour() const throw() { return colour; }
  44058. /** @internal */
  44059. void render (const Drawable::RenderingContext& context) const;
  44060. /** @internal */
  44061. const Rectangle<float> getBounds() const;
  44062. /** @internal */
  44063. bool hitTest (float x, float y) const;
  44064. /** @internal */
  44065. Drawable* createCopy() const;
  44066. /** @internal */
  44067. void invalidatePoints();
  44068. /** @internal */
  44069. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44070. /** @internal */
  44071. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44072. /** @internal */
  44073. static const Identifier valueTreeType;
  44074. /** @internal */
  44075. const Identifier getValueTreeType() const { return valueTreeType; }
  44076. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  44077. class ValueTreeWrapper : public ValueTreeWrapperBase
  44078. {
  44079. public:
  44080. ValueTreeWrapper (const ValueTree& state);
  44081. //xxx todo
  44082. private:
  44083. static const Identifier text;
  44084. };
  44085. juce_UseDebuggingNewOperator
  44086. private:
  44087. GlyphArrangement text;
  44088. Colour colour;
  44089. DrawableText& operator= (const DrawableText&);
  44090. };
  44091. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  44092. /*** End of inlined file: juce_DrawableText.h ***/
  44093. #endif
  44094. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  44095. #endif
  44096. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44097. /*** Start of inlined file: juce_GlowEffect.h ***/
  44098. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44099. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  44100. /**
  44101. A component effect that adds a coloured blur around the component's contents.
  44102. (This will only work on non-opaque components).
  44103. @see Component::setComponentEffect, DropShadowEffect
  44104. */
  44105. class JUCE_API GlowEffect : public ImageEffectFilter
  44106. {
  44107. public:
  44108. /** Creates a default 'glow' effect.
  44109. To customise its appearance, use the setGlowProperties() method.
  44110. */
  44111. GlowEffect();
  44112. /** Destructor. */
  44113. ~GlowEffect();
  44114. /** Sets the glow's radius and colour.
  44115. The radius is how large the blur should be, and the colour is
  44116. used to render it (for a less intense glow, lower the colour's
  44117. opacity).
  44118. */
  44119. void setGlowProperties (float newRadius,
  44120. const Colour& newColour);
  44121. /** @internal */
  44122. void applyEffect (Image& sourceImage, Graphics& destContext);
  44123. juce_UseDebuggingNewOperator
  44124. private:
  44125. float radius;
  44126. Colour colour;
  44127. };
  44128. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  44129. /*** End of inlined file: juce_GlowEffect.h ***/
  44130. #endif
  44131. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  44132. #endif
  44133. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44134. /*** Start of inlined file: juce_ReduceOpacityEffect.h ***/
  44135. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44136. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44137. /**
  44138. An effect filter that reduces the image's opacity.
  44139. This can be used to make a component (and its child components) more
  44140. transparent.
  44141. @see Component::setComponentEffect
  44142. */
  44143. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  44144. {
  44145. public:
  44146. /** Creates the effect object.
  44147. The opacity of the component to which the effect is applied will be
  44148. scaled by the given factor (in the range 0 to 1.0f).
  44149. */
  44150. ReduceOpacityEffect (float opacity = 1.0f);
  44151. /** Destructor. */
  44152. ~ReduceOpacityEffect();
  44153. /** Sets how much to scale the component's opacity.
  44154. @param newOpacity should be between 0 and 1.0f
  44155. */
  44156. void setOpacity (float newOpacity);
  44157. /** @internal */
  44158. void applyEffect (Image& sourceImage, Graphics& destContext);
  44159. juce_UseDebuggingNewOperator
  44160. private:
  44161. float opacity;
  44162. };
  44163. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44164. /*** End of inlined file: juce_ReduceOpacityEffect.h ***/
  44165. #endif
  44166. #ifndef __JUCE_FONT_JUCEHEADER__
  44167. #endif
  44168. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  44169. #endif
  44170. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  44171. #endif
  44172. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  44173. #endif
  44174. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  44175. #endif
  44176. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  44177. #endif
  44178. #ifndef __JUCE_LINE_JUCEHEADER__
  44179. #endif
  44180. #ifndef __JUCE_PATH_JUCEHEADER__
  44181. #endif
  44182. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  44183. /*** Start of inlined file: juce_PathIterator.h ***/
  44184. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  44185. #define __JUCE_PATHITERATOR_JUCEHEADER__
  44186. /**
  44187. Flattens a Path object into a series of straight-line sections.
  44188. Use one of these to iterate through a Path object, and it will convert
  44189. all the curves into line sections so it's easy to render or perform
  44190. geometric operations on.
  44191. @see Path
  44192. */
  44193. class JUCE_API PathFlatteningIterator
  44194. {
  44195. public:
  44196. /** Creates a PathFlatteningIterator.
  44197. After creation, use the next() method to initialise the fields in the
  44198. object with the first line's position.
  44199. @param path the path to iterate along
  44200. @param transform a transform to apply to each point in the path being iterated
  44201. @param tolerence the amount by which the curves are allowed to deviate from the
  44202. lines into which they are being broken down - a higher tolerence
  44203. is a bit faster, but less smooth.
  44204. */
  44205. PathFlatteningIterator (const Path& path,
  44206. const AffineTransform& transform = AffineTransform::identity,
  44207. float tolerence = 6.0f);
  44208. /** Destructor. */
  44209. ~PathFlatteningIterator();
  44210. /** Fetches the next line segment from the path.
  44211. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  44212. so that they describe the new line segment.
  44213. @returns false when there are no more lines to fetch.
  44214. */
  44215. bool next();
  44216. float x1; /**< The x position of the start of the current line segment. */
  44217. float y1; /**< The y position of the start of the current line segment. */
  44218. float x2; /**< The x position of the end of the current line segment. */
  44219. float y2; /**< The y position of the end of the current line segment. */
  44220. /** Indicates whether the current line segment is closing a sub-path.
  44221. If the current line is the one that connects the end of a sub-path
  44222. back to the start again, this will be true.
  44223. */
  44224. bool closesSubPath;
  44225. /** The index of the current line within the current sub-path.
  44226. E.g. you can use this to see whether the line is the first one in the
  44227. subpath by seeing if it's 0.
  44228. */
  44229. int subPathIndex;
  44230. /** Returns true if the current segment is the last in the current sub-path. */
  44231. bool isLastInSubpath() const throw() { return stackPos == stackBase.getData()
  44232. && (index >= path.numElements || points [index] == Path::moveMarker); }
  44233. juce_UseDebuggingNewOperator
  44234. private:
  44235. const Path& path;
  44236. const AffineTransform transform;
  44237. float* points;
  44238. float tolerence, subPathCloseX, subPathCloseY;
  44239. const bool isIdentityTransform;
  44240. HeapBlock <float> stackBase;
  44241. float* stackPos;
  44242. size_t index, stackSize;
  44243. PathFlatteningIterator (const PathFlatteningIterator&);
  44244. PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  44245. };
  44246. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  44247. /*** End of inlined file: juce_PathIterator.h ***/
  44248. #endif
  44249. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  44250. #endif
  44251. #ifndef __JUCE_POINT_JUCEHEADER__
  44252. #endif
  44253. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44254. /*** Start of inlined file: juce_PositionedRectangle.h ***/
  44255. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44256. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44257. /**
  44258. A rectangle whose co-ordinates can be defined in terms of absolute or
  44259. proportional distances.
  44260. Designed mainly for storing component positions, this gives you a lot of
  44261. control over how each co-ordinate is stored, either as an absolute position,
  44262. or as a proportion of the size of a parent rectangle.
  44263. It also allows you to define the anchor points by which the rectangle is
  44264. positioned, so for example you could specify that the top right of the
  44265. rectangle should be an absolute distance from its parent's bottom-right corner.
  44266. This object can be stored as a string, which takes the form "x y w h", including
  44267. symbols like '%' and letters to indicate the anchor point. See its toString()
  44268. method for more info.
  44269. Example usage:
  44270. @code
  44271. class MyComponent
  44272. {
  44273. void resized()
  44274. {
  44275. // this will set the child component's x to be 20% of our width, its y
  44276. // to be 30, its width to be 150, and its height to be 50% of our
  44277. // height..
  44278. const PositionedRectangle pos1 ("20% 30 150 50%");
  44279. pos1.applyToComponent (*myChildComponent1);
  44280. // this will inset the child component with a gap of 10 pixels
  44281. // around each of its edges..
  44282. const PositionedRectangle pos2 ("10 10 20M 20M");
  44283. pos2.applyToComponent (*myChildComponent2);
  44284. }
  44285. };
  44286. @endcode
  44287. */
  44288. class JUCE_API PositionedRectangle
  44289. {
  44290. public:
  44291. /** Creates an empty rectangle with all co-ordinates set to zero.
  44292. The default anchor point is top-left; the default
  44293. */
  44294. PositionedRectangle() throw();
  44295. /** Initialises a PositionedRectangle from a saved string version.
  44296. The string must be in the format generated by toString().
  44297. */
  44298. PositionedRectangle (const String& stringVersion) throw();
  44299. /** Creates a copy of another PositionedRectangle. */
  44300. PositionedRectangle (const PositionedRectangle& other) throw();
  44301. /** Copies another PositionedRectangle. */
  44302. PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  44303. /** Destructor. */
  44304. ~PositionedRectangle() throw();
  44305. /** Returns a string version of this position, from which it can later be
  44306. re-generated.
  44307. The format is four co-ordinates, "x y w h".
  44308. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  44309. - If a co-ordinate is proportional to its parent's width or height, it is stored
  44310. as a percentage, e.g. "80%".
  44311. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  44312. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  44313. the parent's right-hand edge.
  44314. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  44315. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  44316. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  44317. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  44318. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  44319. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  44320. has "c" appended to it. So "-50Rc" would mean that this component's
  44321. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  44322. this component's centre should be placed 40% across the parent's width.
  44323. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  44324. the number has "M" appended to it.
  44325. To reload a stored string, use the constructor that takes a string parameter.
  44326. */
  44327. const String toString() const throw();
  44328. /** Calculates the absolute position, given the size of the space that
  44329. it should go in.
  44330. This will work out any proportional distances and sizes relative to the
  44331. target rectangle, and will return the absolute position.
  44332. @see applyToComponent
  44333. */
  44334. const Rectangle<int> getRectangle (const Rectangle<int>& targetSpaceToBeRelativeTo) const throw();
  44335. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  44336. */
  44337. void getRectangleDouble (const Rectangle<int>& targetSpaceToBeRelativeTo,
  44338. double& x,
  44339. double& y,
  44340. double& width,
  44341. double& height) const throw();
  44342. /** This sets the bounds of the given component to this position.
  44343. This is equivalent to writing:
  44344. @code
  44345. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  44346. @endcode
  44347. @see getRectangle, updateFromComponent
  44348. */
  44349. void applyToComponent (Component& comp) const throw();
  44350. /** Updates this object's co-ordinates to match the given rectangle.
  44351. This will set all co-ordinates based on the given rectangle, re-calculating
  44352. any proportional distances, and using the current anchor points.
  44353. So for example if the x co-ordinate mode is currently proportional, this will
  44354. re-calculate x based on the rectangle's relative position within the target
  44355. rectangle's width.
  44356. If the target rectangle's width or height are zero then it may not be possible
  44357. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  44358. will not be changed.
  44359. */
  44360. void updateFrom (const Rectangle<int>& newPosition,
  44361. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44362. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  44363. */
  44364. void updateFromDouble (double x, double y, double width, double height,
  44365. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44366. /** Updates this object's co-ordinates to match the bounds of this component.
  44367. This is equivalent to calling updateFrom() with the component's bounds and
  44368. it parent size.
  44369. If the component doesn't currently have a parent, then proportional co-ordinates
  44370. might not be updated because it would need to know the parent's size to do the
  44371. maths for this.
  44372. */
  44373. void updateFromComponent (const Component& comp) throw();
  44374. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  44375. enum AnchorPoint
  44376. {
  44377. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  44378. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  44379. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  44380. };
  44381. /** Specifies how an x or y co-ordinate should be interpreted. */
  44382. enum PositionMode
  44383. {
  44384. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  44385. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  44386. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  44387. 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. */
  44388. };
  44389. /** Specifies how the width or height should be interpreted. */
  44390. enum SizeMode
  44391. {
  44392. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  44393. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  44394. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  44395. };
  44396. /** Sets all options for all co-ordinates.
  44397. This requires a reference rectangle to be specified, because if you're changing any
  44398. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  44399. the co-ordinates, and will need to know the parent size so it can calculate this.
  44400. */
  44401. void setModes (const AnchorPoint xAnchorMode,
  44402. const PositionMode xPositionMode,
  44403. const AnchorPoint yAnchorMode,
  44404. const PositionMode yPositionMode,
  44405. const SizeMode widthMode,
  44406. const SizeMode heightMode,
  44407. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  44408. /** Returns the anchoring mode for the x co-ordinate.
  44409. To change any of the modes, use setModes().
  44410. */
  44411. AnchorPoint getAnchorPointX() const throw();
  44412. /** Returns the positioning mode for the x co-ordinate.
  44413. To change any of the modes, use setModes().
  44414. */
  44415. PositionMode getPositionModeX() const throw();
  44416. /** Returns the raw x co-ordinate.
  44417. If the x position mode is absolute, then this will be the absolute value. If it's
  44418. proportional, then this will be a fractional proportion, where 1.0 means the full
  44419. width of the parent space.
  44420. */
  44421. double getX() const throw() { return x; }
  44422. /** Sets the raw value of the x co-ordinate.
  44423. See getX() for the meaning of this value.
  44424. */
  44425. void setX (const double newX) throw() { x = newX; }
  44426. /** Returns the anchoring mode for the y co-ordinate.
  44427. To change any of the modes, use setModes().
  44428. */
  44429. AnchorPoint getAnchorPointY() const throw();
  44430. /** Returns the positioning mode for the y co-ordinate.
  44431. To change any of the modes, use setModes().
  44432. */
  44433. PositionMode getPositionModeY() const throw();
  44434. /** Returns the raw y co-ordinate.
  44435. If the y position mode is absolute, then this will be the absolute value. If it's
  44436. proportional, then this will be a fractional proportion, where 1.0 means the full
  44437. height of the parent space.
  44438. */
  44439. double getY() const throw() { return y; }
  44440. /** Sets the raw value of the y co-ordinate.
  44441. See getY() for the meaning of this value.
  44442. */
  44443. void setY (const double newY) throw() { y = newY; }
  44444. /** Returns the mode used to calculate the width.
  44445. To change any of the modes, use setModes().
  44446. */
  44447. SizeMode getWidthMode() const throw();
  44448. /** Returns the raw width value.
  44449. If the width mode is absolute, then this will be the absolute value. If the mode is
  44450. proportional, then this will be a fractional proportion, where 1.0 means the full
  44451. width of the parent space.
  44452. */
  44453. double getWidth() const throw() { return w; }
  44454. /** Sets the raw width value.
  44455. See getWidth() for the details about what this value means.
  44456. */
  44457. void setWidth (const double newWidth) throw() { w = newWidth; }
  44458. /** Returns the mode used to calculate the height.
  44459. To change any of the modes, use setModes().
  44460. */
  44461. SizeMode getHeightMode() const throw();
  44462. /** Returns the raw height value.
  44463. If the height mode is absolute, then this will be the absolute value. If the mode is
  44464. proportional, then this will be a fractional proportion, where 1.0 means the full
  44465. height of the parent space.
  44466. */
  44467. double getHeight() const throw() { return h; }
  44468. /** Sets the raw height value.
  44469. See getHeight() for the details about what this value means.
  44470. */
  44471. void setHeight (const double newHeight) throw() { h = newHeight; }
  44472. /** If the size and position are constance, and wouldn't be affected by changes
  44473. in the parent's size, then this will return true.
  44474. */
  44475. bool isPositionAbsolute() const throw();
  44476. /** Compares two objects. */
  44477. bool operator== (const PositionedRectangle& other) const throw();
  44478. /** Compares two objects. */
  44479. bool operator!= (const PositionedRectangle& other) const throw();
  44480. juce_UseDebuggingNewOperator
  44481. private:
  44482. double x, y, w, h;
  44483. uint8 xMode, yMode, wMode, hMode;
  44484. void addPosDescription (String& result, uint8 mode, double value) const throw();
  44485. void addSizeDescription (String& result, uint8 mode, double value) const throw();
  44486. void decodePosString (const String& s, uint8& mode, double& value) throw();
  44487. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  44488. void applyPosAndSize (double& xOut, double& wOut, double x, double w,
  44489. uint8 xMode, uint8 wMode,
  44490. int parentPos, int parentSize) const throw();
  44491. void updatePosAndSize (double& xOut, double& wOut, double x, double w,
  44492. uint8 xMode, uint8 wMode,
  44493. int parentPos, int parentSize) const throw();
  44494. };
  44495. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  44496. /*** End of inlined file: juce_PositionedRectangle.h ***/
  44497. #endif
  44498. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  44499. #endif
  44500. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  44501. #endif
  44502. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  44503. #endif
  44504. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  44505. /*** Start of inlined file: juce_CameraDevice.h ***/
  44506. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  44507. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  44508. #if JUCE_USE_CAMERA
  44509. /**
  44510. Receives callbacks with images from a CameraDevice.
  44511. @see CameraDevice::addListener
  44512. */
  44513. class CameraImageListener
  44514. {
  44515. public:
  44516. CameraImageListener() {}
  44517. virtual ~CameraImageListener() {}
  44518. /** This method is called when a new image arrives.
  44519. This may be called by any thread, so be careful about thread-safety,
  44520. and make sure that you process the data as quickly as possible to
  44521. avoid glitching!
  44522. */
  44523. virtual void imageReceived (Image& image) = 0;
  44524. };
  44525. /**
  44526. Controls any camera capture devices that might be available.
  44527. Use getAvailableDevices() to list the devices that are attached to the
  44528. system, then call openDevice to open one for use. Once you have a CameraDevice
  44529. object, you can get a viewer component from it, and use its methods to
  44530. stream to a file or capture still-frames.
  44531. */
  44532. class JUCE_API CameraDevice
  44533. {
  44534. public:
  44535. /** Destructor. */
  44536. virtual ~CameraDevice();
  44537. /** Returns a list of the available cameras on this machine.
  44538. You can open one of these devices by calling openDevice().
  44539. */
  44540. static const StringArray getAvailableDevices();
  44541. /** Opens a camera device.
  44542. The index parameter indicates which of the items returned by getAvailableDevices()
  44543. to open.
  44544. The size constraints allow the method to choose between different resolutions if
  44545. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  44546. then these will be ignored.
  44547. */
  44548. static CameraDevice* openDevice (int deviceIndex,
  44549. int minWidth = 128, int minHeight = 64,
  44550. int maxWidth = 1024, int maxHeight = 768);
  44551. /** Returns the name of this device */
  44552. const String getName() const { return name; }
  44553. /** Creates a component that can be used to display a preview of the
  44554. video from this camera.
  44555. */
  44556. Component* createViewerComponent();
  44557. /** Starts recording video to the specified file.
  44558. You should use getFileExtension() to find out the correct extension to
  44559. use for your filename.
  44560. If the file exists, it will be deleted before the recording starts.
  44561. This method may not start recording instantly, so if you need to know the
  44562. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  44563. after the recording has finished.
  44564. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  44565. or may not be used, depending on the driver.
  44566. */
  44567. void startRecordingToFile (const File& file, int quality = 2);
  44568. /** Stops recording, after a call to startRecordingToFile().
  44569. */
  44570. void stopRecording();
  44571. /** Returns the file extension that should be used for the files
  44572. that you pass to startRecordingToFile().
  44573. This may be platform-specific, e.g. ".mov" or ".avi".
  44574. */
  44575. static const String getFileExtension();
  44576. /** After calling stopRecording(), this method can be called to return the timestamp
  44577. of the first frame that was written to the file.
  44578. */
  44579. const Time getTimeOfFirstRecordedFrame() const;
  44580. /** Adds a listener to receive images from the camera.
  44581. Be very careful not to delete the listener without first removing it by calling
  44582. removeListener().
  44583. */
  44584. void addListener (CameraImageListener* listenerToAdd);
  44585. /** Removes a listener that was previously added with addListener().
  44586. */
  44587. void removeListener (CameraImageListener* listenerToRemove);
  44588. juce_UseDebuggingNewOperator
  44589. protected:
  44590. /** @internal */
  44591. CameraDevice (const String& name, int index);
  44592. private:
  44593. void* internal;
  44594. bool isRecording;
  44595. String name;
  44596. CameraDevice (const CameraDevice&);
  44597. CameraDevice& operator= (const CameraDevice&);
  44598. };
  44599. #endif
  44600. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  44601. /*** End of inlined file: juce_CameraDevice.h ***/
  44602. #endif
  44603. #ifndef __JUCE_IMAGE_JUCEHEADER__
  44604. #endif
  44605. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  44606. /*** Start of inlined file: juce_ImageCache.h ***/
  44607. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  44608. #define __JUCE_IMAGECACHE_JUCEHEADER__
  44609. /**
  44610. A global cache of images that have been loaded from files or memory.
  44611. If you're loading an image and may need to use the image in more than one
  44612. place, this is used to allow the same image to be shared rather than loading
  44613. multiple copies into memory.
  44614. Another advantage is that after images are released, they will be kept in
  44615. memory for a few seconds before it is actually deleted, so if you're repeatedly
  44616. loading/deleting the same image, it'll reduce the chances of having to reload it
  44617. each time.
  44618. @see Image, ImageFileFormat
  44619. */
  44620. class JUCE_API ImageCache : private DeletedAtShutdown,
  44621. private Timer
  44622. {
  44623. public:
  44624. /** Loads an image from a file, (or just returns the image if it's already cached).
  44625. If the cache already contains an image that was loaded from this file,
  44626. that image will be returned. Otherwise, this method will try to load the
  44627. file, add it to the cache, and return it.
  44628. It's very important not to delete the image that is returned - instead use
  44629. the ImageCache::release() method.
  44630. Also, remember that the image returned is shared, so drawing into it might
  44631. affect other things that are using it!
  44632. @param file the file to try to load
  44633. @returns the image, or null if it there was an error loading it
  44634. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  44635. */
  44636. static Image* getFromFile (const File& file);
  44637. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  44638. If the cache already contains an image that was loaded from this block of memory,
  44639. that image will be returned. Otherwise, this method will try to load the
  44640. file, add it to the cache, and return it.
  44641. It's very important not to delete the image that is returned - instead use
  44642. the ImageCache::release() method.
  44643. Also, remember that the image returned is shared, so drawing into it might
  44644. affect other things that are using it!
  44645. @param imageData the block of memory containing the image data
  44646. @param dataSize the data size in bytes
  44647. @returns the image, or null if it there was an error loading it
  44648. @see release, getFromMemory, getFromCache, ImageFileFormat::loadFrom
  44649. */
  44650. static Image* getFromMemory (const void* imageData, int dataSize);
  44651. /** Releases an image that was previously created by the ImageCache.
  44652. If an image has been returned by the getFromFile() or getFromMemory() methods,
  44653. it mustn't be deleted directly, but should be released with this method
  44654. instead.
  44655. @see getFromFile, getFromMemory
  44656. */
  44657. static void release (Image* imageToRelease);
  44658. /** Releases an image if it's in the cache, or deletes it if it isn't cached.
  44659. This is a handy function to use if you want to delete an image but are afraid that
  44660. it might be cached.
  44661. */
  44662. static void releaseOrDelete (Image* imageToRelease);
  44663. /** Checks whether an image is in the cache or not.
  44664. @returns true if the image is currently in the cache
  44665. */
  44666. static bool isImageInCache (Image* imageToLookFor);
  44667. /** Increments the reference-count for a cached image.
  44668. If the image isn't in the cache, this method won't do anything.
  44669. */
  44670. static void incReferenceCount (Image* image);
  44671. /** Checks the cache for an image with a particular hashcode.
  44672. If there's an image in the cache with this hashcode, it will be returned,
  44673. otherwise it will return zero.
  44674. If an image is returned, it must be released with the release() method
  44675. when no longer needed, to maintain the correct reference counts.
  44676. @param hashCode the hash code that would have been associated with the
  44677. image by addImageToCache()
  44678. @see addImageToCache
  44679. */
  44680. static Image* getFromHashCode (int64 hashCode);
  44681. /** Adds an image to the cache with a user-defined hash-code.
  44682. After calling this, responsibilty for deleting the image will be taken
  44683. by the ImageCache.
  44684. The image will be initially be given a reference count of 1, so call
  44685. the release() method to delete it.
  44686. @param image the image to add
  44687. @param hashCode the hash-code to associate with it
  44688. @see getFromHashCode
  44689. */
  44690. static void addImageToCache (Image* image, int64 hashCode);
  44691. /** Changes the amount of time before an unused image will be removed from the cache.
  44692. By default this is about 5 seconds.
  44693. */
  44694. static void setCacheTimeout (int millisecs);
  44695. juce_UseDebuggingNewOperator
  44696. private:
  44697. CriticalSection lock;
  44698. struct Item;
  44699. friend class ScopedPointer<Item>;
  44700. friend class OwnedArray<Item>;
  44701. OwnedArray<Item> images;
  44702. static ImageCache* instance;
  44703. static int cacheTimeout;
  44704. ImageCache();
  44705. ImageCache (const ImageCache&);
  44706. ImageCache& operator= (const ImageCache&);
  44707. ~ImageCache();
  44708. void timerCallback();
  44709. };
  44710. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  44711. /*** End of inlined file: juce_ImageCache.h ***/
  44712. #endif
  44713. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  44714. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  44715. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  44716. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  44717. /**
  44718. Represents a filter kernel to use in convoluting an image.
  44719. @see Image::applyConvolution
  44720. */
  44721. class JUCE_API ImageConvolutionKernel
  44722. {
  44723. public:
  44724. /** Creates an empty convulution kernel.
  44725. @param size the length of each dimension of the kernel, so e.g. if the size
  44726. is 5, it will create a 5x5 kernel
  44727. */
  44728. ImageConvolutionKernel (int size);
  44729. /** Destructor. */
  44730. ~ImageConvolutionKernel();
  44731. /** Resets all values in the kernel to zero. */
  44732. void clear();
  44733. /** Returns one of the kernel values. */
  44734. float getKernelValue (int x, int y) const throw();
  44735. /** Sets the value of a specific cell in the kernel.
  44736. The x and y parameters must be in the range 0 < x < getKernelSize().
  44737. @see setOverallSum
  44738. */
  44739. void setKernelValue (int x, int y, float value) throw();
  44740. /** Rescales all values in the kernel to make the total add up to a fixed value.
  44741. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  44742. */
  44743. void setOverallSum (float desiredTotalSum);
  44744. /** Multiplies all values in the kernel by a value. */
  44745. void rescaleAllValues (float multiplier);
  44746. /** Intialises the kernel for a gaussian blur.
  44747. @param blurRadius this may be larger or smaller than the kernel's actual
  44748. size but this will obviously be wasteful or clip at the
  44749. edges. Ideally the kernel should be just larger than
  44750. (blurRadius * 2).
  44751. */
  44752. void createGaussianBlur (float blurRadius);
  44753. /** Returns the size of the kernel.
  44754. E.g. if it's a 3x3 kernel, this returns 3.
  44755. */
  44756. int getKernelSize() const { return size; }
  44757. /** Applies the kernel to an image.
  44758. @param destImage the image that will receive the resultant convoluted pixels.
  44759. @param sourceImage an optional source image to read from - if this is 0, then the
  44760. destination image will be used as the source. If an image is
  44761. specified, it must be exactly the same size and type as the destination
  44762. image.
  44763. @param destinationArea the region of the image to apply the filter to
  44764. */
  44765. void applyToImage (Image& destImage,
  44766. const Image* sourceImage,
  44767. const Rectangle<int>& destinationArea) const;
  44768. juce_UseDebuggingNewOperator
  44769. private:
  44770. HeapBlock <float> values;
  44771. const int size;
  44772. // no reason not to implement these one day..
  44773. ImageConvolutionKernel (const ImageConvolutionKernel&);
  44774. ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  44775. };
  44776. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  44777. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  44778. #endif
  44779. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  44780. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  44781. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  44782. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  44783. /**
  44784. Base-class for codecs that can read and write image file formats such
  44785. as PNG, JPEG, etc.
  44786. This class also contains static methods to make it easy to load images
  44787. from files, streams or from memory.
  44788. @see Image, ImageCache
  44789. */
  44790. class JUCE_API ImageFileFormat
  44791. {
  44792. protected:
  44793. /** Creates an ImageFormat. */
  44794. ImageFileFormat() {}
  44795. public:
  44796. /** Destructor. */
  44797. virtual ~ImageFileFormat() {}
  44798. /** Returns a description of this file format.
  44799. E.g. "JPEG", "PNG"
  44800. */
  44801. virtual const String getFormatName() = 0;
  44802. /** Returns true if the given stream seems to contain data that this format
  44803. understands.
  44804. The format class should only read the first few bytes of the stream and sniff
  44805. for header bytes that it understands.
  44806. @see decodeImage
  44807. */
  44808. virtual bool canUnderstand (InputStream& input) = 0;
  44809. /** Tries to decode and return an image from the given stream.
  44810. This will be called for an image format after calling its canUnderStand() method
  44811. to see if it can handle the stream.
  44812. @param input the stream to read the data from. The stream will be positioned
  44813. at the start of the image data (but this may not necessarily
  44814. be position 0)
  44815. @returns the image that was decoded, or 0 if it fails. It's the
  44816. caller's responsibility to delete this image when no longer needed.
  44817. @see loadFrom
  44818. */
  44819. virtual Image* decodeImage (InputStream& input) = 0;
  44820. /** Attempts to write an image to a stream.
  44821. To specify extra information like encoding quality, there will be appropriate parameters
  44822. in the subclasses of the specific file types.
  44823. @returns true if it nothing went wrong.
  44824. */
  44825. virtual bool writeImageToStream (const Image& sourceImage,
  44826. OutputStream& destStream) = 0;
  44827. /** Tries the built-in decoders to see if it can find one to read this stream.
  44828. There are currently built-in decoders for PNG, JPEG and GIF formats.
  44829. The object that is returned should not be deleted by the caller.
  44830. @see canUnderstand, decodeImage, loadFrom
  44831. */
  44832. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  44833. /** Tries to load an image from a stream.
  44834. This will use the findImageFormatForStream() method to locate a suitable
  44835. codec, and use that to load the image.
  44836. @returns the image that was decoded, or 0 if it fails to load one. It's the
  44837. caller's responsibility to delete this image when no longer needed.
  44838. */
  44839. static Image* loadFrom (InputStream& input);
  44840. /** Tries to load an image from a file.
  44841. This will use the findImageFormatForStream() method to locate a suitable
  44842. codec, and use that to load the image.
  44843. @returns the image that was decoded, or 0 if it fails to load one. It's the
  44844. caller's responsibility to delete this image when no longer needed.
  44845. */
  44846. static Image* loadFrom (const File& file);
  44847. /** Tries to load an image from a block of raw image data.
  44848. This will use the findImageFormatForStream() method to locate a suitable
  44849. codec, and use that to load the image.
  44850. @returns the image that was decoded, or 0 if it fails to load one. It's the
  44851. caller's responsibility to delete this image when no longer needed.
  44852. */
  44853. static Image* loadFrom (const void* rawData,
  44854. const int numBytesOfData);
  44855. };
  44856. /**
  44857. A type of ImageFileFormat for reading and writing PNG files.
  44858. @see ImageFileFormat, JPEGImageFormat
  44859. */
  44860. class JUCE_API PNGImageFormat : public ImageFileFormat
  44861. {
  44862. public:
  44863. PNGImageFormat();
  44864. ~PNGImageFormat();
  44865. const String getFormatName();
  44866. bool canUnderstand (InputStream& input);
  44867. Image* decodeImage (InputStream& input);
  44868. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  44869. };
  44870. /**
  44871. A type of ImageFileFormat for reading and writing JPEG files.
  44872. @see ImageFileFormat, PNGImageFormat
  44873. */
  44874. class JUCE_API JPEGImageFormat : public ImageFileFormat
  44875. {
  44876. public:
  44877. JPEGImageFormat();
  44878. ~JPEGImageFormat();
  44879. /** Specifies the quality to be used when writing a JPEG file.
  44880. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  44881. any negative value is "default" quality
  44882. */
  44883. void setQuality (const float newQuality);
  44884. const String getFormatName();
  44885. bool canUnderstand (InputStream& input);
  44886. Image* decodeImage (InputStream& input);
  44887. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  44888. private:
  44889. float quality;
  44890. };
  44891. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  44892. /*** End of inlined file: juce_ImageFileFormat.h ***/
  44893. #endif
  44894. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  44895. #endif
  44896. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  44897. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  44898. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  44899. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  44900. /**
  44901. A class to take care of the logic involved with the loading/saving of some kind
  44902. of document.
  44903. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  44904. functions you need for documents that get saved to a file, so this class attempts
  44905. to abstract most of the boring stuff.
  44906. Your subclass should just implement all the pure virtual methods, and you can
  44907. then use the higher-level public methods to do the load/save dialogs, to warn the user
  44908. about overwriting files, etc.
  44909. The document object keeps track of whether it has changed since it was last saved or
  44910. loaded, so when you change something, call its changed() method. This will set a
  44911. flag so it knows it needs saving, and will also broadcast a change message using the
  44912. ChangeBroadcaster base class.
  44913. @see ChangeBroadcaster
  44914. */
  44915. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  44916. {
  44917. public:
  44918. /** Creates a FileBasedDocument.
  44919. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  44920. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  44921. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  44922. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  44923. */
  44924. FileBasedDocument (const String& fileExtension,
  44925. const String& fileWildCard,
  44926. const String& openFileDialogTitle,
  44927. const String& saveFileDialogTitle);
  44928. /** Destructor. */
  44929. virtual ~FileBasedDocument();
  44930. /** Returns true if the changed() method has been called since the file was
  44931. last saved or loaded.
  44932. @see resetChangedFlag, changed
  44933. */
  44934. bool hasChangedSinceSaved() const { return changedSinceSave; }
  44935. /** Called to indicate that the document has changed and needs saving.
  44936. This method will also trigger a change message to be sent out using the
  44937. ChangeBroadcaster base class.
  44938. After calling the method, the hasChangedSinceSaved() method will return true, until
  44939. it is reset either by saving to a file or using the resetChangedFlag() method.
  44940. @see hasChangedSinceSaved, resetChangedFlag
  44941. */
  44942. virtual void changed();
  44943. /** Sets the state of the 'changed' flag.
  44944. The 'changed' flag is set to true when the changed() method is called - use this method
  44945. to reset it or to set it without also broadcasting a change message.
  44946. @see changed, hasChangedSinceSaved
  44947. */
  44948. void setChangedFlag (bool hasChanged);
  44949. /** Tries to open a file.
  44950. If the file opens correctly, the document's file (see the getFile() method) is set
  44951. to this new one; if it fails, the document's file is left unchanged, and optionally
  44952. a message box is shown telling the user there was an error.
  44953. @returns true if the new file loaded successfully
  44954. @see loadDocument, loadFromUserSpecifiedFile
  44955. */
  44956. bool loadFrom (const File& fileToLoadFrom,
  44957. bool showMessageOnFailure);
  44958. /** Asks the user for a file and tries to load it.
  44959. This will pop up a dialog box using the title, file extension and
  44960. wildcard specified in the document's constructor, and asks the user
  44961. for a file. If they pick one, the loadFrom() method is used to
  44962. try to load it, optionally showing a message if it fails.
  44963. @returns true if a file was loaded; false if the user cancelled or if they
  44964. picked a file which failed to load correctly
  44965. @see loadFrom
  44966. */
  44967. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  44968. /** A set of possible outcomes of one of the save() methods
  44969. */
  44970. enum SaveResult
  44971. {
  44972. savedOk = 0, /**< indicates that a file was saved successfully. */
  44973. userCancelledSave, /**< indicates that the user aborted the save operation. */
  44974. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  44975. };
  44976. /** Tries to save the document to the last file it was saved or loaded from.
  44977. This will always try to write to the file, even if the document isn't flagged as
  44978. having changed.
  44979. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  44980. true, it will prompt the user to pick a file, as if
  44981. saveAsInteractive() was called.
  44982. @param showMessageOnFailure if true it will show a warning message when if the
  44983. save operation fails
  44984. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  44985. */
  44986. SaveResult save (bool askUserForFileIfNotSpecified,
  44987. bool showMessageOnFailure);
  44988. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  44989. it if they say yes.
  44990. If you've got a document open and want to close it (e.g. to quit the app), this is the
  44991. method to call.
  44992. If the document doesn't need saving it'll return the value savedOk so
  44993. you can go ahead and delete the document.
  44994. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  44995. return savedOk, so again, you can safely delete the document.
  44996. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  44997. close-document operation.
  44998. And if they click "save changes", it'll try to save and either return savedOk, or
  44999. failedToWriteToFile if there was a problem.
  45000. @see save, saveAs, saveAsInteractive
  45001. */
  45002. SaveResult saveIfNeededAndUserAgrees();
  45003. /** Tries to save the document to a specified file.
  45004. If this succeeds, it'll also change the document's internal file (as returned by
  45005. the getFile() method). If it fails, the file will be left unchanged.
  45006. @param newFile the file to try to write to
  45007. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45008. the user first if they want to overwrite it
  45009. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  45010. use the saveAsInteractive() method to ask the user for a
  45011. filename
  45012. @param showMessageOnFailure if true and the write operation fails, it'll show
  45013. a message box to warn the user
  45014. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  45015. */
  45016. SaveResult saveAs (const File& newFile,
  45017. bool warnAboutOverwritingExistingFiles,
  45018. bool askUserForFileIfNotSpecified,
  45019. bool showMessageOnFailure);
  45020. /** Prompts the user for a filename and tries to save to it.
  45021. This will pop up a dialog box using the title, file extension and
  45022. wildcard specified in the document's constructor, and asks the user
  45023. for a file. If they pick one, the saveAs() method is used to try to save
  45024. to this file.
  45025. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45026. the user first if they want to overwrite it
  45027. @see saveIfNeededAndUserAgrees, save, saveAs
  45028. */
  45029. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  45030. /** Returns the file that this document was last successfully saved or loaded from.
  45031. When the document object is created, this will be set to File::nonexistent.
  45032. It is changed when one of the load or save methods is used, or when setFile()
  45033. is used to explicitly set it.
  45034. */
  45035. const File getFile() const { return documentFile; }
  45036. /** Sets the file that this document thinks it was loaded from.
  45037. This won't actually load anything - it just changes the file stored internally.
  45038. @see getFile
  45039. */
  45040. void setFile (const File& newFile);
  45041. protected:
  45042. /** Overload this to return the title of the document.
  45043. This is used in message boxes, filenames and file choosers, so it should be
  45044. something sensible.
  45045. */
  45046. virtual const String getDocumentTitle() = 0;
  45047. /** This method should try to load your document from the given file.
  45048. If it fails, it should return an error message. If it succeeds, it should return
  45049. an empty string.
  45050. */
  45051. virtual const String loadDocument (const File& file) = 0;
  45052. /** This method should try to write your document to the given file.
  45053. If it fails, it should return an error message. If it succeeds, it should return
  45054. an empty string.
  45055. */
  45056. virtual const String saveDocument (const File& file) = 0;
  45057. /** This is used for dialog boxes to make them open at the last folder you
  45058. were using.
  45059. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45060. the last document that was used - you might want to store this value
  45061. in a static variable, or even in your application's properties. It should
  45062. be a global setting rather than a property of this object.
  45063. This method works very well in conjunction with a RecentlyOpenedFilesList
  45064. object to manage your recent-files list.
  45065. As a default value, it's ok to return File::nonexistent, and the document
  45066. object will use a sensible one instead.
  45067. @see RecentlyOpenedFilesList
  45068. */
  45069. virtual const File getLastDocumentOpened() = 0;
  45070. /** This is used for dialog boxes to make them open at the last folder you
  45071. were using.
  45072. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45073. the last document that was used - you might want to store this value
  45074. in a static variable, or even in your application's properties. It should
  45075. be a global setting rather than a property of this object.
  45076. This method works very well in conjunction with a RecentlyOpenedFilesList
  45077. object to manage your recent-files list.
  45078. @see RecentlyOpenedFilesList
  45079. */
  45080. virtual void setLastDocumentOpened (const File& file) = 0;
  45081. public:
  45082. juce_UseDebuggingNewOperator
  45083. private:
  45084. File documentFile;
  45085. bool changedSinceSave;
  45086. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  45087. FileBasedDocument (const FileBasedDocument&);
  45088. FileBasedDocument& operator= (const FileBasedDocument&);
  45089. };
  45090. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45091. /*** End of inlined file: juce_FileBasedDocument.h ***/
  45092. #endif
  45093. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  45094. #endif
  45095. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45096. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45097. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45098. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45099. /**
  45100. Manages a set of files for use as a list of recently-opened documents.
  45101. This is a handy class for holding your list of recently-opened documents, with
  45102. helpful methods for things like purging any non-existent files, automatically
  45103. adding them to a menu, and making persistence easy.
  45104. @see File, FileBasedDocument
  45105. */
  45106. class JUCE_API RecentlyOpenedFilesList
  45107. {
  45108. public:
  45109. /** Creates an empty list.
  45110. */
  45111. RecentlyOpenedFilesList();
  45112. /** Destructor. */
  45113. ~RecentlyOpenedFilesList();
  45114. /** Sets a limit for the number of files that will be stored in the list.
  45115. When addFile() is called, then if there is no more space in the list, the
  45116. least-recently added file will be dropped.
  45117. @see getMaxNumberOfItems
  45118. */
  45119. void setMaxNumberOfItems (int newMaxNumber);
  45120. /** Returns the number of items that this list will store.
  45121. @see setMaxNumberOfItems
  45122. */
  45123. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  45124. /** Returns the number of files in the list.
  45125. The most recently added file is always at index 0.
  45126. */
  45127. int getNumFiles() const;
  45128. /** Returns one of the files in the list.
  45129. The most recently added file is always at index 0.
  45130. */
  45131. const File getFile (int index) const;
  45132. /** Returns an array of all the absolute pathnames in the list.
  45133. */
  45134. const StringArray& getAllFilenames() const throw() { return files; }
  45135. /** Clears all the files from the list. */
  45136. void clear();
  45137. /** Adds a file to the list.
  45138. The file will be added at index 0. If this file is already in the list, it will
  45139. be moved up to index 0, but a file can only appear once in the list.
  45140. If the list already contains the maximum number of items that is permitted, the
  45141. least-recently added file will be dropped from the end.
  45142. */
  45143. void addFile (const File& file);
  45144. /** Checks each of the files in the list, removing any that don't exist.
  45145. You might want to call this after reloading a list of files, or before putting them
  45146. on a menu.
  45147. */
  45148. void removeNonExistentFiles();
  45149. /** Adds entries to a menu, representing each of the files in the list.
  45150. This is handy for creating an "open recent file..." menu in your app. The
  45151. menu items are numbered consecutively starting with the baseItemId value,
  45152. and can either be added as complete pathnames, or just the last part of the
  45153. filename.
  45154. If dontAddNonExistentFiles is true, then each file will be checked and only those
  45155. that exist will be added.
  45156. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  45157. pointers to file objects. Any files that appear in this list will not be added to the
  45158. menu - the reason for this is that you might have a number of files already open, so
  45159. might not want these to be shown in the menu.
  45160. It returns the number of items that were added.
  45161. */
  45162. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  45163. int baseItemId,
  45164. bool showFullPaths,
  45165. bool dontAddNonExistentFiles,
  45166. const File** filesToAvoid = 0);
  45167. /** Returns a string that encapsulates all the files in the list.
  45168. The string that is returned can later be passed into restoreFromString() in
  45169. order to recreate the list. This is handy for persisting your list, e.g. in
  45170. a PropertiesFile object.
  45171. @see restoreFromString
  45172. */
  45173. const String toString() const;
  45174. /** Restores the list from a previously stringified version of the list.
  45175. Pass in a stringified version created with toString() in order to persist/restore
  45176. your list.
  45177. @see toString
  45178. */
  45179. void restoreFromString (const String& stringifiedVersion);
  45180. juce_UseDebuggingNewOperator
  45181. private:
  45182. StringArray files;
  45183. int maxNumberOfItems;
  45184. };
  45185. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45186. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45187. #endif
  45188. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45189. #endif
  45190. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45191. /*** Start of inlined file: juce_SystemClipboard.h ***/
  45192. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45193. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45194. /**
  45195. Handles reading/writing to the system's clipboard.
  45196. */
  45197. class JUCE_API SystemClipboard
  45198. {
  45199. public:
  45200. /** Copies a string of text onto the clipboard */
  45201. static void copyTextToClipboard (const String& text);
  45202. /** Gets the current clipboard's contents.
  45203. Obviously this might have come from another app, so could contain
  45204. anything..
  45205. */
  45206. static const String getTextFromClipboard();
  45207. };
  45208. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45209. /*** End of inlined file: juce_SystemClipboard.h ***/
  45210. #endif
  45211. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  45212. #endif
  45213. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  45214. #endif
  45215. #endif
  45216. /*** End of inlined file: juce_app_includes.h ***/
  45217. #endif
  45218. #if JUCE_MSVC
  45219. #pragma warning (pop)
  45220. #pragma pack (pop)
  45221. #endif
  45222. END_JUCE_NAMESPACE
  45223. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  45224. #ifdef JUCE_NAMESPACE
  45225. // this will obviously save a lot of typing, but can be disabled by
  45226. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  45227. using namespace JUCE_NAMESPACE;
  45228. /* On the Mac, these symbols are defined in the Mac libraries, so
  45229. these macros make it easier to reference them without writing out
  45230. the namespace every time.
  45231. If you run into difficulties where these macros interfere with the contents
  45232. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  45233. the comments in that file for more information.
  45234. */
  45235. #if (JUCE_MAC || JUCE_IPHONE) && ! JUCE_DONT_DEFINE_MACROS
  45236. #define Component JUCE_NAMESPACE::Component
  45237. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  45238. #define Point JUCE_NAMESPACE::Point
  45239. #define Button JUCE_NAMESPACE::Button
  45240. #endif
  45241. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  45242. it easier to use the juce version explicitly.
  45243. If you run into difficulties where this macro interferes with other 3rd party header
  45244. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  45245. file for more information.
  45246. */
  45247. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  45248. #define Rectangle JUCE_NAMESPACE::Rectangle
  45249. #endif
  45250. #endif
  45251. #endif
  45252. /* Easy autolinking to the right JUCE libraries under win32.
  45253. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  45254. including this header file.
  45255. */
  45256. #if JUCE_MSVC
  45257. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  45258. /** If you want your application to link to Juce as a DLL instead of
  45259. a static library (on win32), just define the JUCE_DLL macro before
  45260. including juce.h
  45261. */
  45262. #ifdef JUCE_DLL
  45263. #if JUCE_DEBUG
  45264. #define AUTOLINKEDLIB "JUCE_debug.lib"
  45265. #else
  45266. #define AUTOLINKEDLIB "JUCE.lib"
  45267. #endif
  45268. #else
  45269. #if JUCE_DEBUG
  45270. #ifdef _WIN64
  45271. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  45272. #else
  45273. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  45274. #endif
  45275. #else
  45276. #ifdef _WIN64
  45277. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  45278. #else
  45279. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  45280. #endif
  45281. #endif
  45282. #endif
  45283. #pragma comment(lib, AUTOLINKEDLIB)
  45284. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  45285. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  45286. #endif
  45287. // Auto-link the other win32 libs that are needed by library calls..
  45288. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  45289. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  45290. // Auto-links to various win32 libs that are needed by library calls..
  45291. #pragma comment(lib, "kernel32.lib")
  45292. #pragma comment(lib, "user32.lib")
  45293. #pragma comment(lib, "shell32.lib")
  45294. #pragma comment(lib, "gdi32.lib")
  45295. #pragma comment(lib, "vfw32.lib")
  45296. #pragma comment(lib, "comdlg32.lib")
  45297. #pragma comment(lib, "winmm.lib")
  45298. #pragma comment(lib, "wininet.lib")
  45299. #pragma comment(lib, "ole32.lib")
  45300. #pragma comment(lib, "oleaut32.lib")
  45301. #pragma comment(lib, "advapi32.lib")
  45302. #pragma comment(lib, "ws2_32.lib")
  45303. #pragma comment(lib, "comsupp.lib")
  45304. #pragma comment(lib, "version.lib")
  45305. #if JUCE_OPENGL
  45306. #pragma comment(lib, "OpenGL32.Lib")
  45307. #pragma comment(lib, "GlU32.Lib")
  45308. #endif
  45309. #if JUCE_QUICKTIME
  45310. #pragma comment (lib, "QTMLClient.lib")
  45311. #endif
  45312. #if JUCE_USE_CAMERA
  45313. #pragma comment (lib, "Strmiids.lib")
  45314. #pragma comment (lib, "wmvcore.lib")
  45315. #endif
  45316. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  45317. #endif
  45318. #endif
  45319. #endif
  45320. /*
  45321. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  45322. AppSubClass is the name of a class derived from JUCEApplication.
  45323. See the JUCEApplication class documentation (juce_Application.h) for more details.
  45324. */
  45325. #if defined (JUCE_GCC) || defined (__MWERKS__)
  45326. #define START_JUCE_APPLICATION(AppClass) \
  45327. int main (int argc, char* argv[]) \
  45328. { \
  45329. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv, new AppClass()); \
  45330. }
  45331. #elif JUCE_WINDOWS
  45332. #ifdef _CONSOLE
  45333. #define START_JUCE_APPLICATION(AppClass) \
  45334. int main (int, char* argv[]) \
  45335. { \
  45336. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45337. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45338. }
  45339. #elif ! defined (_AFXDLL)
  45340. #ifdef _WINDOWS_
  45341. #define START_JUCE_APPLICATION(AppClass) \
  45342. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  45343. { \
  45344. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45345. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45346. }
  45347. #else
  45348. #define START_JUCE_APPLICATION(AppClass) \
  45349. int __stdcall WinMain (int, int, const char*, int) \
  45350. { \
  45351. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  45352. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  45353. }
  45354. #endif
  45355. #endif
  45356. #endif
  45357. #endif // __JUCE_JUCEHEADER__
  45358. /*** End of inlined file: juce.h ***/
  45359. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__