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.

61316 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 39
  46. /** Current Juce version number.
  47. Bits 16 to 32 = major version.
  48. Bits 8 to 16 = minor version.
  49. Bits 0 to 8 = point release (not currently used).
  50. See also SystemStats::getJUCEVersion() for a string version.
  51. */
  52. #define JUCE_VERSION ((JUCE_MAJOR_VERSION << 16) + (JUCE_MINOR_VERSION << 8) + JUCE_BUILDNUMBER)
  53. /*** Start of inlined file: juce_TargetPlatform.h ***/
  54. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  55. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  56. /* This file figures out which platform is being built, and defines some macros
  57. that the rest of the code can use for OS-specific compilation.
  58. Macros that will be set here are:
  59. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  60. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  61. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  62. - Either JUCE_INTEL or JUCE_PPC
  63. - Either JUCE_GCC or JUCE_MSVC
  64. */
  65. #if (defined (_WIN32) || defined (_WIN64))
  66. #define JUCE_WIN32 1
  67. #define JUCE_WINDOWS 1
  68. #elif defined (LINUX) || defined (__linux__)
  69. #define JUCE_LINUX 1
  70. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  71. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  72. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  73. #define JUCE_IPHONE 1
  74. #else
  75. #define JUCE_MAC 1
  76. #endif
  77. #else
  78. #error "Unknown platform!"
  79. #endif
  80. #if JUCE_WINDOWS
  81. #ifdef _MSC_VER
  82. #ifdef _WIN64
  83. #define JUCE_64BIT 1
  84. #else
  85. #define JUCE_32BIT 1
  86. #endif
  87. #endif
  88. #ifdef _DEBUG
  89. #define JUCE_DEBUG 1
  90. #endif
  91. #ifdef __MINGW32__
  92. #define JUCE_MINGW 1
  93. #endif
  94. /** If defined, this indicates that the processor is little-endian. */
  95. #define JUCE_LITTLE_ENDIAN 1
  96. #define JUCE_INTEL 1
  97. #endif
  98. #if JUCE_MAC
  99. #ifndef NDEBUG
  100. #define JUCE_DEBUG 1
  101. #endif
  102. #ifdef __LITTLE_ENDIAN__
  103. #define JUCE_LITTLE_ENDIAN 1
  104. #else
  105. #define JUCE_BIG_ENDIAN 1
  106. #endif
  107. #if defined (__ppc__) || defined (__ppc64__)
  108. #define JUCE_PPC 1
  109. #else
  110. #define JUCE_INTEL 1
  111. #endif
  112. #ifdef __LP64__
  113. #define JUCE_64BIT 1
  114. #else
  115. #define JUCE_32BIT 1
  116. #endif
  117. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  118. #error "Building for OSX 10.3 is no longer supported!"
  119. #endif
  120. #ifndef MAC_OS_X_VERSION_10_5
  121. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  122. #endif
  123. #endif
  124. #if JUCE_IPHONE
  125. #ifndef NDEBUG
  126. #define JUCE_DEBUG 1
  127. #endif
  128. #ifdef __LITTLE_ENDIAN__
  129. #define JUCE_LITTLE_ENDIAN 1
  130. #else
  131. #define JUCE_BIG_ENDIAN 1
  132. #endif
  133. #endif
  134. #if JUCE_LINUX
  135. #ifdef _DEBUG
  136. #define JUCE_DEBUG 1
  137. #endif
  138. // Allow override for big-endian Linux platforms
  139. #ifndef JUCE_BIG_ENDIAN
  140. #define JUCE_LITTLE_ENDIAN 1
  141. #endif
  142. #if defined (__LP64__) || defined (_LP64)
  143. #define JUCE_64BIT 1
  144. #else
  145. #define JUCE_32BIT 1
  146. #endif
  147. #define JUCE_INTEL 1
  148. #endif
  149. // Compiler type macros.
  150. #ifdef __GNUC__
  151. #define JUCE_GCC 1
  152. #elif defined (_MSC_VER)
  153. #define JUCE_MSVC 1
  154. #if _MSC_VER >= 1400
  155. #define JUCE_USE_INTRINSICS 1
  156. #endif
  157. #else
  158. #error unknown compiler
  159. #endif
  160. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  161. /*** End of inlined file: juce_TargetPlatform.h ***/
  162. // (sets up the various JUCE_WINDOWS, JUCE_MAC, etc flags)
  163. /*** Start of inlined file: juce_Config.h ***/
  164. #ifndef __JUCE_CONFIG_JUCEHEADER__
  165. #define __JUCE_CONFIG_JUCEHEADER__
  166. /*
  167. This file contains macros that enable/disable various JUCE features.
  168. */
  169. /** The name of the namespace that all Juce classes and functions will be
  170. put inside. If this is not defined, no namespace will be used.
  171. */
  172. #ifndef JUCE_NAMESPACE
  173. #define JUCE_NAMESPACE juce
  174. #endif
  175. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  176. project settings, but if you define this value, you can override this to force
  177. it to be true or false.
  178. */
  179. #ifndef JUCE_FORCE_DEBUG
  180. //#define JUCE_FORCE_DEBUG 0
  181. #endif
  182. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  183. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  184. Enabling it will also leave this turned on in release builds. When it's disabled,
  185. however, the jassert and jassertfalse macros will not be compiled in a
  186. release build.
  187. @see jassert, jassertfalse, Logger
  188. */
  189. #ifndef JUCE_LOG_ASSERTIONS
  190. #define JUCE_LOG_ASSERTIONS 0
  191. #endif
  192. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  193. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  194. on your Windows build machine.
  195. See the comments in the ASIOAudioIODevice class's header file for more
  196. info about this.
  197. */
  198. #ifndef JUCE_ASIO
  199. #define JUCE_ASIO 0
  200. #endif
  201. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  202. */
  203. #ifndef JUCE_WASAPI
  204. #define JUCE_WASAPI 0
  205. #endif
  206. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  207. */
  208. #ifndef JUCE_DIRECTSOUND
  209. #define JUCE_DIRECTSOUND 1
  210. #endif
  211. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  212. #ifndef JUCE_ALSA
  213. #define JUCE_ALSA 1
  214. #endif
  215. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  216. #ifndef JUCE_JACK
  217. #define JUCE_JACK 0
  218. #endif
  219. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  220. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  221. installed, and its header files will need to be on your include path.
  222. */
  223. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IPHONE || (JUCE_WINDOWS && ! JUCE_MSVC))
  224. #define JUCE_QUICKTIME 0
  225. #endif
  226. #if (JUCE_IPHONE || JUCE_LINUX) && JUCE_QUICKTIME
  227. #undef JUCE_QUICKTIME
  228. #endif
  229. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  230. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  231. */
  232. #ifndef JUCE_OPENGL
  233. #define JUCE_OPENGL 1
  234. #endif
  235. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  236. If your app doesn't need to read FLAC files, you might want to disable this to
  237. reduce the size of your codebase and build time.
  238. */
  239. #ifndef JUCE_USE_FLAC
  240. #define JUCE_USE_FLAC 1
  241. #endif
  242. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  243. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  244. reduce the size of your codebase and build time.
  245. */
  246. #ifndef JUCE_USE_OGGVORBIS
  247. #define JUCE_USE_OGGVORBIS 1
  248. #endif
  249. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  250. Unless you're using CD-burning, you should probably turn this flag off to
  251. reduce code size.
  252. */
  253. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  254. #define JUCE_USE_CDBURNER 0
  255. #endif
  256. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  257. Unless you're using CD-reading, you should probably turn this flag off to
  258. reduce code size.
  259. */
  260. #ifndef JUCE_USE_CDREADER
  261. #define JUCE_USE_CDREADER 0
  262. #endif
  263. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  264. */
  265. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  266. #define JUCE_USE_CAMERA 0
  267. #endif
  268. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  269. gets repainted will flash in a random colour, so that you can check exactly how much and how
  270. often your components are being drawn.
  271. */
  272. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  273. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  274. #endif
  275. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  276. Unless you specifically want to disable this, it's best to leave this option turned on.
  277. */
  278. #ifndef JUCE_USE_XINERAMA
  279. #define JUCE_USE_XINERAMA 1
  280. #endif
  281. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  282. turned on unless you have a good reason to disable it.
  283. */
  284. #ifndef JUCE_USE_XSHM
  285. #define JUCE_USE_XSHM 1
  286. #endif
  287. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  288. */
  289. #ifndef JUCE_USE_XRENDER
  290. #define JUCE_USE_XRENDER 0
  291. #endif
  292. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  293. unless you have a good reason to disable it.
  294. */
  295. #ifndef JUCE_USE_XCURSOR
  296. #define JUCE_USE_XCURSOR 1
  297. #endif
  298. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  299. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  300. you're building a plugin hosting app.
  301. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  302. */
  303. #ifndef JUCE_PLUGINHOST_VST
  304. #define JUCE_PLUGINHOST_VST 0
  305. #endif
  306. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  307. of course, and should only be enabled if you're building a plugin hosting app.
  308. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  309. */
  310. #ifndef JUCE_PLUGINHOST_AU
  311. #define JUCE_PLUGINHOST_AU 0
  312. #endif
  313. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  314. This should be enabled if you're writing a console application.
  315. */
  316. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  317. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  318. #endif
  319. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  320. If you're not using any embedded web-pages, turning this off may reduce your code size.
  321. */
  322. #ifndef JUCE_WEB_BROWSER
  323. #define JUCE_WEB_BROWSER 1
  324. #endif
  325. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  326. Carbon isn't required for a normal app, but may be needed by specialised classes like
  327. plugin-hosts, which support older APIs.
  328. */
  329. #ifndef JUCE_SUPPORT_CARBON
  330. #define JUCE_SUPPORT_CARBON 1
  331. #endif
  332. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  333. You might need to tweak this if you're linking to an external zlib library in your app,
  334. but for normal apps, this option should be left alone.
  335. */
  336. #ifndef JUCE_INCLUDE_ZLIB_CODE
  337. #define JUCE_INCLUDE_ZLIB_CODE 1
  338. #endif
  339. #ifndef JUCE_INCLUDE_FLAC_CODE
  340. #define JUCE_INCLUDE_FLAC_CODE 1
  341. #endif
  342. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  343. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  344. #endif
  345. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  346. #define JUCE_INCLUDE_PNGLIB_CODE 1
  347. #endif
  348. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  349. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  350. #endif
  351. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  352. (Currently, this only affects Windows builds in debug mode).
  353. */
  354. #ifndef JUCE_CHECK_MEMORY_LEAKS
  355. #define JUCE_CHECK_MEMORY_LEAKS 1
  356. #endif
  357. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  358. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  359. are passed to the JUCEApplication::unhandledException() callback for logging.
  360. */
  361. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  362. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  363. #endif
  364. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  365. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  366. #undef JUCE_QUICKTIME
  367. #define JUCE_QUICKTIME 0
  368. #undef JUCE_OPENGL
  369. #define JUCE_OPENGL 0
  370. #undef JUCE_USE_CDBURNER
  371. #define JUCE_USE_CDBURNER 0
  372. #undef JUCE_USE_CDREADER
  373. #define JUCE_USE_CDREADER 0
  374. #undef JUCE_WEB_BROWSER
  375. #define JUCE_WEB_BROWSER 0
  376. #undef JUCE_PLUGINHOST_AU
  377. #define JUCE_PLUGINHOST_AU 0
  378. #undef JUCE_PLUGINHOST_VST
  379. #define JUCE_PLUGINHOST_VST 0
  380. #endif
  381. #endif
  382. /*** End of inlined file: juce_Config.h ***/
  383. #ifdef JUCE_NAMESPACE
  384. #define BEGIN_JUCE_NAMESPACE namespace JUCE_NAMESPACE {
  385. #define END_JUCE_NAMESPACE }
  386. #else
  387. #define BEGIN_JUCE_NAMESPACE
  388. #define END_JUCE_NAMESPACE
  389. #endif
  390. /*** Start of inlined file: juce_PlatformDefs.h ***/
  391. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  392. #define __JUCE_PLATFORMDEFS_JUCEHEADER__
  393. /* This file defines miscellaneous macros for debugging, assertions, etc.
  394. */
  395. #ifdef JUCE_FORCE_DEBUG
  396. #undef JUCE_DEBUG
  397. #if JUCE_FORCE_DEBUG
  398. #define JUCE_DEBUG 1
  399. #endif
  400. #endif
  401. /** This macro defines the C calling convention used as the standard for Juce calls. */
  402. #if JUCE_MSVC
  403. #define JUCE_CALLTYPE __stdcall
  404. #else
  405. #define JUCE_CALLTYPE
  406. #endif
  407. // Debugging and assertion macros
  408. // (For info about JUCE_LOG_ASSERTIONS, have a look in juce_Config.h)
  409. #if JUCE_LOG_ASSERTIONS
  410. #define juce_LogCurrentAssertion juce_LogAssertion (__FILE__, __LINE__);
  411. #elif JUCE_DEBUG
  412. #define juce_LogCurrentAssertion std::cerr << "JUCE Assertion failure in " << __FILE__ << ", line " << __LINE__ << std::endl;
  413. #else
  414. #define juce_LogCurrentAssertion
  415. #endif
  416. #if JUCE_DEBUG
  417. // If debugging is enabled..
  418. /** Writes a string to the standard error stream.
  419. This is only compiled in a debug build.
  420. @see Logger::outputDebugString
  421. */
  422. #define DBG(dbgtext) Logger::outputDebugString (dbgtext);
  423. // Assertions..
  424. #if JUCE_WINDOWS || DOXYGEN
  425. #if JUCE_USE_INTRINSICS
  426. #pragma intrinsic (__debugbreak)
  427. /** This will try to break the debugger if one is currently hosting this app.
  428. @see jassert()
  429. */
  430. #define juce_breakDebugger __debugbreak();
  431. #elif JUCE_GCC
  432. /** This will try to break the debugger if one is currently hosting this app.
  433. @see jassert()
  434. */
  435. #define juce_breakDebugger asm("int $3");
  436. #else
  437. /** This will try to break the debugger if one is currently hosting this app.
  438. @see jassert()
  439. */
  440. #define juce_breakDebugger { __asm int 3 }
  441. #endif
  442. #elif JUCE_MAC
  443. #define juce_breakDebugger Debugger();
  444. #elif JUCE_IPHONE
  445. #define juce_breakDebugger kill (0, SIGTRAP);
  446. #elif JUCE_LINUX
  447. #define juce_breakDebugger kill (0, SIGTRAP);
  448. #endif
  449. /** This will always cause an assertion failure.
  450. It is only compiled in a debug build, (unless JUCE_LOG_ASSERTIONS is enabled
  451. in juce_Config.h).
  452. @see jassert()
  453. */
  454. #define jassertfalse { juce_LogCurrentAssertion; if (JUCE_NAMESPACE::juce_isRunningUnderDebugger()) juce_breakDebugger; }
  455. /** Platform-independent assertion macro.
  456. This gets optimised out when not being built with debugging turned on.
  457. Be careful not to call any functions within its arguments that are vital to
  458. the behaviour of the program, because these won't get called in the release
  459. build.
  460. @see jassertfalse
  461. */
  462. #define jassert(expression) { if (! (expression)) jassertfalse; }
  463. #else
  464. // If debugging is disabled, these dummy debug and assertion macros are used..
  465. #define DBG(dbgtext)
  466. #define jassertfalse { juce_LogCurrentAssertion }
  467. #if JUCE_LOG_ASSERTIONS
  468. #define jassert(expression) { if (! (expression)) jassertfalse; }
  469. #else
  470. #define jassert(a) { }
  471. #endif
  472. #endif
  473. #ifndef DOXYGEN
  474. template <bool b> struct JuceStaticAssert;
  475. template <> struct JuceStaticAssert <true> { static void dummy() {} };
  476. #endif
  477. /** A compile-time assertion macro.
  478. If the expression parameter is false, the macro will cause a compile error.
  479. */
  480. #define static_jassert(expression) JuceStaticAssert<expression>::dummy();
  481. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  482. #define JUCE_TRY try
  483. #define JUCE_CATCH_ALL catch (...) {}
  484. #define JUCE_CATCH_ALL_ASSERT catch (...) { jassertfalse; }
  485. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  486. #define JUCE_CATCH_EXCEPTION JUCE_CATCH_ALL
  487. #else
  488. /** Used in try-catch blocks, this macro will send exceptions to the JUCEApplication
  489. object so they can be logged by the application if it wants to.
  490. */
  491. #define JUCE_CATCH_EXCEPTION \
  492. catch (const std::exception& e) \
  493. { \
  494. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__); \
  495. } \
  496. catch (...) \
  497. { \
  498. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__); \
  499. }
  500. #endif
  501. #else
  502. #define JUCE_TRY
  503. #define JUCE_CATCH_EXCEPTION
  504. #define JUCE_CATCH_ALL
  505. #define JUCE_CATCH_ALL_ASSERT
  506. #endif
  507. // Macros for inlining.
  508. #if JUCE_MSVC
  509. /** A platform-independent way of forcing an inline function.
  510. Use the syntax: @code
  511. forcedinline void myfunction (int x)
  512. @endcode
  513. */
  514. #ifndef JUCE_DEBUG
  515. #define forcedinline __forceinline
  516. #else
  517. #define forcedinline inline
  518. #endif
  519. #define JUCE_ALIGN(bytes) __declspec (align (bytes))
  520. #else
  521. /** A platform-independent way of forcing an inline function.
  522. Use the syntax: @code
  523. forcedinline void myfunction (int x)
  524. @endcode
  525. */
  526. #ifndef JUCE_DEBUG
  527. #define forcedinline inline __attribute__((always_inline))
  528. #else
  529. #define forcedinline inline
  530. #endif
  531. #define JUCE_ALIGN(bytes) __attribute__ ((aligned (bytes)))
  532. #endif
  533. #endif // __JUCE_PLATFORMDEFS_JUCEHEADER__
  534. /*** End of inlined file: juce_PlatformDefs.h ***/
  535. // Now we'll include any OS headers we need.. (at this point we are outside the Juce namespace).
  536. #if JUCE_MSVC
  537. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  538. #pragma warning (disable: 4284 4786) // (spurious VC6 warnings)
  539. #endif
  540. #pragma warning (push)
  541. #pragma warning (disable: 4514 4245 4100)
  542. #endif
  543. #include <cstdlib>
  544. #include <cstdarg>
  545. #include <climits>
  546. #include <limits>
  547. #include <cmath>
  548. #include <cwchar>
  549. #include <stdexcept>
  550. #include <typeinfo>
  551. #include <cstring>
  552. #include <cstdio>
  553. #include <iostream>
  554. #if JUCE_USE_INTRINSICS
  555. #include <intrin.h>
  556. #endif
  557. #if JUCE_MAC || JUCE_IPHONE
  558. #include <libkern/OSAtomic.h>
  559. #endif
  560. #if JUCE_LINUX
  561. #include <signal.h>
  562. #if __INTEL_COMPILER
  563. #if __ia64__
  564. #include <ia64intrin.h>
  565. #else
  566. #include <ia32intrin.h>
  567. #endif
  568. #endif
  569. #endif
  570. #if JUCE_MSVC && JUCE_DEBUG
  571. #include <crtdbg.h>
  572. #endif
  573. #if JUCE_MSVC
  574. #include <malloc.h>
  575. #pragma warning (pop)
  576. #if ! JUCE_PUBLIC_INCLUDES
  577. #pragma warning (4: 4511 4512 4100) // (enable some warnings that are turned off in VC8)
  578. #endif
  579. #endif
  580. // DLL building settings on Win32
  581. #if JUCE_MSVC
  582. #ifdef JUCE_DLL_BUILD
  583. #define JUCE_API __declspec (dllexport)
  584. #pragma warning (disable: 4251)
  585. #elif defined (JUCE_DLL)
  586. #define JUCE_API __declspec (dllimport)
  587. #pragma warning (disable: 4251)
  588. #endif
  589. #elif defined (__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
  590. #ifdef JUCE_DLL_BUILD
  591. #define JUCE_API __attribute__ ((visibility("default")))
  592. #endif
  593. #endif
  594. #ifndef JUCE_API
  595. /** This macro is added to all juce public class declarations. */
  596. #define JUCE_API
  597. #endif
  598. /** This macro is added to all juce public function declarations. */
  599. #define JUCE_PUBLIC_FUNCTION JUCE_API JUCE_CALLTYPE
  600. // Now include some basics that are needed by most of the Juce classes...
  601. BEGIN_JUCE_NAMESPACE
  602. extern bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger();
  603. #if JUCE_LOG_ASSERTIONS
  604. extern void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw();
  605. #endif
  606. /*** Start of inlined file: juce_Memory.h ***/
  607. #ifndef __JUCE_MEMORY_JUCEHEADER__
  608. #define __JUCE_MEMORY_JUCEHEADER__
  609. /*
  610. This file defines the various juce_malloc(), juce_free() macros that should be used in
  611. preference to the standard calls.
  612. */
  613. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  614. #ifndef JUCE_DLL
  615. // Win32 debug non-DLL versions..
  616. /** This should be used instead of calling malloc directly.
  617. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  618. */
  619. #define juce_malloc(numBytes) _malloc_dbg (numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  620. /** This should be used instead of calling calloc directly.
  621. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  622. */
  623. #define juce_calloc(numBytes) _calloc_dbg (1, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  624. /** This should be used instead of calling realloc directly.
  625. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  626. */
  627. #define juce_realloc(location, numBytes) _realloc_dbg (location, numBytes, _NORMAL_BLOCK, __FILE__, __LINE__)
  628. /** This should be used instead of calling free directly.
  629. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  630. */
  631. #define juce_free(location) _free_dbg (location, _NORMAL_BLOCK)
  632. #else
  633. // Win32 debug DLL versions..
  634. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  635. // way all juce calls in the DLL and in the host API will all use the same allocator.
  636. extern JUCE_API void* juce_DebugMalloc (const int size, const char* file, const int line);
  637. extern JUCE_API void* juce_DebugCalloc (const int size, const char* file, const int line);
  638. extern JUCE_API void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line);
  639. extern JUCE_API void juce_DebugFree (void* const block);
  640. /** This should be used instead of calling malloc directly.
  641. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  642. */
  643. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_DebugMalloc (numBytes, __FILE__, __LINE__)
  644. /** This should be used instead of calling calloc directly.
  645. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  646. */
  647. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_DebugCalloc (numBytes, __FILE__, __LINE__)
  648. /** This should be used instead of calling realloc directly.
  649. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  650. */
  651. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_DebugRealloc (location, numBytes, __FILE__, __LINE__)
  652. /** This should be used instead of calling free directly.
  653. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  654. */
  655. #define juce_free(location) JUCE_NAMESPACE::juce_DebugFree (location)
  656. #endif
  657. #if ! defined (_AFXDLL)
  658. /** This macro can be added to classes to add extra debugging information to the memory
  659. allocated for them, so you can see the type of objects involved when there's a dump
  660. of leaked objects at program shutdown. (Only works on win32 at the moment).
  661. */
  662. #define juce_UseDebuggingNewOperator \
  663. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  664. static void* operator new (size_t, void* p) { return p; } \
  665. static void operator delete (void* p) { juce_free (p); } \
  666. static void operator delete (void*, void*) { }
  667. #endif
  668. #elif defined (JUCE_DLL)
  669. // Win32 DLL (release) versions..
  670. // For the DLL, we'll define some functions in the DLL that will be used for allocation - that
  671. // way all juce calls in the DLL and in the host API will all use the same allocator.
  672. extern JUCE_API void* juce_Malloc (const int size);
  673. extern JUCE_API void* juce_Calloc (const int size);
  674. extern JUCE_API void* juce_Realloc (void* const block, const int size);
  675. extern JUCE_API void juce_Free (void* const block);
  676. /** This should be used instead of calling malloc directly.
  677. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  678. */
  679. #define juce_malloc(numBytes) JUCE_NAMESPACE::juce_Malloc (numBytes)
  680. /** This should be used instead of calling calloc directly.
  681. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  682. */
  683. #define juce_calloc(numBytes) JUCE_NAMESPACE::juce_Calloc (numBytes)
  684. /** This should be used instead of calling realloc directly.
  685. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  686. */
  687. #define juce_realloc(location, numBytes) JUCE_NAMESPACE::juce_Realloc (location, numBytes)
  688. /** This should be used instead of calling free directly.
  689. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  690. */
  691. #define juce_free(location) JUCE_NAMESPACE::juce_Free (location)
  692. #define juce_UseDebuggingNewOperator \
  693. static void* operator new (size_t sz) { void* const p = juce_malloc ((int) sz); return (p != 0) ? p : ::operator new (sz); } \
  694. static void* operator new (size_t, void* p) { return p; } \
  695. static void operator delete (void* p) { juce_free (p); } \
  696. static void operator delete (void*, void*) { }
  697. #else
  698. // Mac, Linux and Win32 (release) versions..
  699. /** This should be used instead of calling malloc directly.
  700. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  701. */
  702. #define juce_malloc(numBytes) malloc (numBytes)
  703. /** This should be used instead of calling calloc directly.
  704. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  705. */
  706. #define juce_calloc(numBytes) calloc (1, numBytes)
  707. /** This should be used instead of calling realloc directly.
  708. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  709. */
  710. #define juce_realloc(location, numBytes) realloc (location, numBytes)
  711. /** This should be used instead of calling free directly.
  712. Only use direct memory allocation if there's really no way to use a HeapBlock object instead!
  713. */
  714. #define juce_free(location) free (location)
  715. #endif
  716. /** This macro can be added to classes to add extra debugging information to the memory
  717. allocated for them, so you can see the type of objects involved when there's a dump
  718. of leaked objects at program shutdown. (Only works on win32 at the moment).
  719. Note that if you create a class that inherits from a class that uses this macro,
  720. your class must also use the macro, otherwise you'll probably get compile errors
  721. because of ambiguous new operators.
  722. Most of the JUCE classes use it, so see these for examples of where it should go.
  723. */
  724. #ifndef juce_UseDebuggingNewOperator
  725. #define juce_UseDebuggingNewOperator
  726. #endif
  727. #if JUCE_MSVC
  728. /** This is a compiler-independent way of declaring a variable as being thread-local.
  729. E.g.
  730. @code
  731. juce_ThreadLocal int myVariable;
  732. @endcode
  733. */
  734. #define juce_ThreadLocal __declspec(thread)
  735. #else
  736. #define juce_ThreadLocal __thread
  737. #endif
  738. #if JUCE_MINGW
  739. /** This allocator is not defined in mingw gcc. */
  740. #define alloca __builtin_alloca
  741. #endif
  742. /** Clears a block of memory. */
  743. inline void zeromem (void* memory, size_t numBytes) { memset (memory, 0, numBytes); }
  744. /** Clears a reference to a local structure. */
  745. template <typename Type>
  746. inline void zerostruct (Type& structure) { memset (&structure, 0, sizeof (structure)); }
  747. /** A handy function that calls delete on a pointer if it's non-zero, and then sets
  748. the pointer to null.
  749. */
  750. template <typename Type>
  751. inline void deleteAndZero (Type& pointer) { delete pointer; pointer = 0; }
  752. #endif // __JUCE_MEMORY_JUCEHEADER__
  753. /*** End of inlined file: juce_Memory.h ***/
  754. /*** Start of inlined file: juce_MathsFunctions.h ***/
  755. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  756. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  757. /*
  758. This file sets up some handy mathematical typdefs and functions.
  759. */
  760. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  761. /** A platform-independent 8-bit signed integer type. */
  762. typedef signed char int8;
  763. /** A platform-independent 8-bit unsigned integer type. */
  764. typedef unsigned char uint8;
  765. /** A platform-independent 16-bit signed integer type. */
  766. typedef signed short int16;
  767. /** A platform-independent 16-bit unsigned integer type. */
  768. typedef unsigned short uint16;
  769. /** A platform-independent 32-bit signed integer type. */
  770. typedef signed int int32;
  771. /** A platform-independent 32-bit unsigned integer type. */
  772. typedef unsigned int uint32;
  773. #if JUCE_MSVC
  774. /** A platform-independent 64-bit integer type. */
  775. typedef __int64 int64;
  776. /** A platform-independent 64-bit unsigned integer type. */
  777. typedef unsigned __int64 uint64;
  778. /** A platform-independent macro for writing 64-bit literals, needed because
  779. different compilers have different syntaxes for this.
  780. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  781. GCC, or 0x1000000000 for MSVC.
  782. */
  783. #define literal64bit(longLiteral) ((__int64) longLiteral)
  784. #else
  785. /** A platform-independent 64-bit integer type. */
  786. typedef long long int64;
  787. /** A platform-independent 64-bit unsigned integer type. */
  788. typedef unsigned long long uint64;
  789. /** A platform-independent macro for writing 64-bit literals, needed because
  790. different compilers have different syntaxes for this.
  791. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  792. GCC, or 0x1000000000 for MSVC.
  793. */
  794. #define literal64bit(longLiteral) (longLiteral##LL)
  795. #endif
  796. #if JUCE_64BIT
  797. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  798. typedef int64 pointer_sized_int;
  799. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  800. typedef uint64 pointer_sized_uint;
  801. #elif _MSC_VER >= 1300
  802. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  803. typedef _W64 int pointer_sized_int;
  804. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  805. typedef _W64 unsigned int pointer_sized_uint;
  806. #else
  807. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  808. typedef int pointer_sized_int;
  809. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  810. typedef unsigned int pointer_sized_uint;
  811. #endif
  812. /** A platform-independent unicode character type. */
  813. typedef wchar_t juce_wchar;
  814. // Some indispensible min/max functions
  815. /** Returns the larger of two values. */
  816. template <typename Type>
  817. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  818. /** Returns the larger of three values. */
  819. template <typename Type>
  820. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  821. /** Returns the larger of four values. */
  822. template <typename Type>
  823. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  824. /** Returns the smaller of two values. */
  825. template <typename Type>
  826. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  827. /** Returns the smaller of three values. */
  828. template <typename Type>
  829. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  830. /** Returns the smaller of four values. */
  831. template <typename Type>
  832. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  833. /** Constrains a value to keep it within a given range.
  834. This will check that the specified value lies between the lower and upper bounds
  835. specified, and if not, will return the nearest value that would be in-range. Effectively,
  836. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  837. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  838. the results will be unpredictable.
  839. @param lowerLimit the minimum value to return
  840. @param upperLimit the maximum value to return
  841. @param valueToConstrain the value to try to return
  842. @returns the closest value to valueToConstrain which lies between lowerLimit
  843. and upperLimit (inclusive)
  844. @see jlimit0To, jmin, jmax
  845. */
  846. template <typename Type>
  847. inline Type jlimit (const Type lowerLimit,
  848. const Type upperLimit,
  849. const Type valueToConstrain) throw()
  850. {
  851. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  852. return (valueToConstrain < lowerLimit) ? lowerLimit
  853. : ((upperLimit < valueToConstrain) ? upperLimit
  854. : valueToConstrain);
  855. }
  856. /** Handy function to swap two values over.
  857. */
  858. template <typename Type>
  859. inline void swapVariables (Type& variable1, Type& variable2)
  860. {
  861. const Type tempVal = variable1;
  862. variable1 = variable2;
  863. variable2 = tempVal;
  864. }
  865. /** Handy function for getting the number of elements in a simple const C array.
  866. E.g.
  867. @code
  868. static int myArray[] = { 1, 2, 3 };
  869. int numElements = numElementsInArray (myArray) // returns 3
  870. @endcode
  871. */
  872. template <typename Type>
  873. inline int numElementsInArray (Type& array)
  874. {
  875. (void) array; // (required to avoid a spurious warning in MS compilers)
  876. return static_cast<int> (sizeof (array) / sizeof (array[0]));
  877. }
  878. // Some useful maths functions that aren't always present with all compilers and build settings.
  879. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  880. versions of these functions of various platforms and compilers. */
  881. inline double juce_hypot (double a, double b)
  882. {
  883. #if JUCE_WINDOWS
  884. return _hypot (a, b);
  885. #else
  886. return hypot (a, b);
  887. #endif
  888. }
  889. /** Using juce_hypot and juce_hypotf is easier than dealing with all the different
  890. versions of these functions of various platforms and compilers. */
  891. inline float juce_hypotf (float a, float b) throw()
  892. {
  893. #if JUCE_WINDOWS
  894. return (float) _hypot (a, b);
  895. #else
  896. return hypotf (a, b);
  897. #endif
  898. }
  899. /** 64-bit abs function. */
  900. inline int64 abs64 (const int64 n) throw()
  901. {
  902. return (n >= 0) ? n : -n;
  903. }
  904. /** This templated negate function will negate pointers as well as integers */
  905. template <typename Type>
  906. inline Type juce_negate (Type n) throw()
  907. {
  908. return sizeof (Type) == 1 ? (Type) -(char) n
  909. : (sizeof (Type) == 2 ? (Type) -(short) n
  910. : (sizeof (Type) == 4 ? (Type) -(int) n
  911. : ((Type) -(int64) n)));
  912. }
  913. /** This templated negate function will negate pointers as well as integers */
  914. template <typename Type>
  915. inline Type* juce_negate (Type* n) throw()
  916. {
  917. return (Type*) -(pointer_sized_int) n;
  918. }
  919. /** A predefined value for Pi, at double-precision.
  920. @see float_Pi
  921. */
  922. const double double_Pi = 3.1415926535897932384626433832795;
  923. /** A predefined value for Pi, at sngle-precision.
  924. @see double_Pi
  925. */
  926. const float float_Pi = 3.14159265358979323846f;
  927. /** The isfinite() method seems to vary between platforms, so this is a
  928. platform-independent function for it.
  929. */
  930. template <typename FloatingPointType>
  931. inline bool juce_isfinite (FloatingPointType value)
  932. {
  933. #if JUCE_WINDOWS
  934. return _finite (value);
  935. #else
  936. return std::isfinite (value);
  937. #endif
  938. }
  939. /** Fast floating-point-to-integer conversion.
  940. This is faster than using the normal c++ cast to convert a float to an int, and
  941. it will round the value to the nearest integer, rather than rounding it down
  942. like the normal cast does.
  943. Note that this routine gets its speed at the expense of some accuracy, and when
  944. rounding values whose floating point component is exactly 0.5, odd numbers and
  945. even numbers will be rounded up or down differently.
  946. */
  947. template <typename FloatType>
  948. inline int roundToInt (const FloatType value) throw()
  949. {
  950. union { int asInt[2]; double asDouble; } n;
  951. n.asDouble = ((double) value) + 6755399441055744.0;
  952. #if JUCE_BIG_ENDIAN
  953. return n.asInt [1];
  954. #else
  955. return n.asInt [0];
  956. #endif
  957. }
  958. /** Fast floating-point-to-integer conversion.
  959. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  960. fine for values above zero, but negative numbers are rounded the wrong way.
  961. */
  962. inline int roundToIntAccurate (const double value) throw()
  963. {
  964. return roundToInt (value + 1.5e-8);
  965. }
  966. /** Fast floating-point-to-integer conversion.
  967. This is faster than using the normal c++ cast to convert a double to an int, and
  968. it will round the value to the nearest integer, rather than rounding it down
  969. like the normal cast does.
  970. Note that this routine gets its speed at the expense of some accuracy, and when
  971. rounding values whose floating point component is exactly 0.5, odd numbers and
  972. even numbers will be rounded up or down differently. For a more accurate conversion,
  973. see roundDoubleToIntAccurate().
  974. */
  975. inline int roundDoubleToInt (const double value) throw()
  976. {
  977. return roundToInt (value);
  978. }
  979. /** Fast floating-point-to-integer conversion.
  980. This is faster than using the normal c++ cast to convert a float to an int, and
  981. it will round the value to the nearest integer, rather than rounding it down
  982. like the normal cast does.
  983. Note that this routine gets its speed at the expense of some accuracy, and when
  984. rounding values whose floating point component is exactly 0.5, odd numbers and
  985. even numbers will be rounded up or down differently.
  986. */
  987. inline int roundFloatToInt (const float value) throw()
  988. {
  989. return roundToInt (value);
  990. }
  991. /** This namespace contains a few template classes for helping work out class type variations.
  992. */
  993. namespace TypeHelpers
  994. {
  995. #if defined (_MSC_VER) && _MSC_VER <= 1400
  996. #define PARAMETER_TYPE(a) a
  997. #else
  998. /** The ParameterType struct is used to find the best type to use when passing some kind
  999. of object as a parameter.
  1000. Of course, this is only likely to be useful in certain esoteric template situations.
  1001. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  1002. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  1003. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  1004. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  1005. pass-by-value, but passing objects as a const reference, to avoid copying.
  1006. */
  1007. template <typename Type> struct ParameterType { typedef const Type& type; };
  1008. #if ! DOXYGEN
  1009. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  1010. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  1011. template <> struct ParameterType <char> { typedef char type; };
  1012. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  1013. template <> struct ParameterType <short> { typedef short type; };
  1014. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  1015. template <> struct ParameterType <int> { typedef int type; };
  1016. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  1017. template <> struct ParameterType <long> { typedef long type; };
  1018. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  1019. template <> struct ParameterType <int64> { typedef int64 type; };
  1020. template <> struct ParameterType <uint64> { typedef uint64 type; };
  1021. template <> struct ParameterType <bool> { typedef bool type; };
  1022. template <> struct ParameterType <float> { typedef float type; };
  1023. template <> struct ParameterType <double> { typedef double type; };
  1024. #endif
  1025. /** A helpful macro to simplify the use of the ParameterType template.
  1026. @see ParameterType
  1027. */
  1028. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  1029. #endif
  1030. }
  1031. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  1032. /*** End of inlined file: juce_MathsFunctions.h ***/
  1033. /*** Start of inlined file: juce_ByteOrder.h ***/
  1034. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  1035. #define __JUCE_BYTEORDER_JUCEHEADER__
  1036. /** Contains static methods for converting the byte order between different
  1037. endiannesses.
  1038. */
  1039. class JUCE_API ByteOrder
  1040. {
  1041. public:
  1042. /** Swaps the upper and lower bytes of a 16-bit integer. */
  1043. static uint16 swap (uint16 value);
  1044. /** Reverses the order of the 4 bytes in a 32-bit integer. */
  1045. static uint32 swap (uint32 value);
  1046. /** Reverses the order of the 8 bytes in a 64-bit integer. */
  1047. static uint64 swap (uint64 value);
  1048. /** Swaps the byte order of a 16-bit int if the CPU is big-endian */
  1049. static uint16 swapIfBigEndian (uint16 value);
  1050. /** Swaps the byte order of a 32-bit int if the CPU is big-endian */
  1051. static uint32 swapIfBigEndian (uint32 value);
  1052. /** Swaps the byte order of a 64-bit int if the CPU is big-endian */
  1053. static uint64 swapIfBigEndian (uint64 value);
  1054. /** Swaps the byte order of a 16-bit int if the CPU is little-endian */
  1055. static uint16 swapIfLittleEndian (uint16 value);
  1056. /** Swaps the byte order of a 32-bit int if the CPU is little-endian */
  1057. static uint32 swapIfLittleEndian (uint32 value);
  1058. /** Swaps the byte order of a 64-bit int if the CPU is little-endian */
  1059. static uint64 swapIfLittleEndian (uint64 value);
  1060. /** Turns 4 bytes into a little-endian integer. */
  1061. static uint32 littleEndianInt (const void* bytes);
  1062. /** Turns 2 bytes into a little-endian integer. */
  1063. static uint16 littleEndianShort (const void* bytes);
  1064. /** Turns 4 bytes into a big-endian integer. */
  1065. static uint32 bigEndianInt (const void* bytes);
  1066. /** Turns 2 bytes into a big-endian integer. */
  1067. static uint16 bigEndianShort (const void* bytes);
  1068. /** Converts 3 little-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1069. static int littleEndian24Bit (const char* bytes);
  1070. /** Converts 3 big-endian bytes into a signed 24-bit value (which is sign-extended to 32 bits). */
  1071. static int bigEndian24Bit (const char* bytes);
  1072. /** Copies a 24-bit number to 3 little-endian bytes. */
  1073. static void littleEndian24BitToChars (int value, char* destBytes);
  1074. /** Copies a 24-bit number to 3 big-endian bytes. */
  1075. static void bigEndian24BitToChars (int value, char* destBytes);
  1076. /** Returns true if the current CPU is big-endian. */
  1077. static bool isBigEndian();
  1078. private:
  1079. ByteOrder();
  1080. ByteOrder (const ByteOrder&);
  1081. ByteOrder& operator= (const ByteOrder&);
  1082. };
  1083. #if JUCE_USE_INTRINSICS
  1084. #pragma intrinsic (_byteswap_ulong)
  1085. #endif
  1086. inline uint16 ByteOrder::swap (uint16 n)
  1087. {
  1088. #if JUCE_USE_INTRINSICSxxx // agh - the MS compiler has an internal error when you try to use this intrinsic!
  1089. return static_cast <uint16> (_byteswap_ushort (n));
  1090. #else
  1091. return static_cast <uint16> ((n << 8) | (n >> 8));
  1092. #endif
  1093. }
  1094. inline uint32 ByteOrder::swap (uint32 n)
  1095. {
  1096. #if JUCE_MAC || JUCE_IPHONE
  1097. return OSSwapInt32 (n);
  1098. #elif JUCE_GCC
  1099. asm("bswap %%eax" : "=a"(n) : "a"(n));
  1100. return n;
  1101. #elif JUCE_USE_INTRINSICS
  1102. return _byteswap_ulong (n);
  1103. #else
  1104. __asm {
  1105. mov eax, n
  1106. bswap eax
  1107. mov n, eax
  1108. }
  1109. return n;
  1110. #endif
  1111. }
  1112. inline uint64 ByteOrder::swap (uint64 value)
  1113. {
  1114. #if JUCE_MAC || JUCE_IPHONE
  1115. return OSSwapInt64 (value);
  1116. #elif JUCE_USE_INTRINSICS
  1117. return _byteswap_uint64 (value);
  1118. #else
  1119. return (((int64) swap ((uint32) value)) << 32) | swap ((uint32) (value >> 32));
  1120. #endif
  1121. }
  1122. #if JUCE_LITTLE_ENDIAN
  1123. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return v; }
  1124. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return v; }
  1125. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return v; }
  1126. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return swap (v); }
  1127. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return swap (v); }
  1128. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return swap (v); }
  1129. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1130. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1131. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1132. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1133. inline bool ByteOrder::isBigEndian() { return false; }
  1134. #else
  1135. inline uint16 ByteOrder::swapIfBigEndian (const uint16 v) { return swap (v); }
  1136. inline uint32 ByteOrder::swapIfBigEndian (const uint32 v) { return swap (v); }
  1137. inline uint64 ByteOrder::swapIfBigEndian (const uint64 v) { return swap (v); }
  1138. inline uint16 ByteOrder::swapIfLittleEndian (const uint16 v) { return v; }
  1139. inline uint32 ByteOrder::swapIfLittleEndian (const uint32 v) { return v; }
  1140. inline uint64 ByteOrder::swapIfLittleEndian (const uint64 v) { return v; }
  1141. inline uint32 ByteOrder::littleEndianInt (const void* const bytes) { return swap (*static_cast <const uint32*> (bytes)); }
  1142. inline uint16 ByteOrder::littleEndianShort (const void* const bytes) { return swap (*static_cast <const uint16*> (bytes)); }
  1143. inline uint32 ByteOrder::bigEndianInt (const void* const bytes) { return *static_cast <const uint32*> (bytes); }
  1144. inline uint16 ByteOrder::bigEndianShort (const void* const bytes) { return *static_cast <const uint16*> (bytes); }
  1145. inline bool ByteOrder::isBigEndian() { return true; }
  1146. #endif
  1147. inline int ByteOrder::littleEndian24Bit (const char* const bytes) { return (((int) bytes[2]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[0]); }
  1148. inline int ByteOrder::bigEndian24Bit (const char* const bytes) { return (((int) bytes[0]) << 16) | (((uint32) (uint8) bytes[1]) << 8) | ((uint32) (uint8) bytes[2]); }
  1149. inline void ByteOrder::littleEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)(value & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)((value >> 16) & 0xff); }
  1150. inline void ByteOrder::bigEndian24BitToChars (const int value, char* const destBytes) { destBytes[0] = (char)((value >> 16) & 0xff); destBytes[1] = (char)((value >> 8) & 0xff); destBytes[2] = (char)(value & 0xff); }
  1151. #endif // __JUCE_BYTEORDER_JUCEHEADER__
  1152. /*** End of inlined file: juce_ByteOrder.h ***/
  1153. /*** Start of inlined file: juce_Logger.h ***/
  1154. #ifndef __JUCE_LOGGER_JUCEHEADER__
  1155. #define __JUCE_LOGGER_JUCEHEADER__
  1156. /*** Start of inlined file: juce_String.h ***/
  1157. #ifndef __JUCE_STRING_JUCEHEADER__
  1158. #define __JUCE_STRING_JUCEHEADER__
  1159. /*** Start of inlined file: juce_CharacterFunctions.h ***/
  1160. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1161. #define __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1162. #define JUCE_T(stringLiteral) (L##stringLiteral)
  1163. typedef juce_wchar tchar;
  1164. #if ! JUCE_DONT_DEFINE_MACROS
  1165. /** The 'T' macro allows a literal string to be compiled as unicode.
  1166. If you write your string literals in the form T("xyz"), it will be compiled as L"xyz"
  1167. or "xyz", depending on which representation is best for the String class to work with.
  1168. Because the 'T' symbol is occasionally used inside 3rd-party library headers which you
  1169. may need to include after juce.h, you can use the juce_withoutMacros.h file (in
  1170. the juce/src directory) to avoid defining this macro. See the comments in
  1171. juce_withoutMacros.h for more info.
  1172. */
  1173. #define T(stringLiteral) JUCE_T(stringLiteral)
  1174. #endif
  1175. /**
  1176. A set of methods for manipulating characters and character strings, with
  1177. duplicate methods to handle 8-bit and unicode characters.
  1178. These are defined as wrappers around the basic C string handlers, to provide
  1179. a clean, cross-platform layer, (because various platforms differ in the
  1180. range of C library calls that they provide).
  1181. @see String
  1182. */
  1183. class JUCE_API CharacterFunctions
  1184. {
  1185. public:
  1186. static int length (const char* const s) throw();
  1187. static int length (const juce_wchar* const s) throw();
  1188. static void copy (char* dest, const char* src, const int maxBytes) throw();
  1189. static void copy (juce_wchar* dest, const juce_wchar* src, const int maxChars) throw();
  1190. static void copy (juce_wchar* dest, const char* src, const int maxChars) throw();
  1191. static void copy (char* dest, const juce_wchar* src, const int maxBytes) throw();
  1192. static int bytesRequiredForCopy (const juce_wchar* src) throw();
  1193. static void append (char* dest, const char* src) throw();
  1194. static void append (juce_wchar* dest, const juce_wchar* src) throw();
  1195. static int compare (const char* const s1, const char* const s2) throw();
  1196. static int compare (const juce_wchar* s1, const juce_wchar* s2) throw();
  1197. static int compare (const juce_wchar* s1, const char* s2) throw();
  1198. static int compare (const char* s1, const juce_wchar* s2) throw();
  1199. static int compare (const char* const s1, const char* const s2, const int maxChars) throw();
  1200. static int compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1201. static int compareIgnoreCase (const char* const s1, const char* const s2) throw();
  1202. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw();
  1203. static int compareIgnoreCase (const juce_wchar* s1, const char* s2) throw();
  1204. static int compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw();
  1205. static int compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw();
  1206. static const char* find (const char* const haystack, const char* const needle) throw();
  1207. static const juce_wchar* find (const juce_wchar* haystack, const juce_wchar* const needle) throw();
  1208. static int indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw();
  1209. static int indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw();
  1210. static int indexOfCharFast (const char* const haystack, const char needle) throw();
  1211. static int indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw();
  1212. static int getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw();
  1213. static int getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw();
  1214. static int ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw();
  1215. static int ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw();
  1216. static int getIntValue (const char* const s) throw();
  1217. static int getIntValue (const juce_wchar* s) throw();
  1218. static int64 getInt64Value (const char* s) throw();
  1219. static int64 getInt64Value (const juce_wchar* s) throw();
  1220. static double getDoubleValue (const char* const s) throw();
  1221. static double getDoubleValue (const juce_wchar* const s) throw();
  1222. static char toUpperCase (const char character) throw();
  1223. static juce_wchar toUpperCase (const juce_wchar character) throw();
  1224. static void toUpperCase (char* s) throw();
  1225. static void toUpperCase (juce_wchar* s) throw();
  1226. static bool isUpperCase (const char character) throw();
  1227. static bool isUpperCase (const juce_wchar character) throw();
  1228. static char toLowerCase (const char character) throw();
  1229. static juce_wchar toLowerCase (const juce_wchar character) throw();
  1230. static void toLowerCase (char* s) throw();
  1231. static void toLowerCase (juce_wchar* s) throw();
  1232. static bool isLowerCase (const char character) throw();
  1233. static bool isLowerCase (const juce_wchar character) throw();
  1234. static bool isWhitespace (const char character) throw();
  1235. static bool isWhitespace (const juce_wchar character) throw();
  1236. static bool isDigit (const char character) throw();
  1237. static bool isDigit (const juce_wchar character) throw();
  1238. static bool isLetter (const char character) throw();
  1239. static bool isLetter (const juce_wchar character) throw();
  1240. static bool isLetterOrDigit (const char character) throw();
  1241. static bool isLetterOrDigit (const juce_wchar character) throw();
  1242. /** Returns 0 to 16 for '0' to 'F", or -1 for characters that aren't a legel
  1243. hex digit.
  1244. */
  1245. static int getHexDigitValue (const juce_wchar digit) throw();
  1246. };
  1247. #endif // __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  1248. /*** End of inlined file: juce_CharacterFunctions.h ***/
  1249. class OutputStream;
  1250. /**
  1251. The JUCE String class!
  1252. Using a reference-counted internal representation, these strings are fast
  1253. and efficient, and there are methods to do just about any operation you'll ever
  1254. dream of.
  1255. @see StringArray, StringPairArray
  1256. */
  1257. class JUCE_API String
  1258. {
  1259. public:
  1260. /** Creates an empty string.
  1261. @see empty
  1262. */
  1263. String() throw();
  1264. /** Creates a copy of another string. */
  1265. String (const String& other) throw();
  1266. /** Creates a string from a zero-terminated text string.
  1267. The string is assumed to be stored in the default system encoding.
  1268. */
  1269. String (const char* text);
  1270. /** Creates a string from an string of characters.
  1271. This will use up the the first maxChars characters of the string (or
  1272. less if the string is actually shorter)
  1273. */
  1274. String (const char* text, size_t maxChars);
  1275. /** Creates a string from a zero-terminated unicode text string. */
  1276. String (const juce_wchar* unicodeText);
  1277. /** Creates a string from a unicode text string.
  1278. This will use up the the first maxChars characters of the string (or
  1279. less if the string is actually shorter)
  1280. */
  1281. String (const juce_wchar* unicodeText, size_t maxChars);
  1282. /** Creates a string from a single character. */
  1283. static const String charToString (juce_wchar character);
  1284. /** Destructor. */
  1285. ~String() throw();
  1286. /** This is an empty string that can be used whenever one is needed.
  1287. It's better to use this than String() because it explains what's going on
  1288. and is more efficient.
  1289. */
  1290. static const String empty;
  1291. /** Generates a probably-unique 32-bit hashcode from this string. */
  1292. int hashCode() const throw();
  1293. /** Generates a probably-unique 64-bit hashcode from this string. */
  1294. int64 hashCode64() const throw();
  1295. /** Returns the number of characters in the string. */
  1296. int length() const throw();
  1297. // Assignment and concatenation operators..
  1298. /** Replaces this string's contents with another string. */
  1299. String& operator= (const String& other) throw();
  1300. /** Appends another string at the end of this one. */
  1301. String& operator+= (const juce_wchar* textToAppend);
  1302. /** Appends another string at the end of this one. */
  1303. String& operator+= (const String& stringToAppend);
  1304. /** Appends a character at the end of this string. */
  1305. String& operator+= (char characterToAppend);
  1306. /** Appends a character at the end of this string. */
  1307. String& operator+= (juce_wchar characterToAppend);
  1308. /** Appends a decimal number at the end of this string. */
  1309. String& operator+= (int numberToAppend);
  1310. /** Appends a decimal number at the end of this string. */
  1311. String& operator+= (unsigned int numberToAppend);
  1312. /** Appends a string at the end of this one.
  1313. @param textToAppend the string to add
  1314. @param maxCharsToTake the maximum number of characters to take from the string passed in
  1315. */
  1316. void append (const juce_wchar* textToAppend, int maxCharsToTake);
  1317. // Comparison methods..
  1318. /** Returns true if the string contains no characters.
  1319. Note that there's also an isNotEmpty() method to help write readable code.
  1320. @see containsNonWhitespaceChars()
  1321. */
  1322. inline bool isEmpty() const throw() { return text[0] == 0; }
  1323. /** Returns true if the string contains at least one character.
  1324. Note that there's also an isEmpty() method to help write readable code.
  1325. @see containsNonWhitespaceChars()
  1326. */
  1327. inline bool isNotEmpty() const throw() { return text[0] != 0; }
  1328. /** Case-insensitive comparison with another string. */
  1329. bool equalsIgnoreCase (const String& other) const throw();
  1330. /** Case-insensitive comparison with another string. */
  1331. bool equalsIgnoreCase (const juce_wchar* other) const throw();
  1332. /** Case-insensitive comparison with another string. */
  1333. bool equalsIgnoreCase (const char* other) const throw();
  1334. /** Case-sensitive comparison with another string.
  1335. @returns 0 if the two strings are identical; negative if this string
  1336. comes before the other one alphabetically, or positive if it
  1337. comes after it.
  1338. */
  1339. int compare (const String& other) const throw();
  1340. /** Case-sensitive comparison with another string.
  1341. @returns 0 if the two strings are identical; negative if this string
  1342. comes before the other one alphabetically, or positive if it
  1343. comes after it.
  1344. */
  1345. int compare (const char* other) const throw();
  1346. /** Case-sensitive comparison with another string.
  1347. @returns 0 if the two strings are identical; negative if this string
  1348. comes before the other one alphabetically, or positive if it
  1349. comes after it.
  1350. */
  1351. int compare (const juce_wchar* other) const throw();
  1352. /** Case-insensitive comparison with another string.
  1353. @returns 0 if the two strings are identical; negative if this string
  1354. comes before the other one alphabetically, or positive if it
  1355. comes after it.
  1356. */
  1357. int compareIgnoreCase (const String& other) const throw();
  1358. /** Lexicographic comparison with another string.
  1359. The comparison used here is case-insensitive and ignores leading non-alphanumeric
  1360. characters, making it good for sorting human-readable strings.
  1361. @returns 0 if the two strings are identical; negative if this string
  1362. comes before the other one alphabetically, or positive if it
  1363. comes after it.
  1364. */
  1365. int compareLexicographically (const String& other) const throw();
  1366. /** Tests whether the string begins with another string.
  1367. Uses a case-sensitive comparison.
  1368. */
  1369. bool startsWith (const String& text) const throw();
  1370. /** Tests whether the string begins with a particular character.
  1371. Uses a case-sensitive comparison.
  1372. */
  1373. bool startsWithChar (juce_wchar character) const throw();
  1374. /** Tests whether the string begins with another string.
  1375. Uses a case-insensitive comparison.
  1376. */
  1377. bool startsWithIgnoreCase (const String& text) const throw();
  1378. /** Tests whether the string ends with another string.
  1379. Uses a case-sensitive comparison.
  1380. */
  1381. bool endsWith (const String& text) const throw();
  1382. /** Tests whether the string ends with a particular character.
  1383. Uses a case-sensitive comparison.
  1384. */
  1385. bool endsWithChar (juce_wchar character) const throw();
  1386. /** Tests whether the string ends with another string.
  1387. Uses a case-insensitive comparison.
  1388. */
  1389. bool endsWithIgnoreCase (const String& text) const throw();
  1390. /** Tests whether the string contains another substring.
  1391. Uses a case-sensitive comparison.
  1392. */
  1393. bool contains (const String& text) const throw();
  1394. /** Tests whether the string contains a particular character.
  1395. Uses a case-sensitive comparison.
  1396. */
  1397. bool containsChar (juce_wchar character) const throw();
  1398. /** Tests whether the string contains another substring.
  1399. Uses a case-insensitive comparison.
  1400. */
  1401. bool containsIgnoreCase (const String& text) const throw();
  1402. /** Tests whether the string contains another substring as a distict word.
  1403. @returns true if the string contains this word, surrounded by
  1404. non-alphanumeric characters
  1405. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1406. */
  1407. bool containsWholeWord (const String& wordToLookFor) const throw();
  1408. /** Tests whether the string contains another substring as a distict word.
  1409. @returns true if the string contains this word, surrounded by
  1410. non-alphanumeric characters
  1411. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1412. */
  1413. bool containsWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1414. /** Finds an instance of another substring if it exists as a distict word.
  1415. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1416. then this will return the index of the start of the substring. If it isn't
  1417. found, then it will return -1
  1418. @see indexOfWholeWordIgnoreCase, containsWholeWord
  1419. */
  1420. int indexOfWholeWord (const String& wordToLookFor) const throw();
  1421. /** Finds an instance of another substring if it exists as a distict word.
  1422. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  1423. then this will return the index of the start of the substring. If it isn't
  1424. found, then it will return -1
  1425. @see indexOfWholeWord, containsWholeWordIgnoreCase
  1426. */
  1427. int indexOfWholeWordIgnoreCase (const String& wordToLookFor) const throw();
  1428. /** Looks for any of a set of characters in the string.
  1429. Uses a case-sensitive comparison.
  1430. @returns true if the string contains any of the characters from
  1431. the string that is passed in.
  1432. */
  1433. bool containsAnyOf (const String& charactersItMightContain) const throw();
  1434. /** Looks for a set of characters in the string.
  1435. Uses a case-sensitive comparison.
  1436. @returns true if the all the characters in the string are also found in the
  1437. string that is passed in.
  1438. */
  1439. bool containsOnly (const String& charactersItMightContain) const throw();
  1440. /** Returns true if this string contains any non-whitespace characters.
  1441. This will return false if the string contains only whitespace characters, or
  1442. if it's empty.
  1443. It is equivalent to calling "myString.trim().isNotEmpty()".
  1444. */
  1445. bool containsNonWhitespaceChars() const throw();
  1446. /** Returns true if the string matches this simple wildcard expression.
  1447. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  1448. This isn't a full-blown regex though! The only wildcard characters supported
  1449. are "*" and "?". It's mainly intended for filename pattern matching.
  1450. */
  1451. bool matchesWildcard (const String& wildcard, bool ignoreCase) const throw();
  1452. // Substring location methods..
  1453. /** Searches for a character inside this string.
  1454. Uses a case-sensitive comparison.
  1455. @returns the index of the first occurrence of the character in this
  1456. string, or -1 if it's not found.
  1457. */
  1458. int indexOfChar (juce_wchar characterToLookFor) const throw();
  1459. /** Searches for a character inside this string.
  1460. Uses a case-sensitive comparison.
  1461. @param startIndex the index from which the search should proceed
  1462. @param characterToLookFor the character to look for
  1463. @returns the index of the first occurrence of the character in this
  1464. string, or -1 if it's not found.
  1465. */
  1466. int indexOfChar (int startIndex, juce_wchar characterToLookFor) const throw();
  1467. /** Returns the index of the first character that matches one of the characters
  1468. passed-in to this method.
  1469. This scans the string, beginning from the startIndex supplied, and if it finds
  1470. a character that appears in the string charactersToLookFor, it returns its index.
  1471. If none of these characters are found, it returns -1.
  1472. If ignoreCase is true, the comparison will be case-insensitive.
  1473. @see indexOfChar, lastIndexOfAnyOf
  1474. */
  1475. int indexOfAnyOf (const String& charactersToLookFor,
  1476. int startIndex = 0,
  1477. bool ignoreCase = false) const throw();
  1478. /** Searches for a substring within this string.
  1479. Uses a case-sensitive comparison.
  1480. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1481. */
  1482. int indexOf (const String& text) const throw();
  1483. /** Searches for a substring within this string.
  1484. Uses a case-sensitive comparison.
  1485. @param startIndex the index from which the search should proceed
  1486. @param textToLookFor the string to search for
  1487. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1488. */
  1489. int indexOf (int startIndex,
  1490. const String& textToLookFor) const throw();
  1491. /** Searches for a substring within this string.
  1492. Uses a case-insensitive comparison.
  1493. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1494. */
  1495. int indexOfIgnoreCase (const String& textToLookFor) const throw();
  1496. /** Searches for a substring within this string.
  1497. Uses a case-insensitive comparison.
  1498. @param startIndex the index from which the search should proceed
  1499. @param textToLookFor the string to search for
  1500. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  1501. */
  1502. int indexOfIgnoreCase (int startIndex,
  1503. const String& textToLookFor) const throw();
  1504. /** Searches for a character inside this string (working backwards from the end of the string).
  1505. Uses a case-sensitive comparison.
  1506. @returns the index of the last occurrence of the character in this
  1507. string, or -1 if it's not found.
  1508. */
  1509. int lastIndexOfChar (juce_wchar character) const throw();
  1510. /** Searches for a substring inside this string (working backwards from the end of the string).
  1511. Uses a case-sensitive comparison.
  1512. @returns the index of the start of the last occurrence of the
  1513. substring within this string, or -1 if it's not found.
  1514. */
  1515. int lastIndexOf (const String& textToLookFor) const throw();
  1516. /** Searches for a substring inside this string (working backwards from the end of the string).
  1517. Uses a case-insensitive comparison.
  1518. @returns the index of the start of the last occurrence of the
  1519. substring within this string, or -1 if it's not found.
  1520. */
  1521. int lastIndexOfIgnoreCase (const String& textToLookFor) const throw();
  1522. /** Returns the index of the last character in this string that matches one of the
  1523. characters passed-in to this method.
  1524. This scans the string backwards, starting from its end, and if it finds
  1525. a character that appears in the string charactersToLookFor, it returns its index.
  1526. If none of these characters are found, it returns -1.
  1527. If ignoreCase is true, the comparison will be case-insensitive.
  1528. @see lastIndexOf, indexOfAnyOf
  1529. */
  1530. int lastIndexOfAnyOf (const String& charactersToLookFor,
  1531. bool ignoreCase = false) const throw();
  1532. // Substring extraction and manipulation methods..
  1533. /** Returns the character at this index in the string.
  1534. No checks are made to see if the index is within a valid range, so be careful!
  1535. */
  1536. inline const juce_wchar& operator[] (int index) const throw() { jassert (((unsigned int) index) <= (unsigned int) length()); return text [index]; }
  1537. /** Returns a character from the string such that it can also be altered.
  1538. This can be used as a way of easily changing characters in the string.
  1539. Note that the index passed-in is not checked to see whether it's in-range, so
  1540. be careful when using this.
  1541. */
  1542. juce_wchar& operator[] (int index);
  1543. /** Returns the final character of the string.
  1544. If the string is empty this will return 0.
  1545. */
  1546. juce_wchar getLastCharacter() const throw();
  1547. /** Returns a subsection of the string.
  1548. If the range specified is beyond the limits of the string, as much as
  1549. possible is returned.
  1550. @param startIndex the index of the start of the substring needed
  1551. @param endIndex all characters from startIndex up to (but not including)
  1552. this index are returned
  1553. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  1554. */
  1555. const String substring (int startIndex, int endIndex) const;
  1556. /** Returns a section of the string, starting from a given position.
  1557. @param startIndex the first character to include. If this is beyond the end
  1558. of the string, an empty string is returned. If it is zero or
  1559. less, the whole string is returned.
  1560. @returns the substring from startIndex up to the end of the string
  1561. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  1562. */
  1563. const String substring (int startIndex) const;
  1564. /** Returns a version of this string with a number of characters removed
  1565. from the end.
  1566. @param numberToDrop the number of characters to drop from the end of the
  1567. string. If this is greater than the length of the string,
  1568. an empty string will be returned. If zero or less, the
  1569. original string will be returned.
  1570. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  1571. */
  1572. const String dropLastCharacters (int numberToDrop) const;
  1573. /** Returns a number of characters from the end of the string.
  1574. This returns the last numCharacters characters from the end of the string. If the
  1575. string is shorter than numCharacters, the whole string is returned.
  1576. @see substring, dropLastCharacters, getLastCharacter
  1577. */
  1578. const String getLastCharacters (int numCharacters) const;
  1579. /** Returns a section of the string starting from a given substring.
  1580. This will search for the first occurrence of the given substring, and
  1581. return the section of the string starting from the point where this is
  1582. found (optionally not including the substring itself).
  1583. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  1584. fromFirstOccurrenceOf ("34", false) would return "56".
  1585. If the substring isn't found, the method will return an empty string.
  1586. If ignoreCase is true, the comparison will be case-insensitive.
  1587. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  1588. */
  1589. const String fromFirstOccurrenceOf (const String& substringToStartFrom,
  1590. bool includeSubStringInResult,
  1591. bool ignoreCase) const;
  1592. /** Returns a section of the string starting from the last occurrence of a given substring.
  1593. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  1594. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  1595. return the whole of the original string.
  1596. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  1597. */
  1598. const String fromLastOccurrenceOf (const String& substringToFind,
  1599. bool includeSubStringInResult,
  1600. bool ignoreCase) const;
  1601. /** Returns the start of this string, up to the first occurrence of a substring.
  1602. This will search for the first occurrence of a given substring, and then
  1603. return a copy of the string, up to the position of this substring,
  1604. optionally including or excluding the substring itself in the result.
  1605. e.g. for the string "123456", upTo ("34", false) would return "12", and
  1606. upTo ("34", true) would return "1234".
  1607. If the substring isn't found, this will return the whole of the original string.
  1608. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  1609. */
  1610. const String upToFirstOccurrenceOf (const String& substringToEndWith,
  1611. bool includeSubStringInResult,
  1612. bool ignoreCase) const;
  1613. /** Returns the start of this string, up to the last occurrence of a substring.
  1614. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  1615. If the substring isn't found, this will return an empty string.
  1616. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  1617. */
  1618. const String upToLastOccurrenceOf (const String& substringToFind,
  1619. bool includeSubStringInResult,
  1620. bool ignoreCase) const;
  1621. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  1622. const String trim() const;
  1623. /** Returns a copy of this string with any whitespace characters removed from the start. */
  1624. const String trimStart() const;
  1625. /** Returns a copy of this string with any whitespace characters removed from the end. */
  1626. const String trimEnd() const;
  1627. /** Returns a copy of this string, having removed a specified set of characters from its start.
  1628. Characters are removed from the start of the string until it finds one that is not in the
  1629. specified set, and then it stops.
  1630. @param charactersToTrim the set of characters to remove.
  1631. @see trim, trimStart, trimCharactersAtEnd
  1632. */
  1633. const String trimCharactersAtStart (const String& charactersToTrim) const;
  1634. /** Returns a copy of this string, having removed a specified set of characters from its end.
  1635. Characters are removed from the end of the string until it finds one that is not in the
  1636. specified set, and then it stops.
  1637. @param charactersToTrim the set of characters to remove.
  1638. @see trim, trimEnd, trimCharactersAtStart
  1639. */
  1640. const String trimCharactersAtEnd (const String& charactersToTrim) const;
  1641. /** Returns an upper-case version of this string. */
  1642. const String toUpperCase() const;
  1643. /** Returns an lower-case version of this string. */
  1644. const String toLowerCase() const;
  1645. /** Replaces a sub-section of the string with another string.
  1646. This will return a copy of this string, with a set of characters
  1647. from startIndex to startIndex + numCharsToReplace removed, and with
  1648. a new string inserted in their place.
  1649. Note that this is a const method, and won't alter the string itself.
  1650. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  1651. it will be constrained to a valid range.
  1652. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  1653. characters will be taken out.
  1654. @param stringToInsert the new string to insert at startIndex after the characters have been
  1655. removed.
  1656. */
  1657. const String replaceSection (int startIndex,
  1658. int numCharactersToReplace,
  1659. const String& stringToInsert) const;
  1660. /** Replaces all occurrences of a substring with another string.
  1661. Returns a copy of this string, with any occurrences of stringToReplace
  1662. swapped for stringToInsertInstead.
  1663. Note that this is a const method, and won't alter the string itself.
  1664. */
  1665. const String replace (const String& stringToReplace,
  1666. const String& stringToInsertInstead,
  1667. bool ignoreCase = false) const;
  1668. /** Returns a string with all occurrences of a character replaced with a different one. */
  1669. const String replaceCharacter (juce_wchar characterToReplace,
  1670. juce_wchar characterToInsertInstead) const;
  1671. /** Replaces a set of characters with another set.
  1672. Returns a string in which each character from charactersToReplace has been replaced
  1673. by the character at the equivalent position in newCharacters (so the two strings
  1674. passed in must be the same length).
  1675. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  1676. Note that this is a const method, and won't affect the string itself.
  1677. */
  1678. const String replaceCharacters (const String& charactersToReplace,
  1679. const String& charactersToInsertInstead) const;
  1680. /** Returns a version of this string that only retains a fixed set of characters.
  1681. This will return a copy of this string, omitting any characters which are not
  1682. found in the string passed-in.
  1683. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  1684. Note that this is a const method, and won't alter the string itself.
  1685. */
  1686. const String retainCharacters (const String& charactersToRetain) const;
  1687. /** Returns a version of this string with a set of characters removed.
  1688. This will return a copy of this string, omitting any characters which are
  1689. found in the string passed-in.
  1690. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  1691. Note that this is a const method, and won't alter the string itself.
  1692. */
  1693. const String removeCharacters (const String& charactersToRemove) const;
  1694. /** Returns a section from the start of the string that only contains a certain set of characters.
  1695. This returns the leftmost section of the string, up to (and not including) the
  1696. first character that doesn't appear in the string passed in.
  1697. */
  1698. const String initialSectionContainingOnly (const String& permittedCharacters) const;
  1699. /** Returns a section from the start of the string that only contains a certain set of characters.
  1700. This returns the leftmost section of the string, up to (and not including) the
  1701. first character that occurs in the string passed in.
  1702. */
  1703. const String initialSectionNotContaining (const String& charactersToStopAt) const;
  1704. /** Checks whether the string might be in quotation marks.
  1705. @returns true if the string begins with a quote character (either a double or single quote).
  1706. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  1707. @see unquoted, quoted
  1708. */
  1709. bool isQuotedString() const;
  1710. /** Removes quotation marks from around the string, (if there are any).
  1711. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  1712. at the ends of the string are not affected. If there aren't any quotes, the original string
  1713. is returned.
  1714. Note that this is a const method, and won't alter the string itself.
  1715. @see isQuotedString, quoted
  1716. */
  1717. const String unquoted() const;
  1718. /** Adds quotation marks around a string.
  1719. This will return a copy of the string with a quote at the start and end, (but won't
  1720. add the quote if there's already one there, so it's safe to call this on strings that
  1721. may already have quotes around them).
  1722. Note that this is a const method, and won't alter the string itself.
  1723. @param quoteCharacter the character to add at the start and end
  1724. @see isQuotedString, unquoted
  1725. */
  1726. const String quoted (juce_wchar quoteCharacter = '"') const;
  1727. /** Creates a string which is a version of a string repeated and joined together.
  1728. @param stringToRepeat the string to repeat
  1729. @param numberOfTimesToRepeat how many times to repeat it
  1730. */
  1731. static const String repeatedString (const String& stringToRepeat,
  1732. int numberOfTimesToRepeat);
  1733. /** Returns a copy of this string with the specified character repeatedly added to its
  1734. beginning until the total length is at least the minimum length specified.
  1735. */
  1736. const String paddedLeft (juce_wchar padCharacter, int minimumLength) const;
  1737. /** Returns a copy of this string with the specified character repeatedly added to its
  1738. end until the total length is at least the minimum length specified.
  1739. */
  1740. const String paddedRight (juce_wchar padCharacter, int minimumLength) const;
  1741. /** Creates a string from data in an unknown format.
  1742. This looks at some binary data and tries to guess whether it's Unicode
  1743. or 8-bit characters, then returns a string that represents it correctly.
  1744. Should be able to handle Unicode endianness correctly, by looking at
  1745. the first two bytes.
  1746. */
  1747. static const String createStringFromData (const void* data, int size);
  1748. /** Creates a String from a printf-style parameter list.
  1749. I don't like this method. I don't use it myself, and I recommend avoiding it and
  1750. using the operator<< methods or pretty much anything else instead. It's only provided
  1751. here because of the popular unrest that was stirred-up when I tried to remove it...
  1752. If you're really determined to use it, at least make sure that you never, ever,
  1753. pass any String objects to it as parameters.
  1754. */
  1755. static const String formatted (const juce_wchar* formatString, ... );
  1756. // Numeric conversions..
  1757. /** Creates a string containing this signed 32-bit integer as a decimal number.
  1758. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1759. */
  1760. explicit String (int decimalInteger);
  1761. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  1762. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1763. */
  1764. explicit String (unsigned int decimalInteger);
  1765. /** Creates a string containing this signed 16-bit integer as a decimal number.
  1766. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1767. */
  1768. explicit String (short decimalInteger);
  1769. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  1770. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  1771. */
  1772. explicit String (unsigned short decimalInteger);
  1773. /** Creates a string containing this signed 64-bit integer as a decimal number.
  1774. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1775. */
  1776. explicit String (int64 largeIntegerValue);
  1777. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  1778. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  1779. */
  1780. explicit String (uint64 largeIntegerValue);
  1781. /** Creates a string representing this floating-point number.
  1782. @param floatValue the value to convert to a string
  1783. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1784. decimal places, and will not use exponent notation. If 0 or
  1785. less, it will use exponent notation if necessary.
  1786. @see getDoubleValue, getIntValue
  1787. */
  1788. explicit String (float floatValue,
  1789. int numberOfDecimalPlaces = 0);
  1790. /** Creates a string representing this floating-point number.
  1791. @param doubleValue the value to convert to a string
  1792. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  1793. decimal places, and will not use exponent notation. If 0 or
  1794. less, it will use exponent notation if necessary.
  1795. @see getFloatValue, getIntValue
  1796. */
  1797. explicit String (double doubleValue,
  1798. int numberOfDecimalPlaces = 0);
  1799. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  1800. @returns the value of the string as a 32 bit signed base-10 integer.
  1801. @see getTrailingIntValue, getHexValue32, getHexValue64
  1802. */
  1803. int getIntValue() const throw();
  1804. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  1805. @returns the value of the string as a 64 bit signed base-10 integer.
  1806. */
  1807. int64 getLargeIntValue() const throw();
  1808. /** Parses a decimal number from the end of the string.
  1809. This will look for a value at the end of the string.
  1810. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  1811. Negative numbers are not handled, so "xyz-5" returns 5.
  1812. @see getIntValue
  1813. */
  1814. int getTrailingIntValue() const throw();
  1815. /** Parses this string as a floating point number.
  1816. @returns the value of the string as a 32-bit floating point value.
  1817. @see getDoubleValue
  1818. */
  1819. float getFloatValue() const throw();
  1820. /** Parses this string as a floating point number.
  1821. @returns the value of the string as a 64-bit floating point value.
  1822. @see getFloatValue
  1823. */
  1824. double getDoubleValue() const throw();
  1825. /** Parses the string as a hexadecimal number.
  1826. Non-hexadecimal characters in the string are ignored.
  1827. If the string contains too many characters, then the lowest significant
  1828. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  1829. @returns a 32-bit number which is the value of the string in hex.
  1830. */
  1831. int getHexValue32() const throw();
  1832. /** Parses the string as a hexadecimal number.
  1833. Non-hexadecimal characters in the string are ignored.
  1834. If the string contains too many characters, then the lowest significant
  1835. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  1836. @returns a 64-bit number which is the value of the string in hex.
  1837. */
  1838. int64 getHexValue64() const throw();
  1839. /** Creates a string representing this 32-bit value in hexadecimal. */
  1840. static const String toHexString (int number);
  1841. /** Creates a string representing this 64-bit value in hexadecimal. */
  1842. static const String toHexString (int64 number);
  1843. /** Creates a string representing this 16-bit value in hexadecimal. */
  1844. static const String toHexString (short number);
  1845. /** Creates a string containing a hex dump of a block of binary data.
  1846. @param data the binary data to use as input
  1847. @param size how many bytes of data to use
  1848. @param groupSize how many bytes are grouped together before inserting a
  1849. space into the output. e.g. group size 0 has no spaces,
  1850. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  1851. like "bea1 c2ff".
  1852. */
  1853. static const String toHexString (const unsigned char* data,
  1854. int size,
  1855. int groupSize = 1);
  1856. /** Returns a unicode version of this string.
  1857. Because it returns a reference to the string's internal data, the pointer
  1858. that is returned must not be stored anywhere, as it can become invalid whenever
  1859. any string methods (even some const ones!) are called.
  1860. */
  1861. inline operator const juce_wchar*() const throw() { return text; }
  1862. /** Returns a unicode version of this string.
  1863. Because it returns a reference to the string's internal data, the pointer
  1864. that is returned must not be stored anywhere, as it can become invalid whenever
  1865. any string methods (even some const ones!) are called.
  1866. */
  1867. inline operator juce_wchar*() throw() { return text; }
  1868. /** Returns a pointer to a UTF-8 version of this string.
  1869. Because it returns a reference to the string's internal data, the pointer
  1870. that is returned must not be stored anywhere, as it can be deleted whenever the
  1871. string changes.
  1872. @see getNumBytesAsUTF8, fromUTF8, copyToUTF8, toCString
  1873. */
  1874. const char* toUTF8() const;
  1875. /** Creates a String from a UTF-8 encoded buffer.
  1876. If the size is < 0, it'll keep reading until it hits a zero.
  1877. */
  1878. static const String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  1879. /** Returns the number of bytes required to represent this string as UTF8.
  1880. The number returned does NOT include the trailing zero.
  1881. @see toUTF8, copyToUTF8
  1882. */
  1883. int getNumBytesAsUTF8() const throw();
  1884. /** Copies the string to a buffer as UTF-8 characters.
  1885. Returns the number of bytes copied to the buffer, including the terminating null
  1886. character.
  1887. @param destBuffer the place to copy it to; if this is a null pointer,
  1888. the method just returns the number of bytes required
  1889. (including the terminating null character).
  1890. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1891. string won't fit, it'll put in as many as it can while
  1892. still allowing for a terminating null char at the end, and
  1893. will return the number of bytes that were actually used.
  1894. */
  1895. int copyToUTF8 (char* destBuffer, int maxBufferSizeBytes) const throw();
  1896. /** Returns a version of this string using the default 8-bit multi-byte system encoding.
  1897. Because it returns a reference to the string's internal data, the pointer
  1898. that is returned must not be stored anywhere, as it can be deleted whenever the
  1899. string changes.
  1900. @see getNumBytesAsCString, copyToCString, toUTF8
  1901. */
  1902. const char* toCString() const;
  1903. /** Returns the number of bytes
  1904. */
  1905. int getNumBytesAsCString() const throw();
  1906. /** Copies the string to a buffer.
  1907. @param destBuffer the place to copy it to; if this is a null pointer,
  1908. the method just returns the number of bytes required
  1909. (including the terminating null character).
  1910. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the
  1911. string won't fit, it'll put in as many as it can while
  1912. still allowing for a terminating null char at the end, and
  1913. will return the number of bytes that were actually used.
  1914. */
  1915. int copyToCString (char* destBuffer, int maxBufferSizeBytes) const throw();
  1916. /** Copies the string to a unicode buffer.
  1917. @param destBuffer the place to copy it to
  1918. @param maxCharsToCopy the maximum number of characters to copy to the buffer,
  1919. not including the tailing zero, so this shouldn't be
  1920. larger than the size of your destination buffer - 1
  1921. */
  1922. void copyToUnicode (juce_wchar* destBuffer, int maxCharsToCopy) const throw();
  1923. /** Increases the string's internally allocated storage.
  1924. Although the string's contents won't be affected by this call, it will
  1925. increase the amount of memory allocated internally for the string to grow into.
  1926. If you're about to make a large number of calls to methods such
  1927. as += or <<, it's more efficient to preallocate enough extra space
  1928. beforehand, so that these methods won't have to keep resizing the string
  1929. to append the extra characters.
  1930. @param numCharsNeeded the number of characters to allocate storage for. If this
  1931. value is less than the currently allocated size, it will
  1932. have no effect.
  1933. */
  1934. void preallocateStorage (size_t numCharsNeeded);
  1935. /** Swaps the contents of this string with another one.
  1936. This is a very fast operation, as no allocation or copying needs to be done.
  1937. */
  1938. void swapWith (String& other) throw();
  1939. /** A helper class to improve performance when concatenating many large strings
  1940. together.
  1941. Because appending one string to another involves measuring the length of
  1942. both strings, repeatedly doing this for many long strings will become
  1943. an exponentially slow operation. This class uses some internal state to
  1944. avoid that, so that each append operation only needs to measure the length
  1945. of the appended string.
  1946. */
  1947. class JUCE_API Concatenator
  1948. {
  1949. public:
  1950. Concatenator (String& stringToAppendTo);
  1951. ~Concatenator();
  1952. void append (const String& s);
  1953. private:
  1954. String& result;
  1955. int nextIndex;
  1956. Concatenator (const Concatenator&);
  1957. Concatenator& operator= (const Concatenator&);
  1958. };
  1959. juce_UseDebuggingNewOperator // (adds debugging info to find leaked objects)
  1960. private:
  1961. juce_wchar* text;
  1962. // internal constructor that preallocates a certain amount of memory
  1963. String (size_t numChars, int dummyVariable);
  1964. String (const String& stringToCopy, size_t charsToAllocate);
  1965. void createInternal (const juce_wchar* text, size_t numChars);
  1966. void appendInternal (const juce_wchar* text, int numExtraChars);
  1967. };
  1968. /** Concatenates two strings. */
  1969. const String JUCE_PUBLIC_FUNCTION operator+ (const char* string1, const String& string2);
  1970. /** Concatenates two strings. */
  1971. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* string1, const String& string2);
  1972. /** Concatenates two strings. */
  1973. const String JUCE_PUBLIC_FUNCTION operator+ (char string1, const String& string2);
  1974. /** Concatenates two strings. */
  1975. const String JUCE_PUBLIC_FUNCTION operator+ (juce_wchar string1, const String& string2);
  1976. /** Concatenates two strings. */
  1977. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2);
  1978. /** Concatenates two strings. */
  1979. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* string2);
  1980. /** Concatenates two strings. */
  1981. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* string2);
  1982. /** Concatenates two strings. */
  1983. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, char characterToAppend);
  1984. /** Concatenates two strings. */
  1985. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, juce_wchar characterToAppend);
  1986. /** Appends a character at the end of a string. */
  1987. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, char characterToAppend);
  1988. /** Appends a character at the end of a string. */
  1989. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, juce_wchar characterToAppend);
  1990. /** Appends a string to the end of the first one. */
  1991. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* string2);
  1992. /** Appends a string to the end of the first one. */
  1993. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* string2);
  1994. /** Appends a string to the end of the first one. */
  1995. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2);
  1996. /** Appends a decimal number at the end of a string. */
  1997. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, short number);
  1998. /** Appends a decimal number at the end of a string. */
  1999. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, int number);
  2000. /** Appends a decimal number at the end of a string. */
  2001. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, unsigned int number);
  2002. /** Appends a decimal number at the end of a string. */
  2003. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, long number);
  2004. /** Appends a decimal number at the end of a string. */
  2005. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, unsigned long number);
  2006. /** Appends a decimal number at the end of a string. */
  2007. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, float number);
  2008. /** Appends a decimal number at the end of a string. */
  2009. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, double number);
  2010. /** Case-sensitive comparison of two strings. */
  2011. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw();
  2012. /** Case-sensitive comparison of two strings. */
  2013. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw();
  2014. /** Case-sensitive comparison of two strings. */
  2015. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw();
  2016. /** Case-sensitive comparison of two strings. */
  2017. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw();
  2018. /** Case-sensitive comparison of two strings. */
  2019. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw();
  2020. /** Case-sensitive comparison of two strings. */
  2021. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw();
  2022. /** Case-sensitive comparison of two strings. */
  2023. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw();
  2024. /** Case-sensitive comparison of two strings. */
  2025. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw();
  2026. /** Case-sensitive comparison of two strings. */
  2027. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw();
  2028. /** Case-sensitive comparison of two strings. */
  2029. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw();
  2030. /** This streaming override allows you to pass a juce String directly into std output streams.
  2031. This is very handy for writing strings to std::cout, std::cerr, etc.
  2032. */
  2033. template <class charT, class traits>
  2034. std::basic_ostream <charT, traits>& JUCE_PUBLIC_FUNCTION operator<< (std::basic_ostream <charT, traits>& stream, const String& stringToWrite)
  2035. {
  2036. return stream << stringToWrite.toUTF8();
  2037. }
  2038. /** Writes a string to an OutputStream as UTF8. */
  2039. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text);
  2040. #endif // __JUCE_STRING_JUCEHEADER__
  2041. /*** End of inlined file: juce_String.h ***/
  2042. /**
  2043. Acts as an application-wide logging class.
  2044. A subclass of Logger can be created and passed into the Logger::setCurrentLogger
  2045. method and this will then be used by all calls to writeToLog.
  2046. The logger class also contains methods for writing messages to the debugger's
  2047. output stream.
  2048. @see FileLogger
  2049. */
  2050. class JUCE_API Logger
  2051. {
  2052. public:
  2053. /** Destructor. */
  2054. virtual ~Logger();
  2055. /** Sets the current logging class to use.
  2056. Note that the object passed in won't be deleted when no longer needed.
  2057. A null pointer can be passed-in to disable any logging.
  2058. If deleteOldLogger is set to true, the existing logger will be
  2059. deleted (if there is one).
  2060. */
  2061. static void JUCE_CALLTYPE setCurrentLogger (Logger* const newLogger,
  2062. const bool deleteOldLogger = false);
  2063. /** Writes a string to the current logger.
  2064. This will pass the string to the logger's logMessage() method if a logger
  2065. has been set.
  2066. @see logMessage
  2067. */
  2068. static void JUCE_CALLTYPE writeToLog (const String& message);
  2069. /** Writes a message to the standard error stream.
  2070. This can be called directly, or by using the DBG() macro in
  2071. juce_PlatformDefs.h (which will avoid calling the method in non-debug builds).
  2072. */
  2073. static void JUCE_CALLTYPE outputDebugString (const String& text);
  2074. protected:
  2075. Logger();
  2076. /** This is overloaded by subclasses to implement custom logging behaviour.
  2077. @see setCurrentLogger
  2078. */
  2079. virtual void logMessage (const String& message) = 0;
  2080. private:
  2081. static Logger* currentLogger;
  2082. };
  2083. #endif // __JUCE_LOGGER_JUCEHEADER__
  2084. /*** End of inlined file: juce_Logger.h ***/
  2085. END_JUCE_NAMESPACE
  2086. #endif // __JUCE_STANDARDHEADER_JUCEHEADER__
  2087. /*** End of inlined file: juce_StandardHeader.h ***/
  2088. BEGIN_JUCE_NAMESPACE
  2089. #if JUCE_MSVC
  2090. // this is set explicitly in case the app is using a different packing size.
  2091. #pragma pack (push, 8)
  2092. #pragma warning (push)
  2093. #pragma warning (disable: 4786) // (old vc6 warning about long class names)
  2094. #endif
  2095. // this is where all the class header files get brought in..
  2096. /*** Start of inlined file: juce_core_includes.h ***/
  2097. #ifndef __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2098. #define __JUCE_JUCE_CORE_INCLUDES_INCLUDEFILES__
  2099. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2100. /*** Start of inlined file: juce_Array.h ***/
  2101. #ifndef __JUCE_ARRAY_JUCEHEADER__
  2102. #define __JUCE_ARRAY_JUCEHEADER__
  2103. /*** Start of inlined file: juce_ArrayAllocationBase.h ***/
  2104. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2105. #define __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2106. /*** Start of inlined file: juce_HeapBlock.h ***/
  2107. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  2108. #define __JUCE_HEAPBLOCK_JUCEHEADER__
  2109. /**
  2110. Very simple container class to hold a pointer to some data on the heap.
  2111. When you need to allocate some heap storage for something, always try to use
  2112. this class instead of allocating the memory directly using malloc/free.
  2113. A HeapBlock<char> object can be treated in pretty much exactly the same way
  2114. as an char*, but as long as you allocate it on the stack or as a class member,
  2115. it's almost impossible for it to leak memory.
  2116. It also makes your code much more concise and readable than doing the same thing
  2117. using direct allocations,
  2118. E.g. instead of this:
  2119. @code
  2120. int* temp = (int*) juce_malloc (1024 * sizeof (int));
  2121. memcpy (temp, xyz, 1024 * sizeof (int));
  2122. juce_free (temp);
  2123. temp = (int*) juce_calloc (2048 * sizeof (int));
  2124. temp[0] = 1234;
  2125. memcpy (foobar, temp, 2048 * sizeof (int));
  2126. juce_free (temp);
  2127. @endcode
  2128. ..you could just write this:
  2129. @code
  2130. HeapBlock <int> temp (1024);
  2131. memcpy (temp, xyz, 1024 * sizeof (int));
  2132. temp.calloc (2048);
  2133. temp[0] = 1234;
  2134. memcpy (foobar, temp, 2048 * sizeof (int));
  2135. @endcode
  2136. The class is extremely lightweight, containing only a pointer to the
  2137. data, and exposes malloc/realloc/calloc/free methods that do the same jobs
  2138. as their less object-oriented counterparts. Despite adding safety, you probably
  2139. won't sacrifice any performance by using this in place of normal pointers.
  2140. @see Array, OwnedArray, MemoryBlock
  2141. */
  2142. template <class ElementType>
  2143. class HeapBlock
  2144. {
  2145. public:
  2146. /** Creates a HeapBlock which is initially just a null pointer.
  2147. After creation, you can resize the array using the malloc(), calloc(),
  2148. or realloc() methods.
  2149. */
  2150. HeapBlock() throw() : data (0)
  2151. {
  2152. }
  2153. /** Creates a HeapBlock containing a number of elements.
  2154. The contents of the block are undefined, as it will have been created by a
  2155. malloc call.
  2156. If you want an array of zero values, you can use the calloc() method instead.
  2157. */
  2158. explicit HeapBlock (const size_t numElements)
  2159. : data (static_cast <ElementType*> (::juce_malloc (numElements * sizeof (ElementType))))
  2160. {
  2161. }
  2162. /** Destructor.
  2163. This will free the data, if any has been allocated.
  2164. */
  2165. ~HeapBlock()
  2166. {
  2167. ::juce_free (data);
  2168. }
  2169. /** Returns a raw pointer to the allocated data.
  2170. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2171. freed by calling the free() method.
  2172. */
  2173. inline operator ElementType*() const throw() { return data; }
  2174. /** Returns a raw pointer to the allocated data.
  2175. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2176. freed by calling the free() method.
  2177. */
  2178. inline ElementType* getData() const throw() { return data; }
  2179. /** Returns a void pointer to the allocated data.
  2180. This may be a null pointer if the data hasn't yet been allocated, or if it has been
  2181. freed by calling the free() method.
  2182. */
  2183. inline operator void*() const throw() { return static_cast <void*> (data); }
  2184. /** Lets you use indirect calls to the first element in the array.
  2185. Obviously this will cause problems if the array hasn't been initialised, because it'll
  2186. be referencing a null pointer.
  2187. */
  2188. inline ElementType* operator->() const throw() { return data; }
  2189. /** Returns a reference to one of the data elements.
  2190. Obviously there's no bounds-checking here, as this object is just a dumb pointer and
  2191. has no idea of the size it currently has allocated.
  2192. */
  2193. template <typename IndexType>
  2194. inline ElementType& operator[] (IndexType index) const throw() { return data [index]; }
  2195. /** Returns a pointer to a data element at an offset from the start of the array.
  2196. This is the same as doing pointer arithmetic on the raw pointer itself.
  2197. */
  2198. template <typename IndexType>
  2199. inline ElementType* operator+ (IndexType index) const throw() { return data + index; }
  2200. /** Returns a reference to the raw data pointer.
  2201. Beware that the pointer returned here will become invalid as soon as you call
  2202. any of the allocator methods on this object!
  2203. */
  2204. inline ElementType* const* operator&() const throw() { return static_cast <ElementType* const*> (&data); }
  2205. /** Returns a reference to the raw data pointer.
  2206. Beware that the pointer returned here will become invalid as soon as you call
  2207. any of the allocator methods on this object!
  2208. */
  2209. inline ElementType** operator&() throw() { return static_cast <ElementType**> (&data); }
  2210. /** Compares the pointer with another pointer.
  2211. This can be handy for checking whether this is a null pointer.
  2212. */
  2213. inline bool operator== (const ElementType* const otherPointer) const throw() { return otherPointer == data; }
  2214. /** Compares the pointer with another pointer.
  2215. This can be handy for checking whether this is a null pointer.
  2216. */
  2217. inline bool operator!= (const ElementType* const otherPointer) const throw() { return otherPointer != data; }
  2218. /** Allocates a specified amount of memory.
  2219. This uses the normal malloc to allocate an amount of memory for this object.
  2220. Any previously allocated memory will be freed by this method.
  2221. The number of bytes allocated will be (newNumElements * elementSize). Normally
  2222. you wouldn't need to specify the second parameter, but it can be handy if you need
  2223. to allocate a size in bytes rather than in terms of the number of elements.
  2224. The data that is allocated will be freed when this object is deleted, or when you
  2225. call free() or any of the allocation methods.
  2226. */
  2227. void malloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2228. {
  2229. ::juce_free (data);
  2230. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2231. }
  2232. /** Allocates a specified amount of memory and clears it.
  2233. This does the same job as the malloc() method, but clears the memory that it allocates.
  2234. */
  2235. void calloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2236. {
  2237. ::juce_free (data);
  2238. data = static_cast <ElementType*> (::juce_calloc (newNumElements * elementSize));
  2239. }
  2240. /** Allocates a specified amount of memory and optionally clears it.
  2241. This does the same job as either malloc() or calloc(), depending on the
  2242. initialiseToZero parameter.
  2243. */
  2244. void allocate (const size_t newNumElements, const bool initialiseToZero)
  2245. {
  2246. ::juce_free (data);
  2247. if (initialiseToZero)
  2248. data = static_cast <ElementType*> (::juce_calloc (newNumElements * sizeof (ElementType)));
  2249. else
  2250. data = static_cast <ElementType*> (::juce_malloc (newNumElements * sizeof (ElementType)));
  2251. }
  2252. /** Re-allocates a specified amount of memory.
  2253. The semantics of this method are the same as malloc() and calloc(), but it
  2254. uses realloc() to keep as much of the existing data as possible.
  2255. */
  2256. void realloc (const size_t newNumElements, const size_t elementSize = sizeof (ElementType))
  2257. {
  2258. if (data == 0)
  2259. data = static_cast <ElementType*> (::juce_malloc (newNumElements * elementSize));
  2260. else
  2261. data = static_cast <ElementType*> (::juce_realloc (data, newNumElements * elementSize));
  2262. }
  2263. /** Frees any currently-allocated data.
  2264. This will free the data and reset this object to be a null pointer.
  2265. */
  2266. void free()
  2267. {
  2268. ::juce_free (data);
  2269. data = 0;
  2270. }
  2271. /** Swaps this object's data with the data of another HeapBlock.
  2272. The two objects simply exchange their data pointers.
  2273. */
  2274. void swapWith (HeapBlock <ElementType>& other) throw()
  2275. {
  2276. swapVariables (data, other.data);
  2277. }
  2278. private:
  2279. ElementType* data;
  2280. HeapBlock (const HeapBlock&);
  2281. HeapBlock& operator= (const HeapBlock&);
  2282. };
  2283. #endif // __JUCE_HEAPBLOCK_JUCEHEADER__
  2284. /*** End of inlined file: juce_HeapBlock.h ***/
  2285. /**
  2286. Implements some basic array storage allocation functions.
  2287. This class isn't really for public use - it's used by the other
  2288. array classes, but might come in handy for some purposes.
  2289. It inherits from a critical section class to allow the arrays to use
  2290. the "empty base class optimisation" pattern to reduce their footprint.
  2291. @see Array, OwnedArray, ReferenceCountedArray
  2292. */
  2293. template <class ElementType, class TypeOfCriticalSectionToUse>
  2294. class ArrayAllocationBase : public TypeOfCriticalSectionToUse
  2295. {
  2296. public:
  2297. /** Creates an empty array. */
  2298. ArrayAllocationBase() throw()
  2299. : numAllocated (0)
  2300. {
  2301. }
  2302. /** Destructor. */
  2303. ~ArrayAllocationBase()
  2304. {
  2305. }
  2306. /** Changes the amount of storage allocated.
  2307. This will retain any data currently held in the array, and either add or
  2308. remove extra space at the end.
  2309. @param numElements the number of elements that are needed
  2310. */
  2311. void setAllocatedSize (const int numElements)
  2312. {
  2313. if (numAllocated != numElements)
  2314. {
  2315. if (numElements > 0)
  2316. elements.realloc (numElements);
  2317. else
  2318. elements.free();
  2319. numAllocated = numElements;
  2320. }
  2321. }
  2322. /** Increases the amount of storage allocated if it is less than a given amount.
  2323. This will retain any data currently held in the array, but will add
  2324. extra space at the end to make sure there it's at least as big as the size
  2325. passed in. If it's already bigger, no action is taken.
  2326. @param minNumElements the minimum number of elements that are needed
  2327. */
  2328. void ensureAllocatedSize (const int minNumElements)
  2329. {
  2330. if (minNumElements > numAllocated)
  2331. setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
  2332. }
  2333. /** Minimises the amount of storage allocated so that it's no more than
  2334. the given number of elements.
  2335. */
  2336. void shrinkToNoMoreThan (const int maxNumElements)
  2337. {
  2338. if (maxNumElements < numAllocated)
  2339. setAllocatedSize (maxNumElements);
  2340. }
  2341. /** Swap the contents of two objects. */
  2342. void swapWith (ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse>& other) throw()
  2343. {
  2344. elements.swapWith (other.elements);
  2345. swapVariables (numAllocated, other.numAllocated);
  2346. }
  2347. HeapBlock <ElementType> elements;
  2348. int numAllocated;
  2349. private:
  2350. ArrayAllocationBase (const ArrayAllocationBase&);
  2351. ArrayAllocationBase& operator= (const ArrayAllocationBase&);
  2352. };
  2353. #endif // __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  2354. /*** End of inlined file: juce_ArrayAllocationBase.h ***/
  2355. /*** Start of inlined file: juce_ElementComparator.h ***/
  2356. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2357. #define __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2358. /**
  2359. Sorts a range of elements in an array.
  2360. The comparator object that is passed-in must define a public method with the following
  2361. signature:
  2362. @code
  2363. int compareElements (ElementType first, ElementType second);
  2364. @endcode
  2365. ..and this method must return:
  2366. - a value of < 0 if the first comes before the second
  2367. - a value of 0 if the two objects are equivalent
  2368. - a value of > 0 if the second comes before the first
  2369. To improve performance, the compareElements() method can be declared as static or const.
  2370. @param comparator an object which defines a compareElements() method
  2371. @param array the array to sort
  2372. @param firstElement the index of the first element of the range to be sorted
  2373. @param lastElement the index of the last element in the range that needs
  2374. sorting (this is inclusive)
  2375. @param retainOrderOfEquivalentItems if true, the order of items that the
  2376. comparator deems the same will be maintained - this will be
  2377. a slower algorithm than if they are allowed to be moved around.
  2378. @see sortArrayRetainingOrder
  2379. */
  2380. template <class ElementType, class ElementComparator>
  2381. static void sortArray (ElementComparator& comparator,
  2382. ElementType* const array,
  2383. int firstElement,
  2384. int lastElement,
  2385. const bool retainOrderOfEquivalentItems)
  2386. {
  2387. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2388. // avoids getting warning messages about the parameter being unused
  2389. if (lastElement > firstElement)
  2390. {
  2391. if (retainOrderOfEquivalentItems)
  2392. {
  2393. for (int i = firstElement; i < lastElement; ++i)
  2394. {
  2395. if (comparator.compareElements (array[i], array [i + 1]) > 0)
  2396. {
  2397. const ElementType temp = array [i];
  2398. array [i] = array[i + 1];
  2399. array [i + 1] = temp;
  2400. if (i > firstElement)
  2401. i -= 2;
  2402. }
  2403. }
  2404. }
  2405. else
  2406. {
  2407. int fromStack[30], toStack[30];
  2408. int stackIndex = 0;
  2409. for (;;)
  2410. {
  2411. const int size = (lastElement - firstElement) + 1;
  2412. if (size <= 8)
  2413. {
  2414. int j = lastElement;
  2415. int maxIndex;
  2416. while (j > firstElement)
  2417. {
  2418. maxIndex = firstElement;
  2419. for (int k = firstElement + 1; k <= j; ++k)
  2420. if (comparator.compareElements (array[k], array [maxIndex]) > 0)
  2421. maxIndex = k;
  2422. const ElementType temp = array [maxIndex];
  2423. array [maxIndex] = array[j];
  2424. array [j] = temp;
  2425. --j;
  2426. }
  2427. }
  2428. else
  2429. {
  2430. const int mid = firstElement + (size >> 1);
  2431. ElementType temp = array [mid];
  2432. array [mid] = array [firstElement];
  2433. array [firstElement] = temp;
  2434. int i = firstElement;
  2435. int j = lastElement + 1;
  2436. for (;;)
  2437. {
  2438. while (++i <= lastElement
  2439. && comparator.compareElements (array[i], array [firstElement]) <= 0)
  2440. {}
  2441. while (--j > firstElement
  2442. && comparator.compareElements (array[j], array [firstElement]) >= 0)
  2443. {}
  2444. if (j < i)
  2445. break;
  2446. temp = array[i];
  2447. array[i] = array[j];
  2448. array[j] = temp;
  2449. }
  2450. temp = array [firstElement];
  2451. array [firstElement] = array[j];
  2452. array [j] = temp;
  2453. if (j - 1 - firstElement >= lastElement - i)
  2454. {
  2455. if (firstElement + 1 < j)
  2456. {
  2457. fromStack [stackIndex] = firstElement;
  2458. toStack [stackIndex] = j - 1;
  2459. ++stackIndex;
  2460. }
  2461. if (i < lastElement)
  2462. {
  2463. firstElement = i;
  2464. continue;
  2465. }
  2466. }
  2467. else
  2468. {
  2469. if (i < lastElement)
  2470. {
  2471. fromStack [stackIndex] = i;
  2472. toStack [stackIndex] = lastElement;
  2473. ++stackIndex;
  2474. }
  2475. if (firstElement + 1 < j)
  2476. {
  2477. lastElement = j - 1;
  2478. continue;
  2479. }
  2480. }
  2481. }
  2482. if (--stackIndex < 0)
  2483. break;
  2484. jassert (stackIndex < numElementsInArray (fromStack));
  2485. firstElement = fromStack [stackIndex];
  2486. lastElement = toStack [stackIndex];
  2487. }
  2488. }
  2489. }
  2490. }
  2491. /**
  2492. Searches a sorted array of elements, looking for the index at which a specified value
  2493. should be inserted for it to be in the correct order.
  2494. The comparator object that is passed-in must define a public method with the following
  2495. signature:
  2496. @code
  2497. int compareElements (ElementType first, ElementType second);
  2498. @endcode
  2499. ..and this method must return:
  2500. - a value of < 0 if the first comes before the second
  2501. - a value of 0 if the two objects are equivalent
  2502. - a value of > 0 if the second comes before the first
  2503. To improve performance, the compareElements() method can be declared as static or const.
  2504. @param comparator an object which defines a compareElements() method
  2505. @param array the array to search
  2506. @param newElement the value that is going to be inserted
  2507. @param firstElement the index of the first element to search
  2508. @param lastElement the index of the last element in the range (this is non-inclusive)
  2509. */
  2510. template <class ElementType, class ElementComparator>
  2511. static int findInsertIndexInSortedArray (ElementComparator& comparator,
  2512. ElementType* const array,
  2513. const ElementType newElement,
  2514. int firstElement,
  2515. int lastElement)
  2516. {
  2517. jassert (firstElement <= lastElement);
  2518. (void) comparator; // if you pass in an object with a static compareElements() method, this
  2519. // avoids getting warning messages about the parameter being unused
  2520. while (firstElement < lastElement)
  2521. {
  2522. if (comparator.compareElements (newElement, array [firstElement]) == 0)
  2523. {
  2524. ++firstElement;
  2525. break;
  2526. }
  2527. else
  2528. {
  2529. const int halfway = (firstElement + lastElement) >> 1;
  2530. if (halfway == firstElement)
  2531. {
  2532. if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2533. ++firstElement;
  2534. break;
  2535. }
  2536. else if (comparator.compareElements (newElement, array [halfway]) >= 0)
  2537. {
  2538. firstElement = halfway;
  2539. }
  2540. else
  2541. {
  2542. lastElement = halfway;
  2543. }
  2544. }
  2545. }
  2546. return firstElement;
  2547. }
  2548. /**
  2549. A simple ElementComparator class that can be used to sort an array of
  2550. objects that support the '<' operator.
  2551. This will work for primitive types and objects that implement operator<().
  2552. Example: @code
  2553. Array <int> myArray;
  2554. DefaultElementComparator<int> sorter;
  2555. myArray.sort (sorter);
  2556. @endcode
  2557. @see ElementComparator
  2558. */
  2559. template <class ElementType>
  2560. class DefaultElementComparator
  2561. {
  2562. private:
  2563. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2564. public:
  2565. static int compareElements (ParameterType first, ParameterType second)
  2566. {
  2567. return (first < second) ? -1 : ((second < first) ? 1 : 0);
  2568. }
  2569. };
  2570. #endif // __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  2571. /*** End of inlined file: juce_ElementComparator.h ***/
  2572. /*** Start of inlined file: juce_CriticalSection.h ***/
  2573. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  2574. #define __JUCE_CRITICALSECTION_JUCEHEADER__
  2575. class JUCE_API ScopedLock;
  2576. class JUCE_API ScopedUnlock;
  2577. /**
  2578. Prevents multiple threads from accessing shared objects at the same time.
  2579. @see ScopedLock, Thread, InterProcessLock
  2580. */
  2581. class JUCE_API CriticalSection
  2582. {
  2583. public:
  2584. /**
  2585. Creates a CriticalSection object
  2586. */
  2587. CriticalSection() throw();
  2588. /** Destroys a CriticalSection object.
  2589. If the critical section is deleted whilst locked, its subsequent behaviour
  2590. is unpredictable.
  2591. */
  2592. ~CriticalSection() throw();
  2593. /** Locks this critical section.
  2594. If the lock is currently held by another thread, this will wait until it
  2595. becomes free.
  2596. If the lock is already held by the caller thread, the method returns immediately.
  2597. @see exit, ScopedLock
  2598. */
  2599. void enter() const throw();
  2600. /** Attempts to lock this critical section without blocking.
  2601. This method behaves identically to CriticalSection::enter, except that the caller thread
  2602. does not wait if the lock is currently held by another thread but returns false immediately.
  2603. @returns false if the lock is currently held by another thread, true otherwise.
  2604. @see enter
  2605. */
  2606. bool tryEnter() const throw();
  2607. /** Releases the lock.
  2608. If the caller thread hasn't got the lock, this can have unpredictable results.
  2609. If the enter() method has been called multiple times by the thread, each
  2610. call must be matched by a call to exit() before other threads will be allowed
  2611. to take over the lock.
  2612. @see enter, ScopedLock
  2613. */
  2614. void exit() const throw();
  2615. /** Provides the type of scoped lock to use with this type of critical section object. */
  2616. typedef ScopedLock ScopedLockType;
  2617. /** Provides the type of scoped unlocker to use with this type of critical section object. */
  2618. typedef ScopedUnlock ScopedUnlockType;
  2619. juce_UseDebuggingNewOperator
  2620. private:
  2621. #if JUCE_WINDOWS
  2622. #if JUCE_64BIT
  2623. // To avoid including windows.h in the public Juce includes, we'll just allocate a
  2624. // block of memory here that's big enough to be used internally as a windows critical
  2625. // section object.
  2626. uint8 internal [44];
  2627. #else
  2628. uint8 internal [24];
  2629. #endif
  2630. #else
  2631. mutable pthread_mutex_t internal;
  2632. #endif
  2633. CriticalSection (const CriticalSection&);
  2634. CriticalSection& operator= (const CriticalSection&);
  2635. };
  2636. /**
  2637. A class that can be used in place of a real CriticalSection object.
  2638. This is currently used by some templated classes, and should get
  2639. optimised out by the compiler.
  2640. @see Array, OwnedArray, ReferenceCountedArray
  2641. */
  2642. class JUCE_API DummyCriticalSection
  2643. {
  2644. public:
  2645. inline DummyCriticalSection() throw() {}
  2646. inline ~DummyCriticalSection() throw() {}
  2647. inline void enter() const throw() {}
  2648. inline void exit() const throw() {}
  2649. /** A dummy scoped-lock type to use with a dummy critical section. */
  2650. struct ScopedLockType
  2651. {
  2652. ScopedLockType (const DummyCriticalSection&) throw() {}
  2653. };
  2654. /** A dummy scoped-unlocker type to use with a dummy critical section. */
  2655. typedef ScopedLockType ScopedUnlockType;
  2656. private:
  2657. DummyCriticalSection (const DummyCriticalSection&);
  2658. DummyCriticalSection& operator= (const DummyCriticalSection&);
  2659. };
  2660. #endif // __JUCE_CRITICALSECTION_JUCEHEADER__
  2661. /*** End of inlined file: juce_CriticalSection.h ***/
  2662. /**
  2663. Holds a list of simple objects, such as ints, doubles, or pointers.
  2664. Examples of arrays are: Array<int>, Array<Rectangle> or Array<MyClass*>
  2665. The array can be used to hold simple, non-polymorphic objects as well as primitive types - to
  2666. do so, the class must fulfil these requirements:
  2667. - it must have a copy constructor and operator=
  2668. - it must be able to be relocated in memory by a memcpy without this causing a problem - so no
  2669. objects whose functionality relies on pointers or references to themselves can be used.
  2670. You can of course have an array of pointers to any kind of object, e.g. Array <MyClass*>, but if
  2671. you do this, the array doesn't take any ownership of the objects - see the OwnedArray class or the
  2672. ReferenceCountedArray class for more powerful ways of holding lists of objects.
  2673. For holding lists of strings, you can use Array\<String\>, but it's usually better to use the
  2674. specialised class StringArray, which provides more useful functions.
  2675. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  2676. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  2677. @see OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  2678. */
  2679. template <typename ElementType,
  2680. typename TypeOfCriticalSectionToUse = DummyCriticalSection>
  2681. class Array
  2682. {
  2683. private:
  2684. #if defined (_MSC_VER) && _MSC_VER <= 1400
  2685. typedef const ElementType& ParameterType;
  2686. #else
  2687. typedef PARAMETER_TYPE (ElementType) ParameterType;
  2688. #endif
  2689. public:
  2690. /** Creates an empty array. */
  2691. Array() throw()
  2692. : numUsed (0)
  2693. {
  2694. }
  2695. /** Creates a copy of another array.
  2696. @param other the array to copy
  2697. */
  2698. Array (const Array<ElementType, TypeOfCriticalSectionToUse>& other)
  2699. {
  2700. const ScopedLockType lock (other.getLock());
  2701. numUsed = other.numUsed;
  2702. data.setAllocatedSize (other.numUsed);
  2703. for (int i = 0; i < numUsed; ++i)
  2704. new (data.elements + i) ElementType (other.data.elements[i]);
  2705. }
  2706. /** Initalises from a null-terminated C array of values.
  2707. @param values the array to copy from
  2708. */
  2709. template <typename TypeToCreateFrom>
  2710. explicit Array (const TypeToCreateFrom* values)
  2711. : numUsed (0)
  2712. {
  2713. while (*values != TypeToCreateFrom())
  2714. add (*values++);
  2715. }
  2716. /** Initalises from a C array of values.
  2717. @param values the array to copy from
  2718. @param numValues the number of values in the array
  2719. */
  2720. template <typename TypeToCreateFrom>
  2721. Array (const TypeToCreateFrom* values, int numValues)
  2722. : numUsed (numValues)
  2723. {
  2724. data.setAllocatedSize (numValues);
  2725. for (int i = 0; i < numValues; ++i)
  2726. new (data.elements + i) ElementType (values[i]);
  2727. }
  2728. /** Destructor. */
  2729. ~Array()
  2730. {
  2731. for (int i = 0; i < numUsed; ++i)
  2732. data.elements[i].~ElementType();
  2733. }
  2734. /** Copies another array.
  2735. @param other the array to copy
  2736. */
  2737. Array& operator= (const Array& other)
  2738. {
  2739. if (this != &other)
  2740. {
  2741. Array<ElementType, TypeOfCriticalSectionToUse> otherCopy (other);
  2742. swapWithArray (otherCopy);
  2743. }
  2744. return *this;
  2745. }
  2746. /** Compares this array to another one.
  2747. Two arrays are considered equal if they both contain the same set of
  2748. elements, in the same order.
  2749. @param other the other array to compare with
  2750. */
  2751. template <class OtherArrayType>
  2752. bool operator== (const OtherArrayType& other) const
  2753. {
  2754. const ScopedLockType lock (getLock());
  2755. if (numUsed != other.numUsed)
  2756. return false;
  2757. for (int i = numUsed; --i >= 0;)
  2758. if (! (data.elements [i] == other.data.elements [i]))
  2759. return false;
  2760. return true;
  2761. }
  2762. /** Compares this array to another one.
  2763. Two arrays are considered equal if they both contain the same set of
  2764. elements, in the same order.
  2765. @param other the other array to compare with
  2766. */
  2767. template <class OtherArrayType>
  2768. bool operator!= (const OtherArrayType& other) const
  2769. {
  2770. return ! operator== (other);
  2771. }
  2772. /** Removes all elements from the array.
  2773. This will remove all the elements, and free any storage that the array is
  2774. using. To clear the array without freeing the storage, use the clearQuick()
  2775. method instead.
  2776. @see clearQuick
  2777. */
  2778. void clear()
  2779. {
  2780. const ScopedLockType lock (getLock());
  2781. for (int i = 0; i < numUsed; ++i)
  2782. data.elements[i].~ElementType();
  2783. data.setAllocatedSize (0);
  2784. numUsed = 0;
  2785. }
  2786. /** Removes all elements from the array without freeing the array's allocated storage.
  2787. @see clear
  2788. */
  2789. void clearQuick()
  2790. {
  2791. const ScopedLockType lock (getLock());
  2792. for (int i = 0; i < numUsed; ++i)
  2793. data.elements[i].~ElementType();
  2794. numUsed = 0;
  2795. }
  2796. /** Returns the current number of elements in the array.
  2797. */
  2798. inline int size() const throw()
  2799. {
  2800. return numUsed;
  2801. }
  2802. /** Returns one of the elements in the array.
  2803. If the index passed in is beyond the range of valid elements, this
  2804. will return zero.
  2805. If you're certain that the index will always be a valid element, you
  2806. can call getUnchecked() instead, which is faster.
  2807. @param index the index of the element being requested (0 is the first element in the array)
  2808. @see getUnchecked, getFirst, getLast
  2809. */
  2810. inline ElementType operator[] (const int index) const
  2811. {
  2812. const ScopedLockType lock (getLock());
  2813. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  2814. : ElementType();
  2815. }
  2816. /** Returns one of the elements in the array, without checking the index passed in.
  2817. Unlike the operator[] method, this will try to return an element without
  2818. checking that the index is within the bounds of the array, so should only
  2819. be used when you're confident that it will always be a valid index.
  2820. @param index the index of the element being requested (0 is the first element in the array)
  2821. @see operator[], getFirst, getLast
  2822. */
  2823. inline const ElementType getUnchecked (const int index) const
  2824. {
  2825. const ScopedLockType lock (getLock());
  2826. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2827. return data.elements [index];
  2828. }
  2829. /** Returns a direct reference to one of the elements in the array, without checking the index passed in.
  2830. This is like getUnchecked, but returns a direct reference to the element, so that
  2831. you can alter it directly. Obviously this can be dangerous, so only use it when
  2832. absolutely necessary.
  2833. @param index the index of the element being requested (0 is the first element in the array)
  2834. @see operator[], getFirst, getLast
  2835. */
  2836. inline ElementType& getReference (const int index) const throw()
  2837. {
  2838. const ScopedLockType lock (getLock());
  2839. jassert (((unsigned int) index) < (unsigned int) numUsed);
  2840. return data.elements [index];
  2841. }
  2842. /** Returns the first element in the array, or 0 if the array is empty.
  2843. @see operator[], getUnchecked, getLast
  2844. */
  2845. inline ElementType getFirst() const
  2846. {
  2847. const ScopedLockType lock (getLock());
  2848. return (numUsed > 0) ? data.elements [0]
  2849. : ElementType();
  2850. }
  2851. /** Returns the last element in the array, or 0 if the array is empty.
  2852. @see operator[], getUnchecked, getFirst
  2853. */
  2854. inline ElementType getLast() const
  2855. {
  2856. const ScopedLockType lock (getLock());
  2857. return (numUsed > 0) ? data.elements [numUsed - 1]
  2858. : ElementType();
  2859. }
  2860. /** Returns a pointer to the actual array data.
  2861. This pointer will only be valid until the next time a non-const method
  2862. is called on the array.
  2863. */
  2864. inline ElementType* getRawDataPointer() throw()
  2865. {
  2866. return data.elements;
  2867. }
  2868. /** Finds the index of the first element which matches the value passed in.
  2869. This will search the array for the given object, and return the index
  2870. of its first occurrence. If the object isn't found, the method will return -1.
  2871. @param elementToLookFor the value or object to look for
  2872. @returns the index of the object, or -1 if it's not found
  2873. */
  2874. int indexOf (ParameterType elementToLookFor) const
  2875. {
  2876. const ScopedLockType lock (getLock());
  2877. const ElementType* e = data.elements.getData();
  2878. const ElementType* const end = e + numUsed;
  2879. while (e != end)
  2880. {
  2881. if (elementToLookFor == *e)
  2882. return static_cast <int> (e - data.elements.getData());
  2883. ++e;
  2884. }
  2885. return -1;
  2886. }
  2887. /** Returns true if the array contains at least one occurrence of an object.
  2888. @param elementToLookFor the value or object to look for
  2889. @returns true if the item is found
  2890. */
  2891. bool contains (ParameterType elementToLookFor) const
  2892. {
  2893. const ScopedLockType lock (getLock());
  2894. const ElementType* e = data.elements.getData();
  2895. const ElementType* const end = e + numUsed;
  2896. while (e != end)
  2897. {
  2898. if (elementToLookFor == *e)
  2899. return true;
  2900. ++e;
  2901. }
  2902. return false;
  2903. }
  2904. /** Appends a new element at the end of the array.
  2905. @param newElement the new object to add to the array
  2906. @see set, insert, addIfNotAlreadyThere, addSorted, addUsingDefaultSort, addArray
  2907. */
  2908. void add (ParameterType newElement)
  2909. {
  2910. const ScopedLockType lock (getLock());
  2911. data.ensureAllocatedSize (numUsed + 1);
  2912. new (data.elements + numUsed++) ElementType (newElement);
  2913. }
  2914. /** Inserts a new element into the array at a given position.
  2915. If the index is less than 0 or greater than the size of the array, the
  2916. element will be added to the end of the array.
  2917. Otherwise, it will be inserted into the array, moving all the later elements
  2918. along to make room.
  2919. @param indexToInsertAt the index at which the new element should be
  2920. inserted (pass in -1 to add it to the end)
  2921. @param newElement the new object to add to the array
  2922. @see add, addSorted, addUsingDefaultSort, set
  2923. */
  2924. void insert (int indexToInsertAt, ParameterType newElement)
  2925. {
  2926. const ScopedLockType lock (getLock());
  2927. data.ensureAllocatedSize (numUsed + 1);
  2928. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2929. {
  2930. ElementType* const insertPos = data.elements + indexToInsertAt;
  2931. const int numberToMove = numUsed - indexToInsertAt;
  2932. if (numberToMove > 0)
  2933. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  2934. new (insertPos) ElementType (newElement);
  2935. ++numUsed;
  2936. }
  2937. else
  2938. {
  2939. new (data.elements + numUsed++) ElementType (newElement);
  2940. }
  2941. }
  2942. /** Inserts multiple copies of an element into the array at a given position.
  2943. If the index is less than 0 or greater than the size of the array, the
  2944. element will be added to the end of the array.
  2945. Otherwise, it will be inserted into the array, moving all the later elements
  2946. along to make room.
  2947. @param indexToInsertAt the index at which the new element should be inserted
  2948. @param newElement the new object to add to the array
  2949. @param numberOfTimesToInsertIt how many copies of the value to insert
  2950. @see insert, add, addSorted, set
  2951. */
  2952. void insertMultiple (int indexToInsertAt, ParameterType newElement,
  2953. int numberOfTimesToInsertIt)
  2954. {
  2955. if (numberOfTimesToInsertIt > 0)
  2956. {
  2957. const ScopedLockType lock (getLock());
  2958. data.ensureAllocatedSize (numUsed + numberOfTimesToInsertIt);
  2959. ElementType* insertPos;
  2960. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2961. {
  2962. insertPos = data.elements + indexToInsertAt;
  2963. const int numberToMove = numUsed - indexToInsertAt;
  2964. memmove (insertPos + numberOfTimesToInsertIt, insertPos, numberToMove * sizeof (ElementType));
  2965. }
  2966. else
  2967. {
  2968. insertPos = data.elements + numUsed;
  2969. }
  2970. numUsed += numberOfTimesToInsertIt;
  2971. while (--numberOfTimesToInsertIt >= 0)
  2972. new (insertPos++) ElementType (newElement);
  2973. }
  2974. }
  2975. /** Inserts an array of values into this array at a given position.
  2976. If the index is less than 0 or greater than the size of the array, the
  2977. new elements will be added to the end of the array.
  2978. Otherwise, they will be inserted into the array, moving all the later elements
  2979. along to make room.
  2980. @param indexToInsertAt the index at which the first new element should be inserted
  2981. @param newElements the new values to add to the array
  2982. @param numberOfElements how many items are in the array
  2983. @see insert, add, addSorted, set
  2984. */
  2985. void insertArray (int indexToInsertAt,
  2986. const ElementType* newElements,
  2987. int numberOfElements)
  2988. {
  2989. if (numberOfElements > 0)
  2990. {
  2991. const ScopedLockType lock (getLock());
  2992. data.ensureAllocatedSize (numUsed + numberOfElements);
  2993. ElementType* insertPos;
  2994. if (((unsigned int) indexToInsertAt) < (unsigned int) numUsed)
  2995. {
  2996. insertPos = data.elements + indexToInsertAt;
  2997. const int numberToMove = numUsed - indexToInsertAt;
  2998. memmove (insertPos + numberOfElements, insertPos, numberToMove * sizeof (ElementType));
  2999. }
  3000. else
  3001. {
  3002. insertPos = data.elements + numUsed;
  3003. }
  3004. numUsed += numberOfElements;
  3005. while (--numberOfElements >= 0)
  3006. new (insertPos++) ElementType (*newElements++);
  3007. }
  3008. }
  3009. /** Appends a new element at the end of the array as long as the array doesn't
  3010. already contain it.
  3011. If the array already contains an element that matches the one passed in, nothing
  3012. will be done.
  3013. @param newElement the new object to add to the array
  3014. */
  3015. void addIfNotAlreadyThere (ParameterType newElement)
  3016. {
  3017. const ScopedLockType lock (getLock());
  3018. if (! contains (newElement))
  3019. add (newElement);
  3020. }
  3021. /** Replaces an element with a new value.
  3022. If the index is less than zero, this method does nothing.
  3023. If the index is beyond the end of the array, the item is added to the end of the array.
  3024. @param indexToChange the index whose value you want to change
  3025. @param newValue the new value to set for this index.
  3026. @see add, insert
  3027. */
  3028. void set (const int indexToChange, ParameterType newValue)
  3029. {
  3030. jassert (indexToChange >= 0);
  3031. const ScopedLockType lock (getLock());
  3032. if (((unsigned int) indexToChange) < (unsigned int) numUsed)
  3033. {
  3034. data.elements [indexToChange] = newValue;
  3035. }
  3036. else if (indexToChange >= 0)
  3037. {
  3038. data.ensureAllocatedSize (numUsed + 1);
  3039. new (data.elements + numUsed++) ElementType (newValue);
  3040. }
  3041. }
  3042. /** Replaces an element with a new value without doing any bounds-checking.
  3043. This just sets a value directly in the array's internal storage, so you'd
  3044. better make sure it's in range!
  3045. @param indexToChange the index whose value you want to change
  3046. @param newValue the new value to set for this index.
  3047. @see set, getUnchecked
  3048. */
  3049. void setUnchecked (const int indexToChange, ParameterType newValue)
  3050. {
  3051. const ScopedLockType lock (getLock());
  3052. jassert (((unsigned int) indexToChange) < (unsigned int) numUsed);
  3053. data.elements [indexToChange] = newValue;
  3054. }
  3055. /** Adds elements from an array to the end of this array.
  3056. @param elementsToAdd the array of elements to add
  3057. @param numElementsToAdd how many elements are in this other array
  3058. @see add
  3059. */
  3060. void addArray (const ElementType* elementsToAdd, int numElementsToAdd)
  3061. {
  3062. const ScopedLockType lock (getLock());
  3063. if (numElementsToAdd > 0)
  3064. {
  3065. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  3066. while (--numElementsToAdd >= 0)
  3067. {
  3068. new (data.elements + numUsed) ElementType (*elementsToAdd++);
  3069. ++numUsed;
  3070. }
  3071. }
  3072. }
  3073. /** This swaps the contents of this array with those of another array.
  3074. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  3075. because it just swaps their internal pointers.
  3076. */
  3077. void swapWithArray (Array& otherArray) throw()
  3078. {
  3079. const ScopedLockType lock1 (getLock());
  3080. const ScopedLockType lock2 (otherArray.getLock());
  3081. data.swapWith (otherArray.data);
  3082. swapVariables (numUsed, otherArray.numUsed);
  3083. }
  3084. /** Adds elements from another array to the end of this array.
  3085. @param arrayToAddFrom the array from which to copy the elements
  3086. @param startIndex the first element of the other array to start copying from
  3087. @param numElementsToAdd how many elements to add from the other array. If this
  3088. value is negative or greater than the number of available elements,
  3089. all available elements will be copied.
  3090. @see add
  3091. */
  3092. template <class OtherArrayType>
  3093. void addArray (const OtherArrayType& arrayToAddFrom,
  3094. int startIndex = 0,
  3095. int numElementsToAdd = -1)
  3096. {
  3097. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  3098. const ScopedLockType lock2 (getLock());
  3099. if (startIndex < 0)
  3100. {
  3101. jassertfalse;
  3102. startIndex = 0;
  3103. }
  3104. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  3105. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  3106. while (--numElementsToAdd >= 0)
  3107. add (arrayToAddFrom.getUnchecked (startIndex++));
  3108. }
  3109. /** Inserts a new element into the array, assuming that the array is sorted.
  3110. This will use a comparator to find the position at which the new element
  3111. should go. If the array isn't sorted, the behaviour of this
  3112. method will be unpredictable.
  3113. @param comparator the comparator to use to compare the elements - see the sort()
  3114. method for details about the form this object should take
  3115. @param newElement the new element to insert to the array
  3116. @see addUsingDefaultSort, add, sort
  3117. */
  3118. template <class ElementComparator>
  3119. void addSorted (ElementComparator& comparator, ParameterType newElement)
  3120. {
  3121. const ScopedLockType lock (getLock());
  3122. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newElement, 0, numUsed), newElement);
  3123. }
  3124. /** Inserts a new element into the array, assuming that the array is sorted.
  3125. This will use the DefaultElementComparator class for sorting, so your ElementType
  3126. must be suitable for use with that class. If the array isn't sorted, the behaviour of this
  3127. method will be unpredictable.
  3128. @param newElement the new element to insert to the array
  3129. @see addSorted, sort
  3130. */
  3131. void addUsingDefaultSort (ParameterType newElement)
  3132. {
  3133. DefaultElementComparator <ElementType> comparator;
  3134. addSorted (comparator, newElement);
  3135. }
  3136. /** Finds the index of an element in the array, assuming that the array is sorted.
  3137. This will use a comparator to do a binary-chop to find the index of the given
  3138. element, if it exists. If the array isn't sorted, the behaviour of this
  3139. method will be unpredictable.
  3140. @param comparator the comparator to use to compare the elements - see the sort()
  3141. method for details about the form this object should take
  3142. @param elementToLookFor the element to search for
  3143. @returns the index of the element, or -1 if it's not found
  3144. @see addSorted, sort
  3145. */
  3146. template <class ElementComparator>
  3147. int indexOfSorted (ElementComparator& comparator, ParameterType elementToLookFor) const
  3148. {
  3149. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3150. // avoids getting warning messages about the parameter being unused
  3151. const ScopedLockType lock (getLock());
  3152. int start = 0;
  3153. int end = numUsed;
  3154. for (;;)
  3155. {
  3156. if (start >= end)
  3157. {
  3158. return -1;
  3159. }
  3160. else if (comparator.compareElements (elementToLookFor, data.elements [start]) == 0)
  3161. {
  3162. return start;
  3163. }
  3164. else
  3165. {
  3166. const int halfway = (start + end) >> 1;
  3167. if (halfway == start)
  3168. return -1;
  3169. else if (comparator.compareElements (elementToLookFor, data.elements [halfway]) >= 0)
  3170. start = halfway;
  3171. else
  3172. end = halfway;
  3173. }
  3174. }
  3175. }
  3176. /** Removes an element from the array.
  3177. This will remove the element at a given index, and move back
  3178. all the subsequent elements to close the gap.
  3179. If the index passed in is out-of-range, nothing will happen.
  3180. @param indexToRemove the index of the element to remove
  3181. @returns the element that has been removed
  3182. @see removeValue, removeRange
  3183. */
  3184. ElementType remove (const int indexToRemove)
  3185. {
  3186. const ScopedLockType lock (getLock());
  3187. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  3188. {
  3189. --numUsed;
  3190. ElementType* const e = data.elements + indexToRemove;
  3191. ElementType removed (*e);
  3192. e->~ElementType();
  3193. const int numberToShift = numUsed - indexToRemove;
  3194. if (numberToShift > 0)
  3195. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  3196. if ((numUsed << 1) < data.numAllocated)
  3197. minimiseStorageOverheads();
  3198. return removed;
  3199. }
  3200. else
  3201. {
  3202. return ElementType();
  3203. }
  3204. }
  3205. /** Removes an item from the array.
  3206. This will remove the first occurrence of the given element from the array.
  3207. If the item isn't found, no action is taken.
  3208. @param valueToRemove the object to try to remove
  3209. @see remove, removeRange
  3210. */
  3211. void removeValue (ParameterType valueToRemove)
  3212. {
  3213. const ScopedLockType lock (getLock());
  3214. ElementType* e = data.elements;
  3215. for (int i = numUsed; --i >= 0;)
  3216. {
  3217. if (valueToRemove == *e)
  3218. {
  3219. remove (static_cast <int> (e - data.elements.getData()));
  3220. break;
  3221. }
  3222. ++e;
  3223. }
  3224. }
  3225. /** Removes a range of elements from the array.
  3226. This will remove a set of elements, starting from the given index,
  3227. and move subsequent elements down to close the gap.
  3228. If the range extends beyond the bounds of the array, it will
  3229. be safely clipped to the size of the array.
  3230. @param startIndex the index of the first element to remove
  3231. @param numberToRemove how many elements should be removed
  3232. @see remove, removeValue
  3233. */
  3234. void removeRange (int startIndex, int numberToRemove)
  3235. {
  3236. const ScopedLockType lock (getLock());
  3237. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  3238. startIndex = jlimit (0, numUsed, startIndex);
  3239. if (endIndex > startIndex)
  3240. {
  3241. ElementType* const e = data.elements + startIndex;
  3242. numberToRemove = endIndex - startIndex;
  3243. for (int i = 0; i < numberToRemove; ++i)
  3244. e[i].~ElementType();
  3245. const int numToShift = numUsed - endIndex;
  3246. if (numToShift > 0)
  3247. memmove (e, e + numberToRemove, numToShift * sizeof (ElementType));
  3248. numUsed -= numberToRemove;
  3249. if ((numUsed << 1) < data.numAllocated)
  3250. minimiseStorageOverheads();
  3251. }
  3252. }
  3253. /** Removes the last n elements from the array.
  3254. @param howManyToRemove how many elements to remove from the end of the array
  3255. @see remove, removeValue, removeRange
  3256. */
  3257. void removeLast (int howManyToRemove = 1)
  3258. {
  3259. const ScopedLockType lock (getLock());
  3260. if (howManyToRemove > numUsed)
  3261. howManyToRemove = numUsed;
  3262. for (int i = 0; i < howManyToRemove; ++i)
  3263. data.elements [numUsed - i].~ElementType();
  3264. numUsed -= howManyToRemove;
  3265. if ((numUsed << 1) < data.numAllocated)
  3266. minimiseStorageOverheads();
  3267. }
  3268. /** Removes any elements which are also in another array.
  3269. @param otherArray the other array in which to look for elements to remove
  3270. @see removeValuesNotIn, remove, removeValue, removeRange
  3271. */
  3272. template <class OtherArrayType>
  3273. void removeValuesIn (const OtherArrayType& otherArray)
  3274. {
  3275. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3276. const ScopedLockType lock2 (getLock());
  3277. if (this == &otherArray)
  3278. {
  3279. clear();
  3280. }
  3281. else
  3282. {
  3283. if (otherArray.size() > 0)
  3284. {
  3285. for (int i = numUsed; --i >= 0;)
  3286. if (otherArray.contains (data.elements [i]))
  3287. remove (i);
  3288. }
  3289. }
  3290. }
  3291. /** Removes any elements which are not found in another array.
  3292. Only elements which occur in this other array will be retained.
  3293. @param otherArray the array in which to look for elements NOT to remove
  3294. @see removeValuesIn, remove, removeValue, removeRange
  3295. */
  3296. template <class OtherArrayType>
  3297. void removeValuesNotIn (const OtherArrayType& otherArray)
  3298. {
  3299. const typename OtherArrayType::ScopedLockType lock1 (otherArray.getLock());
  3300. const ScopedLockType lock2 (getLock());
  3301. if (this != &otherArray)
  3302. {
  3303. if (otherArray.size() <= 0)
  3304. {
  3305. clear();
  3306. }
  3307. else
  3308. {
  3309. for (int i = numUsed; --i >= 0;)
  3310. if (! otherArray.contains (data.elements [i]))
  3311. remove (i);
  3312. }
  3313. }
  3314. }
  3315. /** Swaps over two elements in the array.
  3316. This swaps over the elements found at the two indexes passed in.
  3317. If either index is out-of-range, this method will do nothing.
  3318. @param index1 index of one of the elements to swap
  3319. @param index2 index of the other element to swap
  3320. */
  3321. void swap (const int index1,
  3322. const int index2)
  3323. {
  3324. const ScopedLockType lock (getLock());
  3325. if (((unsigned int) index1) < (unsigned int) numUsed
  3326. && ((unsigned int) index2) < (unsigned int) numUsed)
  3327. {
  3328. swapVariables (data.elements [index1],
  3329. data.elements [index2]);
  3330. }
  3331. }
  3332. /** Moves one of the values to a different position.
  3333. This will move the value to a specified index, shuffling along
  3334. any intervening elements as required.
  3335. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  3336. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  3337. @param currentIndex the index of the value to be moved. If this isn't a
  3338. valid index, then nothing will be done
  3339. @param newIndex the index at which you'd like this value to end up. If this
  3340. is less than zero, the value will be moved to the end
  3341. of the array
  3342. */
  3343. void move (const int currentIndex, int newIndex) throw()
  3344. {
  3345. if (currentIndex != newIndex)
  3346. {
  3347. const ScopedLockType lock (getLock());
  3348. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  3349. {
  3350. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  3351. newIndex = numUsed - 1;
  3352. char tempCopy [sizeof (ElementType)];
  3353. memcpy (tempCopy, data.elements + currentIndex, sizeof (ElementType));
  3354. if (newIndex > currentIndex)
  3355. {
  3356. memmove (data.elements + currentIndex,
  3357. data.elements + currentIndex + 1,
  3358. (newIndex - currentIndex) * sizeof (ElementType));
  3359. }
  3360. else
  3361. {
  3362. memmove (data.elements + newIndex + 1,
  3363. data.elements + newIndex,
  3364. (currentIndex - newIndex) * sizeof (ElementType));
  3365. }
  3366. memcpy (data.elements + newIndex, tempCopy, sizeof (ElementType));
  3367. }
  3368. }
  3369. }
  3370. /** Reduces the amount of storage being used by the array.
  3371. Arrays typically allocate slightly more storage than they need, and after
  3372. removing elements, they may have quite a lot of unused space allocated.
  3373. This method will reduce the amount of allocated storage to a minimum.
  3374. */
  3375. void minimiseStorageOverheads()
  3376. {
  3377. const ScopedLockType lock (getLock());
  3378. data.shrinkToNoMoreThan (numUsed);
  3379. }
  3380. /** Increases the array's internal storage to hold a minimum number of elements.
  3381. Calling this before adding a large known number of elements means that
  3382. the array won't have to keep dynamically resizing itself as the elements
  3383. are added, and it'll therefore be more efficient.
  3384. */
  3385. void ensureStorageAllocated (const int minNumElements)
  3386. {
  3387. const ScopedLockType lock (getLock());
  3388. data.ensureAllocatedSize (minNumElements);
  3389. }
  3390. /** Sorts the elements in the array.
  3391. This will use a comparator object to sort the elements into order. The object
  3392. passed must have a method of the form:
  3393. @code
  3394. int compareElements (ElementType first, ElementType second);
  3395. @endcode
  3396. ..and this method must return:
  3397. - a value of < 0 if the first comes before the second
  3398. - a value of 0 if the two objects are equivalent
  3399. - a value of > 0 if the second comes before the first
  3400. To improve performance, the compareElements() method can be declared as static or const.
  3401. @param comparator the comparator to use for comparing elements.
  3402. @param retainOrderOfEquivalentItems if this is true, then items
  3403. which the comparator says are equivalent will be
  3404. kept in the order in which they currently appear
  3405. in the array. This is slower to perform, but may
  3406. be important in some cases. If it's false, a faster
  3407. algorithm is used, but equivalent elements may be
  3408. rearranged.
  3409. @see addSorted, indexOfSorted, sortArray
  3410. */
  3411. template <class ElementComparator>
  3412. void sort (ElementComparator& comparator,
  3413. const bool retainOrderOfEquivalentItems = false) const
  3414. {
  3415. const ScopedLockType lock (getLock());
  3416. (void) comparator; // if you pass in an object with a static compareElements() method, this
  3417. // avoids getting warning messages about the parameter being unused
  3418. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  3419. }
  3420. /** Returns the CriticalSection that locks this array.
  3421. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  3422. an object of ScopedLockType as an RAII lock for it.
  3423. */
  3424. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  3425. /** Returns the type of scoped lock to use for locking this array */
  3426. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  3427. juce_UseDebuggingNewOperator
  3428. private:
  3429. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  3430. int numUsed;
  3431. };
  3432. #endif // __JUCE_ARRAY_JUCEHEADER__
  3433. /*** End of inlined file: juce_Array.h ***/
  3434. #endif
  3435. #ifndef __JUCE_ARRAYALLOCATIONBASE_JUCEHEADER__
  3436. #endif
  3437. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3438. /*** Start of inlined file: juce_BigInteger.h ***/
  3439. #ifndef __JUCE_BIGINTEGER_JUCEHEADER__
  3440. #define __JUCE_BIGINTEGER_JUCEHEADER__
  3441. class MemoryBlock;
  3442. /**
  3443. An arbitrarily large integer class.
  3444. A BigInteger can be used in a similar way to a normal integer, but has no size
  3445. limit (except for memory and performance constraints).
  3446. Negative values are possible, but the value isn't stored as 2s-complement, so
  3447. be careful if you use negative values and look at the values of individual bits.
  3448. */
  3449. class JUCE_API BigInteger
  3450. {
  3451. public:
  3452. /** Creates an empty BigInteger */
  3453. BigInteger();
  3454. /** Creates a BigInteger containing an integer value in its low bits.
  3455. The low 32 bits of the number are initialised with this value.
  3456. */
  3457. BigInteger (unsigned int value);
  3458. /** Creates a BigInteger containing an integer value in its low bits.
  3459. The low 32 bits of the number are initialised with the absolute value
  3460. passed in, and its sign is set to reflect the sign of the number.
  3461. */
  3462. BigInteger (int value);
  3463. /** Creates a BigInteger containing an integer value in its low bits.
  3464. The low 64 bits of the number are initialised with the absolute value
  3465. passed in, and its sign is set to reflect the sign of the number.
  3466. */
  3467. BigInteger (int64 value);
  3468. /** Creates a copy of another BigInteger. */
  3469. BigInteger (const BigInteger& other);
  3470. /** Destructor. */
  3471. ~BigInteger();
  3472. /** Copies another BigInteger onto this one. */
  3473. BigInteger& operator= (const BigInteger& other);
  3474. /** Swaps the internal contents of this with another object. */
  3475. void swapWith (BigInteger& other) throw();
  3476. /** Returns the value of a specified bit in the number.
  3477. If the index is out-of-range, the result will be false.
  3478. */
  3479. bool operator[] (int bit) const throw();
  3480. /** Returns true if no bits are set. */
  3481. bool isZero() const throw();
  3482. /** Returns true if the value is 1. */
  3483. bool isOne() const throw();
  3484. /** Attempts to get the lowest bits of the value as an integer.
  3485. If the value is bigger than the integer limits, this will return only the lower bits.
  3486. */
  3487. int toInteger() const throw();
  3488. /** Resets the value to 0. */
  3489. void clear();
  3490. /** Clears a particular bit in the number. */
  3491. void clearBit (int bitNumber) throw();
  3492. /** Sets a specified bit to 1. */
  3493. void setBit (int bitNumber);
  3494. /** Sets or clears a specified bit. */
  3495. void setBit (int bitNumber, bool shouldBeSet);
  3496. /** Sets a range of bits to be either on or off.
  3497. @param startBit the first bit to change
  3498. @param numBits the number of bits to change
  3499. @param shouldBeSet whether to turn these bits on or off
  3500. */
  3501. void setRange (int startBit, int numBits, bool shouldBeSet);
  3502. /** Inserts a bit an a given position, shifting up any bits above it. */
  3503. void insertBit (int bitNumber, bool shouldBeSet);
  3504. /** Returns a range of bits as a new BigInteger.
  3505. e.g. getBitRangeAsInt (0, 64) would return the lowest 64 bits.
  3506. @see getBitRangeAsInt
  3507. */
  3508. const BigInteger getBitRange (int startBit, int numBits) const;
  3509. /** Returns a range of bits as an integer value.
  3510. e.g. getBitRangeAsInt (0, 32) would return the lowest 32 bits.
  3511. Asking for more than 32 bits isn't allowed (obviously) - for that, use
  3512. getBitRange().
  3513. */
  3514. int getBitRangeAsInt (int startBit, int numBits) const throw();
  3515. /** Sets a range of bits to an integer value.
  3516. Copies the given integer onto a range of bits, starting at startBit,
  3517. and using up to numBits of the available bits.
  3518. */
  3519. void setBitRangeAsInt (int startBit, int numBits, unsigned int valueToSet);
  3520. /** Shifts a section of bits left or right.
  3521. @param howManyBitsLeft how far to move the bits (+ve numbers shift it left, -ve numbers shift it right).
  3522. @param startBit the first bit to affect - if this is > 0, only bits above that index will be affected.
  3523. */
  3524. void shiftBits (int howManyBitsLeft, int startBit);
  3525. /** Returns the total number of set bits in the value. */
  3526. int countNumberOfSetBits() const throw();
  3527. /** Looks for the index of the next set bit after a given starting point.
  3528. This searches from startIndex (inclusive) upwards for the first set bit,
  3529. and returns its index. If no set bits are found, it returns -1.
  3530. */
  3531. int findNextSetBit (int startIndex = 0) const throw();
  3532. /** Looks for the index of the next clear bit after a given starting point.
  3533. This searches from startIndex (inclusive) upwards for the first clear bit,
  3534. and returns its index.
  3535. */
  3536. int findNextClearBit (int startIndex = 0) const throw();
  3537. /** Returns the index of the highest set bit in the number.
  3538. If the value is zero, this will return -1.
  3539. */
  3540. int getHighestBit() const throw();
  3541. // All the standard arithmetic ops...
  3542. BigInteger& operator+= (const BigInteger& other);
  3543. BigInteger& operator-= (const BigInteger& other);
  3544. BigInteger& operator*= (const BigInteger& other);
  3545. BigInteger& operator/= (const BigInteger& other);
  3546. BigInteger& operator|= (const BigInteger& other);
  3547. BigInteger& operator&= (const BigInteger& other);
  3548. BigInteger& operator^= (const BigInteger& other);
  3549. BigInteger& operator%= (const BigInteger& other);
  3550. BigInteger& operator<<= (int numBitsToShift);
  3551. BigInteger& operator>>= (int numBitsToShift);
  3552. BigInteger& operator++();
  3553. BigInteger& operator--();
  3554. const BigInteger operator++ (int);
  3555. const BigInteger operator-- (int);
  3556. const BigInteger operator-() const;
  3557. const BigInteger operator+ (const BigInteger& other) const;
  3558. const BigInteger operator- (const BigInteger& other) const;
  3559. const BigInteger operator* (const BigInteger& other) const;
  3560. const BigInteger operator/ (const BigInteger& other) const;
  3561. const BigInteger operator| (const BigInteger& other) const;
  3562. const BigInteger operator& (const BigInteger& other) const;
  3563. const BigInteger operator^ (const BigInteger& other) const;
  3564. const BigInteger operator% (const BigInteger& other) const;
  3565. const BigInteger operator<< (int numBitsToShift) const;
  3566. const BigInteger operator>> (int numBitsToShift) const;
  3567. bool operator== (const BigInteger& other) const throw();
  3568. bool operator!= (const BigInteger& other) const throw();
  3569. bool operator< (const BigInteger& other) const throw();
  3570. bool operator<= (const BigInteger& other) const throw();
  3571. bool operator> (const BigInteger& other) const throw();
  3572. bool operator>= (const BigInteger& other) const throw();
  3573. /** Does a signed comparison of two BigIntegers.
  3574. Return values are:
  3575. - 0 if the numbers are the same
  3576. - < 0 if this number is smaller than the other
  3577. - > 0 if this number is bigger than the other
  3578. */
  3579. int compare (const BigInteger& other) const throw();
  3580. /** Compares the magnitudes of two BigIntegers, ignoring their signs.
  3581. Return values are:
  3582. - 0 if the numbers are the same
  3583. - < 0 if this number is smaller than the other
  3584. - > 0 if this number is bigger than the other
  3585. */
  3586. int compareAbsolute (const BigInteger& other) const throw();
  3587. /** Divides this value by another one and returns the remainder.
  3588. This number is divided by other, leaving the quotient in this number,
  3589. with the remainder being copied to the other BigInteger passed in.
  3590. */
  3591. void divideBy (const BigInteger& divisor, BigInteger& remainder);
  3592. /** Returns the largest value that will divide both this value and the one passed-in.
  3593. */
  3594. const BigInteger findGreatestCommonDivisor (BigInteger other) const;
  3595. /** Performs a combined exponent and modulo operation.
  3596. This BigInteger's value becomes (this ^ exponent) % modulus.
  3597. */
  3598. void exponentModulo (const BigInteger& exponent, const BigInteger& modulus);
  3599. /** Performs an inverse modulo on the value.
  3600. i.e. the result is (this ^ -1) mod (modulus).
  3601. */
  3602. void inverseModulo (const BigInteger& modulus);
  3603. /** Returns true if the value is less than zero.
  3604. @see setNegative, negate
  3605. */
  3606. bool isNegative() const throw();
  3607. /** Changes the sign of the number to be positive or negative.
  3608. @see isNegative, negate
  3609. */
  3610. void setNegative (const bool shouldBeNegative) throw();
  3611. /** Inverts the sign of the number.
  3612. @see isNegative, setNegative
  3613. */
  3614. void negate() throw();
  3615. /** Converts the number to a string.
  3616. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3617. If minimumNumCharacters is greater than 0, the returned string will be
  3618. padded with leading zeros to reach at least that length.
  3619. */
  3620. const String toString (int base, int minimumNumCharacters = 1) const;
  3621. /** Reads the numeric value from a string.
  3622. Specify a base such as 2 (binary), 8 (octal), 10 (decimal), 16 (hex).
  3623. Any invalid characters will be ignored.
  3624. */
  3625. void parseString (const String& text, int base);
  3626. /** Turns the number into a block of binary data.
  3627. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3628. of the number, and so on.
  3629. @see loadFromMemoryBlock
  3630. */
  3631. const MemoryBlock toMemoryBlock() const;
  3632. /** Converts a block of raw data into a number.
  3633. The data is arranged as little-endian, so the first byte of data is the low 8 bits
  3634. of the number, and so on.
  3635. @see toMemoryBlock
  3636. */
  3637. void loadFromMemoryBlock (const MemoryBlock& data);
  3638. juce_UseDebuggingNewOperator
  3639. private:
  3640. HeapBlock <unsigned int> values;
  3641. int numValues, highestBit;
  3642. bool negative;
  3643. void ensureSize (int numVals);
  3644. static const BigInteger simpleGCD (BigInteger* m, BigInteger* n);
  3645. };
  3646. /** Writes a BigInteger to an OutputStream as a UTF8 decimal string. */
  3647. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value);
  3648. /** For backwards compatibility, BitArray is defined to be an alias for BigInteger.
  3649. */
  3650. typedef BigInteger BitArray;
  3651. #endif // __JUCE_BIGINTEGER_JUCEHEADER__
  3652. /*** End of inlined file: juce_BigInteger.h ***/
  3653. #endif
  3654. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3655. /*** Start of inlined file: juce_DynamicObject.h ***/
  3656. #ifndef __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3657. #define __JUCE_DYNAMICOBJECT_JUCEHEADER__
  3658. /*** Start of inlined file: juce_NamedValueSet.h ***/
  3659. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  3660. #define __JUCE_NAMEDVALUESET_JUCEHEADER__
  3661. /*** Start of inlined file: juce_Variant.h ***/
  3662. #ifndef __JUCE_VARIANT_JUCEHEADER__
  3663. #define __JUCE_VARIANT_JUCEHEADER__
  3664. /*** Start of inlined file: juce_Identifier.h ***/
  3665. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  3666. #define __JUCE_IDENTIFIER_JUCEHEADER__
  3667. /*** Start of inlined file: juce_StringPool.h ***/
  3668. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  3669. #define __JUCE_STRINGPOOL_JUCEHEADER__
  3670. /**
  3671. A StringPool holds a set of shared strings, which reduces storage overheads and improves
  3672. comparison speed when dealing with many duplicate strings.
  3673. When you add a string to a pool using getPooledString, it'll return a character
  3674. array containing the same string. This array is owned by the pool, and the same array
  3675. is returned every time a matching string is asked for. This means that it's trivial to
  3676. compare two pooled strings for equality, as you can simply compare their pointers. It
  3677. also cuts down on storage if you're using many copies of the same string.
  3678. */
  3679. class JUCE_API StringPool
  3680. {
  3681. public:
  3682. /** Creates an empty pool. */
  3683. StringPool() throw();
  3684. /** Destructor */
  3685. ~StringPool();
  3686. /** Returns a pointer to a copy of the string that is passed in.
  3687. The pool will always return the same pointer when asked for a string that matches it.
  3688. The pool will own all the pointers that it returns, deleting them when the pool itself
  3689. is deleted.
  3690. */
  3691. const juce_wchar* getPooledString (const String& original);
  3692. /** Returns a pointer to a copy of the string that is passed in.
  3693. The pool will always return the same pointer when asked for a string that matches it.
  3694. The pool will own all the pointers that it returns, deleting them when the pool itself
  3695. is deleted.
  3696. */
  3697. const juce_wchar* getPooledString (const char* original);
  3698. /** Returns a pointer to a copy of the string that is passed in.
  3699. The pool will always return the same pointer when asked for a string that matches it.
  3700. The pool will own all the pointers that it returns, deleting them when the pool itself
  3701. is deleted.
  3702. */
  3703. const juce_wchar* getPooledString (const juce_wchar* original);
  3704. /** Returns the number of strings in the pool. */
  3705. int size() const throw();
  3706. /** Returns one of the strings in the pool, by index. */
  3707. const juce_wchar* operator[] (int index) const throw();
  3708. private:
  3709. Array <String> strings;
  3710. };
  3711. #endif // __JUCE_STRINGPOOL_JUCEHEADER__
  3712. /*** End of inlined file: juce_StringPool.h ***/
  3713. /**
  3714. Represents a string identifier, designed for accessing properties by name.
  3715. Identifier objects are very light and fast to copy, but slower to initialise
  3716. from a string, so it's much faster to keep a static identifier object to refer
  3717. to frequently-used names, rather than constructing them each time you need it.
  3718. @see NamedPropertySet, ValueTree
  3719. */
  3720. class JUCE_API Identifier
  3721. {
  3722. public:
  3723. /** Creates a null identifier. */
  3724. Identifier() throw();
  3725. /** Creates an identifier with a specified name.
  3726. Because this name may need to be used in contexts such as script variables or XML
  3727. tags, it must only contain ascii letters and digits, or the underscore character.
  3728. */
  3729. Identifier (const char* name);
  3730. /** Creates an identifier with a specified name.
  3731. Because this name may need to be used in contexts such as script variables or XML
  3732. tags, it must only contain ascii letters and digits, or the underscore character.
  3733. */
  3734. Identifier (const String& name);
  3735. /** Creates a copy of another identifier. */
  3736. Identifier (const Identifier& other) throw();
  3737. /** Creates a copy of another identifier. */
  3738. Identifier& operator= (const Identifier& other) throw();
  3739. /** Destructor */
  3740. ~Identifier();
  3741. /** Compares two identifiers. This is a very fast operation. */
  3742. inline bool operator== (const Identifier& other) const throw() { return name == other.name; }
  3743. /** Compares two identifiers. This is a very fast operation. */
  3744. inline bool operator!= (const Identifier& other) const throw() { return name != other.name; }
  3745. /** Returns this identifier as a string. */
  3746. const String toString() const { return name; }
  3747. /** Returns this identifier's raw string pointer. */
  3748. operator const juce_wchar*() const throw() { return name; }
  3749. private:
  3750. const juce_wchar* name;
  3751. static StringPool& getPool();
  3752. };
  3753. #endif // __JUCE_IDENTIFIER_JUCEHEADER__
  3754. /*** End of inlined file: juce_Identifier.h ***/
  3755. /*** Start of inlined file: juce_OutputStream.h ***/
  3756. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3757. #define __JUCE_OUTPUTSTREAM_JUCEHEADER__
  3758. /*** Start of inlined file: juce_InputStream.h ***/
  3759. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  3760. #define __JUCE_INPUTSTREAM_JUCEHEADER__
  3761. /*** Start of inlined file: juce_MemoryBlock.h ***/
  3762. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  3763. #define __JUCE_MEMORYBLOCK_JUCEHEADER__
  3764. /**
  3765. A class to hold a resizable block of raw data.
  3766. */
  3767. class JUCE_API MemoryBlock
  3768. {
  3769. public:
  3770. /** Create an uninitialised block with 0 size. */
  3771. MemoryBlock() throw();
  3772. /** Creates a memory block with a given initial size.
  3773. @param initialSize the size of block to create
  3774. @param initialiseToZero whether to clear the memory or just leave it uninitialised
  3775. */
  3776. MemoryBlock (const size_t initialSize,
  3777. const bool initialiseToZero = false) throw();
  3778. /** Creates a copy of another memory block. */
  3779. MemoryBlock (const MemoryBlock& other) throw();
  3780. /** Creates a memory block using a copy of a block of data.
  3781. @param dataToInitialiseFrom some data to copy into this block
  3782. @param sizeInBytes how much space to use
  3783. */
  3784. MemoryBlock (const void* const dataToInitialiseFrom,
  3785. const size_t sizeInBytes) throw();
  3786. /** Destructor. */
  3787. ~MemoryBlock() throw();
  3788. /** Copies another memory block onto this one.
  3789. This block will be resized and copied to exactly match the other one.
  3790. */
  3791. MemoryBlock& operator= (const MemoryBlock& other) throw();
  3792. /** Compares two memory blocks.
  3793. @returns true only if the two blocks are the same size and have identical contents.
  3794. */
  3795. bool operator== (const MemoryBlock& other) const throw();
  3796. /** Compares two memory blocks.
  3797. @returns true if the two blocks are different sizes or have different contents.
  3798. */
  3799. bool operator!= (const MemoryBlock& other) const throw();
  3800. /** Returns true if the data in this MemoryBlock matches the raw bytes passed-in.
  3801. */
  3802. bool matches (const void* data, size_t dataSize) const throw();
  3803. /** Returns a void pointer to the data.
  3804. Note that the pointer returned will probably become invalid when the
  3805. block is resized.
  3806. */
  3807. void* getData() const throw() { return data; }
  3808. /** Returns a byte from the memory block.
  3809. This returns a reference, so you can also use it to set a byte.
  3810. */
  3811. template <typename Type>
  3812. char& operator[] (const Type offset) const throw() { return data [offset]; }
  3813. /** Returns the block's current allocated size, in bytes. */
  3814. size_t getSize() const throw() { return size; }
  3815. /** Resizes the memory block.
  3816. This will try to keep as much of the block's current content as it can,
  3817. and can optionally be made to clear any new space that gets allocated at
  3818. the end of the block.
  3819. @param newSize the new desired size for the block
  3820. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3821. whether to clear the new section or just leave it
  3822. uninitialised
  3823. @see ensureSize
  3824. */
  3825. void setSize (const size_t newSize,
  3826. const bool initialiseNewSpaceToZero = false) throw();
  3827. /** Increases the block's size only if it's smaller than a given size.
  3828. @param minimumSize if the block is already bigger than this size, no action
  3829. will be taken; otherwise it will be increased to this size
  3830. @param initialiseNewSpaceToZero if the block gets enlarged, this determines
  3831. whether to clear the new section or just leave it
  3832. uninitialised
  3833. @see setSize
  3834. */
  3835. void ensureSize (const size_t minimumSize,
  3836. const bool initialiseNewSpaceToZero = false) throw();
  3837. /** Fills the entire memory block with a repeated byte value.
  3838. This is handy for clearing a block of memory to zero.
  3839. */
  3840. void fillWith (const uint8 valueToUse) throw();
  3841. /** Adds another block of data to the end of this one.
  3842. This block's size will be increased accordingly.
  3843. */
  3844. void append (const void* const data,
  3845. const size_t numBytes) throw();
  3846. /** Exchanges the contents of this and another memory block.
  3847. No actual copying is required for this, so it's very fast.
  3848. */
  3849. void swapWith (MemoryBlock& other) throw();
  3850. /** Copies data into this MemoryBlock from a memory address.
  3851. @param srcData the memory location of the data to copy into this block
  3852. @param destinationOffset the offset in this block at which the data being copied should begin
  3853. @param numBytes how much to copy in (if this goes beyond the size of the memory block,
  3854. it will be clipped so not to do anything nasty)
  3855. */
  3856. void copyFrom (const void* srcData,
  3857. int destinationOffset,
  3858. size_t numBytes) throw();
  3859. /** Copies data from this MemoryBlock to a memory address.
  3860. @param destData the memory location to write to
  3861. @param sourceOffset the offset within this block from which the copied data will be read
  3862. @param numBytes how much to copy (if this extends beyond the limits of the memory block,
  3863. zeros will be used for that portion of the data)
  3864. */
  3865. void copyTo (void* destData,
  3866. int sourceOffset,
  3867. size_t numBytes) const throw();
  3868. /** Chops out a section of the block.
  3869. This will remove a section of the memory block and close the gap around it,
  3870. shifting any subsequent data downwards and reducing the size of the block.
  3871. If the range specified goes beyond the size of the block, it will be clipped.
  3872. */
  3873. void removeSection (size_t startByte, size_t numBytesToRemove) throw();
  3874. /** Attempts to parse the contents of the block as a zero-terminated string of 8-bit
  3875. characters in the system's default encoding. */
  3876. const String toString() const throw();
  3877. /** Parses a string of hexadecimal numbers and writes this data into the memory block.
  3878. The block will be resized to the number of valid bytes read from the string.
  3879. Non-hex characters in the string will be ignored.
  3880. @see String::toHexString()
  3881. */
  3882. void loadFromHexString (const String& sourceHexString) throw();
  3883. /** Sets a number of bits in the memory block, treating it as a long binary sequence. */
  3884. void setBitRange (size_t bitRangeStart,
  3885. size_t numBits,
  3886. int binaryNumberToApply) throw();
  3887. /** Reads a number of bits from the memory block, treating it as one long binary sequence */
  3888. int getBitRange (size_t bitRangeStart,
  3889. size_t numBitsToRead) const throw();
  3890. /** Returns a string of characters that represent the binary contents of this block.
  3891. Uses a 64-bit encoding system to allow binary data to be turned into a string
  3892. of simple non-extended characters, e.g. for storage in XML.
  3893. @see fromBase64Encoding
  3894. */
  3895. const String toBase64Encoding() const throw();
  3896. /** Takes a string of encoded characters and turns it into binary data.
  3897. The string passed in must have been created by to64BitEncoding(), and this
  3898. block will be resized to recreate the original data block.
  3899. @see toBase64Encoding
  3900. */
  3901. bool fromBase64Encoding (const String& encodedString) throw();
  3902. juce_UseDebuggingNewOperator
  3903. private:
  3904. HeapBlock <char> data;
  3905. size_t size;
  3906. static const char* const encodingTable;
  3907. };
  3908. #endif // __JUCE_MEMORYBLOCK_JUCEHEADER__
  3909. /*** End of inlined file: juce_MemoryBlock.h ***/
  3910. /** The base class for streams that read data.
  3911. Input and output streams are used throughout the library - subclasses can override
  3912. some or all of the virtual functions to implement their behaviour.
  3913. @see OutputStream, MemoryInputStream, BufferedInputStream, FileInputStream
  3914. */
  3915. class JUCE_API InputStream
  3916. {
  3917. public:
  3918. /** Destructor. */
  3919. virtual ~InputStream() {}
  3920. /** Returns the total number of bytes available for reading in this stream.
  3921. Note that this is the number of bytes available from the start of the
  3922. stream, not from the current position.
  3923. If the size of the stream isn't actually known, this may return -1.
  3924. */
  3925. virtual int64 getTotalLength() = 0;
  3926. /** Returns true if the stream has no more data to read. */
  3927. virtual bool isExhausted() = 0;
  3928. /** Reads a set of bytes from the stream into a memory buffer.
  3929. This is the only read method that subclasses actually need to implement, as the
  3930. InputStream base class implements the other read methods in terms of this one (although
  3931. it's often more efficient for subclasses to implement them directly).
  3932. @param destBuffer the destination buffer for the data
  3933. @param maxBytesToRead the maximum number of bytes to read - make sure the
  3934. memory block passed in is big enough to contain this
  3935. many bytes.
  3936. @returns the actual number of bytes that were read, which may be less than
  3937. maxBytesToRead if the stream is exhausted before it gets that far
  3938. */
  3939. virtual int read (void* destBuffer, int maxBytesToRead) = 0;
  3940. /** Reads a byte from the stream.
  3941. If the stream is exhausted, this will return zero.
  3942. @see OutputStream::writeByte
  3943. */
  3944. virtual char readByte();
  3945. /** Reads a boolean from the stream.
  3946. The bool is encoded as a single byte - 1 for true, 0 for false.
  3947. If the stream is exhausted, this will return false.
  3948. @see OutputStream::writeBool
  3949. */
  3950. virtual bool readBool();
  3951. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3952. If the next two bytes read are byte1 and byte2, this returns
  3953. (byte1 | (byte2 << 8)).
  3954. If the stream is exhausted partway through reading the bytes, this will return zero.
  3955. @see OutputStream::writeShort, readShortBigEndian
  3956. */
  3957. virtual short readShort();
  3958. /** Reads two bytes from the stream as a little-endian 16-bit value.
  3959. If the next two bytes read are byte1 and byte2, this returns
  3960. (byte2 | (byte1 << 8)).
  3961. If the stream is exhausted partway through reading the bytes, this will return zero.
  3962. @see OutputStream::writeShortBigEndian, readShort
  3963. */
  3964. virtual short readShortBigEndian();
  3965. /** Reads four bytes from the stream as a little-endian 32-bit value.
  3966. If the next four bytes are byte1 to byte4, this returns
  3967. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24)).
  3968. If the stream is exhausted partway through reading the bytes, this will return zero.
  3969. @see OutputStream::writeInt, readIntBigEndian
  3970. */
  3971. virtual int readInt();
  3972. /** Reads four bytes from the stream as a big-endian 32-bit value.
  3973. If the next four bytes are byte1 to byte4, this returns
  3974. (byte4 | (byte3 << 8) | (byte2 << 16) | (byte1 << 24)).
  3975. If the stream is exhausted partway through reading the bytes, this will return zero.
  3976. @see OutputStream::writeIntBigEndian, readInt
  3977. */
  3978. virtual int readIntBigEndian();
  3979. /** Reads eight bytes from the stream as a little-endian 64-bit value.
  3980. If the next eight bytes are byte1 to byte8, this returns
  3981. (byte1 | (byte2 << 8) | (byte3 << 16) | (byte4 << 24) | (byte5 << 32) | (byte6 << 40) | (byte7 << 48) | (byte8 << 56)).
  3982. If the stream is exhausted partway through reading the bytes, this will return zero.
  3983. @see OutputStream::writeInt64, readInt64BigEndian
  3984. */
  3985. virtual int64 readInt64();
  3986. /** Reads eight bytes from the stream as a big-endian 64-bit value.
  3987. If the next eight bytes are byte1 to byte8, this returns
  3988. (byte8 | (byte7 << 8) | (byte6 << 16) | (byte5 << 24) | (byte4 << 32) | (byte3 << 40) | (byte2 << 48) | (byte1 << 56)).
  3989. If the stream is exhausted partway through reading the bytes, this will return zero.
  3990. @see OutputStream::writeInt64BigEndian, readInt64
  3991. */
  3992. virtual int64 readInt64BigEndian();
  3993. /** Reads four bytes as a 32-bit floating point value.
  3994. The raw 32-bit encoding of the float is read from the stream as a little-endian int.
  3995. If the stream is exhausted partway through reading the bytes, this will return zero.
  3996. @see OutputStream::writeFloat, readDouble
  3997. */
  3998. virtual float readFloat();
  3999. /** Reads four bytes as a 32-bit floating point value.
  4000. The raw 32-bit encoding of the float is read from the stream as a big-endian int.
  4001. If the stream is exhausted partway through reading the bytes, this will return zero.
  4002. @see OutputStream::writeFloatBigEndian, readDoubleBigEndian
  4003. */
  4004. virtual float readFloatBigEndian();
  4005. /** Reads eight bytes as a 64-bit floating point value.
  4006. The raw 64-bit encoding of the double is read from the stream as a little-endian int64.
  4007. If the stream is exhausted partway through reading the bytes, this will return zero.
  4008. @see OutputStream::writeDouble, readFloat
  4009. */
  4010. virtual double readDouble();
  4011. /** Reads eight bytes as a 64-bit floating point value.
  4012. The raw 64-bit encoding of the double is read from the stream as a big-endian int64.
  4013. If the stream is exhausted partway through reading the bytes, this will return zero.
  4014. @see OutputStream::writeDoubleBigEndian, readFloatBigEndian
  4015. */
  4016. virtual double readDoubleBigEndian();
  4017. /** Reads an encoded 32-bit number from the stream using a space-saving compressed format.
  4018. For small values, this is more space-efficient than using readInt() and OutputStream::writeInt()
  4019. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4020. @see OutputStream::writeCompressedInt()
  4021. */
  4022. virtual int readCompressedInt();
  4023. /** Reads a UTF8 string from the stream, up to the next linefeed or carriage return.
  4024. This will read up to the next "\n" or "\r\n" or end-of-stream.
  4025. After this call, the stream's position will be left pointing to the next character
  4026. following the line-feed, but the linefeeds aren't included in the string that
  4027. is returned.
  4028. */
  4029. virtual const String readNextLine();
  4030. /** Reads a zero-terminated UTF8 string from the stream.
  4031. This will read characters from the stream until it hits a zero character or
  4032. end-of-stream.
  4033. @see OutputStream::writeString, readEntireStreamAsString
  4034. */
  4035. virtual const String readString();
  4036. /** Tries to read the whole stream and turn it into a string.
  4037. This will read from the stream's current position until the end-of-stream, and
  4038. will try to make an educated guess about whether it's unicode or an 8-bit encoding.
  4039. */
  4040. virtual const String readEntireStreamAsString();
  4041. /** Reads from the stream and appends the data to a MemoryBlock.
  4042. @param destBlock the block to append the data onto
  4043. @param maxNumBytesToRead if this is a positive value, it sets a limit to the number
  4044. of bytes that will be read - if it's negative, data
  4045. will be read until the stream is exhausted.
  4046. @returns the number of bytes that were added to the memory block
  4047. */
  4048. virtual int readIntoMemoryBlock (MemoryBlock& destBlock,
  4049. int maxNumBytesToRead = -1);
  4050. /** Returns the offset of the next byte that will be read from the stream.
  4051. @see setPosition
  4052. */
  4053. virtual int64 getPosition() = 0;
  4054. /** Tries to move the current read position of the stream.
  4055. The position is an absolute number of bytes from the stream's start.
  4056. Some streams might not be able to do this, in which case they should do
  4057. nothing and return false. Others might be able to manage it by resetting
  4058. themselves and skipping to the correct position, although this is
  4059. obviously a bit slow.
  4060. @returns true if the stream manages to reposition itself correctly
  4061. @see getPosition
  4062. */
  4063. virtual bool setPosition (int64 newPosition) = 0;
  4064. /** Reads and discards a number of bytes from the stream.
  4065. Some input streams might implement this efficiently, but the base
  4066. class will just keep reading data until the requisite number of bytes
  4067. have been done.
  4068. */
  4069. virtual void skipNextBytes (int64 numBytesToSkip);
  4070. juce_UseDebuggingNewOperator
  4071. protected:
  4072. InputStream() throw() {}
  4073. };
  4074. #endif // __JUCE_INPUTSTREAM_JUCEHEADER__
  4075. /*** End of inlined file: juce_InputStream.h ***/
  4076. class File;
  4077. /**
  4078. The base class for streams that write data to some kind of destination.
  4079. Input and output streams are used throughout the library - subclasses can override
  4080. some or all of the virtual functions to implement their behaviour.
  4081. @see InputStream, MemoryOutputStream, FileOutputStream
  4082. */
  4083. class JUCE_API OutputStream
  4084. {
  4085. protected:
  4086. OutputStream();
  4087. public:
  4088. /** Destructor.
  4089. Some subclasses might want to do things like call flush() during their
  4090. destructors.
  4091. */
  4092. virtual ~OutputStream();
  4093. /** If the stream is using a buffer, this will ensure it gets written
  4094. out to the destination. */
  4095. virtual void flush() = 0;
  4096. /** Tries to move the stream's output position.
  4097. Not all streams will be able to seek to a new position - this will return
  4098. false if it fails to work.
  4099. @see getPosition
  4100. */
  4101. virtual bool setPosition (int64 newPosition) = 0;
  4102. /** Returns the stream's current position.
  4103. @see setPosition
  4104. */
  4105. virtual int64 getPosition() = 0;
  4106. /** Writes a block of data to the stream.
  4107. When creating a subclass of OutputStream, this is the only write method
  4108. that needs to be overloaded - the base class has methods for writing other
  4109. types of data which use this to do the work.
  4110. @returns false if the write operation fails for some reason
  4111. */
  4112. virtual bool write (const void* dataToWrite,
  4113. int howManyBytes) = 0;
  4114. /** Writes a single byte to the stream.
  4115. @see InputStream::readByte
  4116. */
  4117. virtual void writeByte (char byte);
  4118. /** Writes a boolean to the stream as a single byte.
  4119. This is encoded as a binary byte (not as text) with a value of 1 or 0.
  4120. @see InputStream::readBool
  4121. */
  4122. virtual void writeBool (bool boolValue);
  4123. /** Writes a 16-bit integer to the stream in a little-endian byte order.
  4124. This will write two bytes to the stream: (value & 0xff), then (value >> 8).
  4125. @see InputStream::readShort
  4126. */
  4127. virtual void writeShort (short value);
  4128. /** Writes a 16-bit integer to the stream in a big-endian byte order.
  4129. This will write two bytes to the stream: (value >> 8), then (value & 0xff).
  4130. @see InputStream::readShortBigEndian
  4131. */
  4132. virtual void writeShortBigEndian (short value);
  4133. /** Writes a 32-bit integer to the stream in a little-endian byte order.
  4134. @see InputStream::readInt
  4135. */
  4136. virtual void writeInt (int value);
  4137. /** Writes a 32-bit integer to the stream in a big-endian byte order.
  4138. @see InputStream::readIntBigEndian
  4139. */
  4140. virtual void writeIntBigEndian (int value);
  4141. /** Writes a 64-bit integer to the stream in a little-endian byte order.
  4142. @see InputStream::readInt64
  4143. */
  4144. virtual void writeInt64 (int64 value);
  4145. /** Writes a 64-bit integer to the stream in a big-endian byte order.
  4146. @see InputStream::readInt64BigEndian
  4147. */
  4148. virtual void writeInt64BigEndian (int64 value);
  4149. /** Writes a 32-bit floating point value to the stream in a binary format.
  4150. The binary 32-bit encoding of the float is written as a little-endian int.
  4151. @see InputStream::readFloat
  4152. */
  4153. virtual void writeFloat (float value);
  4154. /** Writes a 32-bit floating point value to the stream in a binary format.
  4155. The binary 32-bit encoding of the float is written as a big-endian int.
  4156. @see InputStream::readFloatBigEndian
  4157. */
  4158. virtual void writeFloatBigEndian (float value);
  4159. /** Writes a 64-bit floating point value to the stream in a binary format.
  4160. The eight raw bytes of the double value are written out as a little-endian 64-bit int.
  4161. @see InputStream::readDouble
  4162. */
  4163. virtual void writeDouble (double value);
  4164. /** Writes a 64-bit floating point value to the stream in a binary format.
  4165. The eight raw bytes of the double value are written out as a big-endian 64-bit int.
  4166. @see InputStream::readDoubleBigEndian
  4167. */
  4168. virtual void writeDoubleBigEndian (double value);
  4169. /** Writes a condensed binary encoding of a 32-bit integer.
  4170. If you're storing a lot of integers which are unlikely to have very large values,
  4171. this can save a lot of space, because values under 0xff will only take up 2 bytes,
  4172. under 0xffff only 3 bytes, etc.
  4173. The format used is: number of significant bytes + up to 4 bytes in little-endian order.
  4174. @see InputStream::readCompressedInt
  4175. */
  4176. virtual void writeCompressedInt (int value);
  4177. /** Stores a string in the stream in a binary format.
  4178. This isn't the method to use if you're trying to append text to the end of a
  4179. text-file! It's intended for storing a string so that it can be retrieved later
  4180. by InputStream::readString().
  4181. It writes the string to the stream as UTF8, including the null termination character.
  4182. For appending text to a file, instead use writeText, or operator<<
  4183. @see InputStream::readString, writeText, operator<<
  4184. */
  4185. virtual void writeString (const String& text);
  4186. /** Writes a string of text to the stream.
  4187. It can either write it as UTF8 characters or as unicode, and
  4188. can also add unicode header bytes (0xff, 0xfe) to indicate the endianness (this
  4189. should only be done at the start of a file).
  4190. The method also replaces '\\n' characters in the text with '\\r\\n'.
  4191. */
  4192. virtual void writeText (const String& text,
  4193. bool asUnicode,
  4194. bool writeUnicodeHeaderBytes);
  4195. /** Reads data from an input stream and writes it to this stream.
  4196. @param source the stream to read from
  4197. @param maxNumBytesToWrite the number of bytes to read from the stream (if this is
  4198. less than zero, it will keep reading until the input
  4199. is exhausted)
  4200. */
  4201. virtual int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  4202. juce_UseDebuggingNewOperator
  4203. };
  4204. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4205. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, int number);
  4206. /** Writes a number to a stream as 8-bit characters in the default system encoding. */
  4207. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, double number);
  4208. /** Writes a character to a stream. */
  4209. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, char character);
  4210. /** Writes a null-terminated text string to a stream. */
  4211. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* text);
  4212. /** Writes a block of data from a MemoryBlock to a stream. */
  4213. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data);
  4214. /** Writes the contents of a file to a stream. */
  4215. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead);
  4216. #endif // __JUCE_OUTPUTSTREAM_JUCEHEADER__
  4217. /*** End of inlined file: juce_OutputStream.h ***/
  4218. class JUCE_API DynamicObject;
  4219. /**
  4220. A variant class, that can be used to hold a range of primitive values.
  4221. A var object can hold a range of simple primitive values, strings, or
  4222. a reference-counted pointer to a DynamicObject. The var class is intended
  4223. to act like the values used in dynamic scripting languages.
  4224. @see DynamicObject
  4225. */
  4226. class JUCE_API var
  4227. {
  4228. public:
  4229. typedef const var (DynamicObject::*MethodFunction) (const var* arguments, int numArguments);
  4230. typedef Identifier identifier;
  4231. /** Creates a void variant. */
  4232. var() throw();
  4233. /** Destructor. */
  4234. ~var() throw();
  4235. /** A static var object that can be used where you need an empty variant object. */
  4236. static const var null;
  4237. var (const var& valueToCopy);
  4238. var (int value) throw();
  4239. var (bool value) throw();
  4240. var (double value) throw();
  4241. var (const char* value);
  4242. var (const juce_wchar* value);
  4243. var (const String& value);
  4244. var (DynamicObject* object);
  4245. var (MethodFunction method) throw();
  4246. var& operator= (const var& valueToCopy);
  4247. var& operator= (int value);
  4248. var& operator= (bool value);
  4249. var& operator= (double value);
  4250. var& operator= (const char* value);
  4251. var& operator= (const juce_wchar* value);
  4252. var& operator= (const String& value);
  4253. var& operator= (DynamicObject* object);
  4254. var& operator= (MethodFunction method);
  4255. void swapWith (var& other) throw();
  4256. operator int() const;
  4257. operator bool() const;
  4258. operator float() const;
  4259. operator double() const;
  4260. operator const String() const;
  4261. const String toString() const;
  4262. DynamicObject* getObject() const;
  4263. bool isVoid() const throw();
  4264. bool isInt() const throw();
  4265. bool isBool() const throw();
  4266. bool isDouble() const throw();
  4267. bool isString() const throw();
  4268. bool isObject() const throw();
  4269. bool isMethod() const throw();
  4270. /** Writes a binary representation of this value to a stream.
  4271. The data can be read back later using readFromStream().
  4272. */
  4273. void writeToStream (OutputStream& output) const;
  4274. /** Reads back a stored binary representation of a value.
  4275. The data in the stream must have been written using writeToStream(), or this
  4276. will have unpredictable results.
  4277. */
  4278. static const var readFromStream (InputStream& input);
  4279. /** If this variant is an object, this returns one of its properties. */
  4280. const var operator[] (const Identifier& propertyName) const;
  4281. /** If this variant is an object, this invokes one of its methods with no arguments. */
  4282. const var call (const Identifier& method) const;
  4283. /** If this variant is an object, this invokes one of its methods with one argument. */
  4284. const var call (const Identifier& method, const var& arg1) const;
  4285. /** If this variant is an object, this invokes one of its methods with 2 arguments. */
  4286. const var call (const Identifier& method, const var& arg1, const var& arg2) const;
  4287. /** If this variant is an object, this invokes one of its methods with 3 arguments. */
  4288. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
  4289. /** If this variant is an object, this invokes one of its methods with 4 arguments. */
  4290. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
  4291. /** If this variant is an object, this invokes one of its methods with 5 arguments. */
  4292. const var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
  4293. /** If this variant is an object, this invokes one of its methods with a list of arguments. */
  4294. const var invoke (const Identifier& method, const var* arguments, int numArguments) const;
  4295. /** If this variant is a method pointer, this invokes it on a target object. */
  4296. const var invoke (const var& targetObject, const var* arguments, int numArguments) const;
  4297. juce_UseDebuggingNewOperator
  4298. /** Returns true if this var has the same value as the one supplied. */
  4299. bool equals (const var& other) const throw();
  4300. private:
  4301. class VariantType;
  4302. friend class VariantType;
  4303. class VariantType_Void;
  4304. friend class VariantType_Void;
  4305. class VariantType_Int;
  4306. friend class VariantType_Int;
  4307. class VariantType_Double;
  4308. friend class VariantType_Double;
  4309. class VariantType_Float;
  4310. friend class VariantType_Float;
  4311. class VariantType_Bool;
  4312. friend class VariantType_Bool;
  4313. class VariantType_String;
  4314. friend class VariantType_String;
  4315. class VariantType_Object;
  4316. friend class VariantType_Object;
  4317. class VariantType_Method;
  4318. friend class VariantType_Method;
  4319. union ValueUnion
  4320. {
  4321. int intValue;
  4322. bool boolValue;
  4323. double doubleValue;
  4324. String* stringValue;
  4325. DynamicObject* objectValue;
  4326. MethodFunction methodValue;
  4327. };
  4328. const VariantType* type;
  4329. ValueUnion value;
  4330. };
  4331. bool operator== (const var& v1, const var& v2) throw();
  4332. bool operator!= (const var& v1, const var& v2) throw();
  4333. bool operator== (const var& v1, const String& v2) throw();
  4334. bool operator!= (const var& v1, const String& v2) throw();
  4335. #endif // __JUCE_VARIANT_JUCEHEADER__
  4336. /*** End of inlined file: juce_Variant.h ***/
  4337. /** Holds a set of named var objects.
  4338. This can be used as a basic structure to hold a set of var object, which can
  4339. be retrieved by using their identifier.
  4340. */
  4341. class JUCE_API NamedValueSet
  4342. {
  4343. public:
  4344. /** Creates an empty set. */
  4345. NamedValueSet() throw();
  4346. /** Creates a copy of another set. */
  4347. NamedValueSet (const NamedValueSet& other);
  4348. /** Replaces this set with a copy of another set. */
  4349. NamedValueSet& operator= (const NamedValueSet& other);
  4350. /** Destructor. */
  4351. ~NamedValueSet();
  4352. bool operator== (const NamedValueSet& other) const;
  4353. bool operator!= (const NamedValueSet& other) const;
  4354. /** Returns the total number of values that the set contains. */
  4355. int size() const throw();
  4356. /** Returns the value of a named item.
  4357. If the name isn't found, this will return a void variant.
  4358. @see getProperty
  4359. */
  4360. const var& operator[] (const Identifier& name) const;
  4361. /** Tries to return the named value, but if no such value is found, this will
  4362. instead return the supplied default value.
  4363. */
  4364. const var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
  4365. /** Returns a pointer to the object holding a named value, or
  4366. null if there is no value with this name. */
  4367. var* getItem (const Identifier& name) const;
  4368. /** Changes or adds a named value.
  4369. @returns true if a value was changed or added; false if the
  4370. value was already set the the value passed-in.
  4371. */
  4372. bool set (const Identifier& name, const var& newValue);
  4373. /** Returns true if the set contains an item with the specified name. */
  4374. bool contains (const Identifier& name) const;
  4375. /** Removes a value from the set.
  4376. @returns true if a value was removed; false if there was no value
  4377. with the name that was given.
  4378. */
  4379. bool remove (const Identifier& name);
  4380. /** Returns the name of the value at a given index.
  4381. The index must be between 0 and size() - 1. Out-of-range indexes will
  4382. return an empty identifier.
  4383. */
  4384. const Identifier getName (int index) const;
  4385. /** Returns the value of the item at a given index.
  4386. The index must be between 0 and size() - 1. Out-of-range indexes will
  4387. return an empty identifier.
  4388. */
  4389. const var getValueAt (int index) const;
  4390. /** Removes all values. */
  4391. void clear();
  4392. juce_UseDebuggingNewOperator
  4393. private:
  4394. struct NamedValue
  4395. {
  4396. NamedValue() throw();
  4397. NamedValue (const Identifier& name, const var& value);
  4398. bool operator== (const NamedValue& other) const throw();
  4399. Identifier name;
  4400. var value;
  4401. };
  4402. Array <NamedValue> values;
  4403. };
  4404. #endif // __JUCE_NAMEDVALUESET_JUCEHEADER__
  4405. /*** End of inlined file: juce_NamedValueSet.h ***/
  4406. /*** Start of inlined file: juce_ReferenceCountedObject.h ***/
  4407. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4408. #define __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4409. /*** Start of inlined file: juce_Atomic.h ***/
  4410. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  4411. #define __JUCE_ATOMIC_JUCEHEADER__
  4412. /**
  4413. Simple class to hold a primitive value and perform atomic operations on it.
  4414. The type used must be a 32 or 64 bit primitive, like an int, pointer, etc.
  4415. There are methods to perform most of the basic atomic operations.
  4416. */
  4417. template <typename Type>
  4418. class Atomic
  4419. {
  4420. public:
  4421. /** Creates a new value, initialised to zero. */
  4422. inline Atomic() throw()
  4423. : value (0)
  4424. {
  4425. }
  4426. /** Creates a new value, with a given initial value. */
  4427. inline Atomic (const Type initialValue) throw()
  4428. : value (initialValue)
  4429. {
  4430. }
  4431. /** Copies another value (atomically). */
  4432. inline Atomic (const Atomic& other) throw()
  4433. : value (other.get())
  4434. {
  4435. }
  4436. /** Destructor. */
  4437. inline ~Atomic() throw()
  4438. {
  4439. // This class can only be used for types which are 32 or 64 bits in size.
  4440. static_jassert (sizeof (Type) == 4 || sizeof (Type) == 8);
  4441. }
  4442. /** Atomically reads and returns the current value. */
  4443. Type get() const throw();
  4444. /** Copies another value onto this one (atomically). */
  4445. inline Atomic& operator= (const Atomic& other) throw() { exchange (other.get()); return *this; }
  4446. /** Copies another value onto this one (atomically). */
  4447. inline Atomic& operator= (const Type newValue) throw() { exchange (newValue); return *this; }
  4448. /** Atomically sets the current value. */
  4449. void set (Type newValue) throw() { exchange (newValue); }
  4450. /** Atomically sets the current value, returning the value that was replaced. */
  4451. Type exchange (Type value) throw();
  4452. /** Atomically adds a number to this value, returning the new value. */
  4453. Type operator+= (Type amountToAdd) throw();
  4454. /** Atomically subtracts a number from this value, returning the new value. */
  4455. Type operator-= (Type amountToSubtract) throw();
  4456. /** Atomically increments this value, returning the new value. */
  4457. Type operator++() throw();
  4458. /** Atomically decrements this value, returning the new value. */
  4459. Type operator--() throw();
  4460. /** Atomically compares this value with a target value, and if it is equal, sets
  4461. this to be equal to a new value.
  4462. This operation is the atomic equivalent of doing this:
  4463. @code
  4464. bool compareAndSetBool (Type newValue, Type valueToCompare)
  4465. {
  4466. if (get() == valueToCompare)
  4467. {
  4468. set (newValue);
  4469. return true;
  4470. }
  4471. return false;
  4472. }
  4473. @endcode
  4474. @returns true if the comparison was true and the value was replaced; false if
  4475. the comparison failed and the value was left unchanged.
  4476. @see compareAndSetValue
  4477. */
  4478. bool compareAndSetBool (Type newValue, Type valueToCompare) throw();
  4479. /** Atomically compares this value with a target value, and if it is equal, sets
  4480. this to be equal to a new value.
  4481. This operation is the atomic equivalent of doing this:
  4482. @code
  4483. Type compareAndSetValue (Type newValue, Type valueToCompare)
  4484. {
  4485. Type oldValue = get();
  4486. if (oldValue == valueToCompare)
  4487. set (newValue);
  4488. return oldValue;
  4489. }
  4490. @endcode
  4491. @returns the old value before it was changed.
  4492. @see compareAndSetBool
  4493. */
  4494. Type compareAndSetValue (Type newValue, Type valueToCompare) throw();
  4495. /** Implements a memory read/write barrier. */
  4496. static void memoryBarrier() throw();
  4497. JUCE_ALIGN(8)
  4498. /** The raw value that this class operates on.
  4499. This is exposed publically in case you need to manipulate it directly
  4500. for performance reasons.
  4501. */
  4502. volatile Type value;
  4503. private:
  4504. static inline Type castFrom32Bit (int32 value) throw() { return *(Type*) &value; }
  4505. static inline Type castFrom64Bit (int64 value) throw() { return *(Type*) &value; }
  4506. static inline int32 castTo32Bit (Type value) throw() { return *(int32*) &value; }
  4507. static inline int64 castTo64Bit (Type value) throw() { return *(int64*) &value; }
  4508. };
  4509. /*
  4510. The following code is in the header so that the atomics can be inlined where possible...
  4511. */
  4512. #if (JUCE_IPHONE && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_3_2 || ! defined (__IPHONE_3_2))) \
  4513. || (JUCE_MAC && (JUCE_PPC || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)))
  4514. #define JUCE_ATOMICS_MAC 1 // Older OSX builds using gcc4.1 or earlier
  4515. #if JUCE_PPC || JUCE_IPHONE
  4516. // None of these atomics are available for PPC or for iPhoneOS 3.1 or earlier!!
  4517. template <typename Type> static Type OSAtomicAdd64Barrier (Type b, volatile Type* a) throw() { jassertfalse; return *a += b; }
  4518. template <typename Type> static Type OSAtomicIncrement64Barrier (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4519. template <typename Type> static Type OSAtomicDecrement64Barrier (volatile Type* a) throw() { jassertfalse; return --*a; }
  4520. template <typename Type> static bool OSAtomicCompareAndSwap64Barrier (Type old, Type newValue, volatile Type* value) throw()
  4521. { jassertfalse; if (old == *value) { *value = newValue; return true; } return false; }
  4522. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4523. #endif
  4524. #elif JUCE_GCC
  4525. #define JUCE_ATOMICS_GCC 1 // GCC with intrinsics
  4526. #if JUCE_IPHONE
  4527. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1 // (on the iphone, the 64-bit ops will compile but not link)
  4528. #endif
  4529. #else
  4530. #define JUCE_ATOMICS_WINDOWS 1 // Windows with intrinsics
  4531. #if JUCE_USE_INTRINSICS || JUCE_64BIT
  4532. #pragma intrinsic (_InterlockedExchange, _InterlockedIncrement, _InterlockedDecrement, _InterlockedCompareExchange, \
  4533. _InterlockedCompareExchange64, _InterlockedExchangeAdd, _ReadWriteBarrier)
  4534. #define juce_InterlockedExchange(a, b) _InterlockedExchange(a, b)
  4535. #define juce_InterlockedIncrement(a) _InterlockedIncrement(a)
  4536. #define juce_InterlockedDecrement(a) _InterlockedDecrement(a)
  4537. #define juce_InterlockedExchangeAdd(a, b) _InterlockedExchangeAdd(a, b)
  4538. #define juce_InterlockedCompareExchange(a, b, c) _InterlockedCompareExchange(a, b, c)
  4539. #define juce_InterlockedCompareExchange64(a, b, c) _InterlockedCompareExchange64(a, b, c)
  4540. #define juce_MemoryBarrier _ReadWriteBarrier
  4541. #else
  4542. // (these are defined in juce_win32_Threads.cpp)
  4543. long juce_InterlockedExchange (volatile long* a, long b) throw();
  4544. long juce_InterlockedIncrement (volatile long* a) throw();
  4545. long juce_InterlockedDecrement (volatile long* a) throw();
  4546. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw();
  4547. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw();
  4548. __int64 juce_InterlockedCompareExchange64 (volatile __int64* a, __int64 b, __int64 c) throw();
  4549. static void juce_MemoryBarrier() throw() { long x = 0; juce_InterlockedIncrement (&x); }
  4550. #endif
  4551. #if JUCE_64BIT
  4552. #pragma intrinsic (_InterlockedExchangeAdd64, _InterlockedExchange64, _InterlockedIncrement64, _InterlockedDecrement64)
  4553. #define juce_InterlockedExchangeAdd64(a, b) _InterlockedExchangeAdd64(a, b)
  4554. #define juce_InterlockedExchange64(a, b) _InterlockedExchange64(a, b)
  4555. #define juce_InterlockedIncrement64(a) _InterlockedIncrement64(a)
  4556. #define juce_InterlockedDecrement64(a) _InterlockedDecrement64(a)
  4557. #else
  4558. // None of these atomics are available in a 32-bit Windows build!!
  4559. template <typename Type> static Type juce_InterlockedExchangeAdd64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a += b; return old; }
  4560. template <typename Type> static Type juce_InterlockedExchange64 (volatile Type* a, Type b) throw() { jassertfalse; Type old = *a; *a = b; return old; }
  4561. template <typename Type> static Type juce_InterlockedIncrement64 (volatile Type* a) throw() { jassertfalse; return ++*a; }
  4562. template <typename Type> static Type juce_InterlockedDecrement64 (volatile Type* a) throw() { jassertfalse; return --*a; }
  4563. #define JUCE_64BIT_ATOMICS_UNAVAILABLE 1
  4564. #endif
  4565. #endif
  4566. #if JUCE_MSVC
  4567. #pragma warning (push)
  4568. #pragma warning (disable: 4311) // (truncation warning)
  4569. #endif
  4570. template <typename Type>
  4571. inline Type Atomic<Type>::get() const throw()
  4572. {
  4573. #if JUCE_ATOMICS_MAC
  4574. return sizeof (Type) == 4 ? castFrom32Bit ((int32) OSAtomicAdd32Barrier (0, (int32_t*) &value))
  4575. : castFrom64Bit ((int64) OSAtomicAdd64Barrier (0, (int64_t*) &value));
  4576. #elif JUCE_ATOMICS_WINDOWS
  4577. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchangeAdd ((volatile long*) &value, (long) 0))
  4578. : castFrom64Bit ((int64) juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) 0));
  4579. #elif JUCE_ATOMICS_GCC
  4580. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_add_and_fetch ((volatile int32*) &value, 0))
  4581. : castFrom64Bit ((int64) __sync_add_and_fetch ((volatile int64*) &value, 0));
  4582. #endif
  4583. }
  4584. template <typename Type>
  4585. inline Type Atomic<Type>::exchange (const Type newValue) throw()
  4586. {
  4587. #if JUCE_ATOMICS_MAC || JUCE_ATOMICS_GCC
  4588. Type currentVal = value;
  4589. while (! compareAndSetBool (newValue, currentVal)) { currentVal = value; }
  4590. return currentVal;
  4591. #elif JUCE_ATOMICS_WINDOWS
  4592. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedExchange ((volatile long*) &value, (long) castTo32Bit (newValue)))
  4593. : castFrom64Bit ((int64) juce_InterlockedExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue)));
  4594. #endif
  4595. }
  4596. template <typename Type>
  4597. inline Type Atomic<Type>::operator+= (const Type amountToAdd) throw()
  4598. {
  4599. #if JUCE_ATOMICS_MAC
  4600. return sizeof (Type) == 4 ? (Type) OSAtomicAdd32Barrier ((int32_t) amountToAdd, (int32_t*) &value)
  4601. : (Type) OSAtomicAdd64Barrier ((int64_t) amountToAdd, (int64_t*) &value);
  4602. #elif JUCE_ATOMICS_WINDOWS
  4603. return sizeof (Type) == 4 ? (Type) (juce_InterlockedExchangeAdd ((volatile long*) &value, (long) amountToAdd) + (long) amountToAdd)
  4604. : (Type) (juce_InterlockedExchangeAdd64 ((volatile __int64*) &value, (__int64) amountToAdd) + (__int64) amountToAdd);
  4605. #elif JUCE_ATOMICS_GCC
  4606. return (Type) __sync_add_and_fetch (&value, amountToAdd);
  4607. #endif
  4608. }
  4609. template <typename Type>
  4610. inline Type Atomic<Type>::operator-= (const Type amountToSubtract) throw()
  4611. {
  4612. return operator+= (juce_negate (amountToSubtract));
  4613. }
  4614. template <typename Type>
  4615. inline Type Atomic<Type>::operator++() throw()
  4616. {
  4617. #if JUCE_ATOMICS_MAC
  4618. return sizeof (Type) == 4 ? (Type) OSAtomicIncrement32Barrier ((int32_t*) &value)
  4619. : (Type) OSAtomicIncrement64Barrier ((int64_t*) &value);
  4620. #elif JUCE_ATOMICS_WINDOWS
  4621. return sizeof (Type) == 4 ? (Type) juce_InterlockedIncrement ((volatile long*) &value)
  4622. : (Type) juce_InterlockedIncrement64 ((volatile __int64*) &value);
  4623. #elif JUCE_ATOMICS_GCC
  4624. return (Type) __sync_add_and_fetch (&value, 1);
  4625. #endif
  4626. }
  4627. template <typename Type>
  4628. inline Type Atomic<Type>::operator--() throw()
  4629. {
  4630. #if JUCE_ATOMICS_MAC
  4631. return sizeof (Type) == 4 ? (Type) OSAtomicDecrement32Barrier ((int32_t*) &value)
  4632. : (Type) OSAtomicDecrement64Barrier ((int64_t*) &value);
  4633. #elif JUCE_ATOMICS_WINDOWS
  4634. return sizeof (Type) == 4 ? (Type) juce_InterlockedDecrement ((volatile long*) &value)
  4635. : (Type) juce_InterlockedDecrement64 ((volatile __int64*) &value);
  4636. #elif JUCE_ATOMICS_GCC
  4637. return (Type) __sync_add_and_fetch (&value, -1);
  4638. #endif
  4639. }
  4640. template <typename Type>
  4641. inline bool Atomic<Type>::compareAndSetBool (const Type newValue, const Type valueToCompare) throw()
  4642. {
  4643. #if JUCE_ATOMICS_MAC
  4644. return sizeof (Type) == 4 ? OSAtomicCompareAndSwap32Barrier ((int32_t) castTo32Bit (valueToCompare), (int32_t) castTo32Bit (newValue), (int32_t*) &value)
  4645. : OSAtomicCompareAndSwap64Barrier ((int64_t) castTo64Bit (valueToCompare), (int64_t) castTo64Bit (newValue), (int64_t*) &value);
  4646. #elif JUCE_ATOMICS_WINDOWS
  4647. return compareAndSetValue (newValue, valueToCompare) == valueToCompare;
  4648. #elif JUCE_ATOMICS_GCC
  4649. return sizeof (Type) == 4 ? __sync_bool_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue))
  4650. : __sync_bool_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue));
  4651. #endif
  4652. }
  4653. template <typename Type>
  4654. inline Type Atomic<Type>::compareAndSetValue (const Type newValue, const Type valueToCompare) throw()
  4655. {
  4656. #if JUCE_ATOMICS_MAC
  4657. for (;;) // Annoying workaround for OSX only having a bool CAS operation..
  4658. {
  4659. if (compareAndSetBool (newValue, valueToCompare))
  4660. return valueToCompare;
  4661. const Type result = value;
  4662. if (result != valueToCompare)
  4663. return result;
  4664. }
  4665. #elif JUCE_ATOMICS_WINDOWS
  4666. return sizeof (Type) == 4 ? castFrom32Bit ((int32) juce_InterlockedCompareExchange ((volatile long*) &value, (long) castTo32Bit (newValue), (long) castTo32Bit (valueToCompare)))
  4667. : castFrom64Bit ((int64) juce_InterlockedCompareExchange64 ((volatile __int64*) &value, (__int64) castTo64Bit (newValue), (__int64) castTo64Bit (valueToCompare)));
  4668. #elif JUCE_ATOMICS_GCC
  4669. return sizeof (Type) == 4 ? castFrom32Bit ((int32) __sync_val_compare_and_swap ((volatile int32*) &value, castTo32Bit (valueToCompare), castTo32Bit (newValue)))
  4670. : castFrom64Bit ((int64) __sync_val_compare_and_swap ((volatile int64*) &value, castTo64Bit (valueToCompare), castTo64Bit (newValue)));
  4671. #endif
  4672. }
  4673. template <typename Type>
  4674. inline void Atomic<Type>::memoryBarrier() throw()
  4675. {
  4676. #if JUCE_ATOMICS_MAC
  4677. OSMemoryBarrier();
  4678. #elif JUCE_ATOMICS_GCC
  4679. __sync_synchronize();
  4680. #elif JUCE_ATOMICS_WINDOWS
  4681. juce_MemoryBarrier();
  4682. #endif
  4683. }
  4684. #if JUCE_MSVC
  4685. #pragma warning (pop)
  4686. #endif
  4687. #endif // __JUCE_ATOMIC_JUCEHEADER__
  4688. /*** End of inlined file: juce_Atomic.h ***/
  4689. /**
  4690. Adds reference-counting to an object.
  4691. To add reference-counting to a class, derive it from this class, and
  4692. use the ReferenceCountedObjectPtr class to point to it.
  4693. e.g. @code
  4694. class MyClass : public ReferenceCountedObject
  4695. {
  4696. void foo();
  4697. // This is a neat way of declaring a typedef for a pointer class,
  4698. // rather than typing out the full templated name each time..
  4699. typedef ReferenceCountedObjectPtr<MyClass> Ptr;
  4700. };
  4701. MyClass::Ptr p = new MyClass();
  4702. MyClass::Ptr p2 = p;
  4703. p = 0;
  4704. p2->foo();
  4705. @endcode
  4706. Once a new ReferenceCountedObject has been assigned to a pointer, be
  4707. careful not to delete the object manually.
  4708. @see ReferenceCountedObjectPtr, ReferenceCountedArray
  4709. */
  4710. class JUCE_API ReferenceCountedObject
  4711. {
  4712. public:
  4713. /** Increments the object's reference count.
  4714. This is done automatically by the smart pointer, but is public just
  4715. in case it's needed for nefarious purposes.
  4716. */
  4717. inline void incReferenceCount() throw()
  4718. {
  4719. ++refCount;
  4720. }
  4721. /** Decreases the object's reference count.
  4722. If the count gets to zero, the object will be deleted.
  4723. */
  4724. inline void decReferenceCount() throw()
  4725. {
  4726. jassert (getReferenceCount() > 0);
  4727. if (--refCount == 0)
  4728. delete this;
  4729. }
  4730. /** Returns the object's current reference count. */
  4731. inline int getReferenceCount() const throw()
  4732. {
  4733. return refCount.get();
  4734. }
  4735. protected:
  4736. /** Creates the reference-counted object (with an initial ref count of zero). */
  4737. ReferenceCountedObject()
  4738. {
  4739. }
  4740. /** Destructor. */
  4741. virtual ~ReferenceCountedObject()
  4742. {
  4743. // it's dangerous to delete an object that's still referenced by something else!
  4744. jassert (getReferenceCount() == 0);
  4745. }
  4746. private:
  4747. Atomic <int> refCount;
  4748. };
  4749. /**
  4750. Used to point to an object of type ReferenceCountedObject.
  4751. It's wise to use a typedef instead of typing out the templated name
  4752. each time - e.g.
  4753. typedef ReferenceCountedObjectPtr<MyClass> MyClassPtr;
  4754. @see ReferenceCountedObject, ReferenceCountedObjectArray
  4755. */
  4756. template <class ReferenceCountedObjectClass>
  4757. class ReferenceCountedObjectPtr
  4758. {
  4759. public:
  4760. /** Creates a pointer to a null object. */
  4761. inline ReferenceCountedObjectPtr() throw()
  4762. : referencedObject (0)
  4763. {
  4764. }
  4765. /** Creates a pointer to an object.
  4766. This will increment the object's reference-count if it is non-null.
  4767. */
  4768. inline ReferenceCountedObjectPtr (ReferenceCountedObjectClass* const refCountedObject) throw()
  4769. : referencedObject (refCountedObject)
  4770. {
  4771. if (refCountedObject != 0)
  4772. refCountedObject->incReferenceCount();
  4773. }
  4774. /** Copies another pointer.
  4775. This will increment the object's reference-count (if it is non-null).
  4776. */
  4777. inline ReferenceCountedObjectPtr (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other) throw()
  4778. : referencedObject (other.referencedObject)
  4779. {
  4780. if (referencedObject != 0)
  4781. referencedObject->incReferenceCount();
  4782. }
  4783. /** Changes this pointer to point at a different object.
  4784. The reference count of the old object is decremented, and it might be
  4785. deleted if it hits zero. The new object's count is incremented.
  4786. */
  4787. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (const ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& other)
  4788. {
  4789. ReferenceCountedObjectClass* const newObject = other.referencedObject;
  4790. if (newObject != referencedObject)
  4791. {
  4792. if (newObject != 0)
  4793. newObject->incReferenceCount();
  4794. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4795. referencedObject = newObject;
  4796. if (oldObject != 0)
  4797. oldObject->decReferenceCount();
  4798. }
  4799. return *this;
  4800. }
  4801. /** Changes this pointer to point at a different object.
  4802. The reference count of the old object is decremented, and it might be
  4803. deleted if it hits zero. The new object's count is incremented.
  4804. */
  4805. ReferenceCountedObjectPtr<ReferenceCountedObjectClass>& operator= (ReferenceCountedObjectClass* const newObject)
  4806. {
  4807. if (referencedObject != newObject)
  4808. {
  4809. if (newObject != 0)
  4810. newObject->incReferenceCount();
  4811. ReferenceCountedObjectClass* const oldObject = referencedObject;
  4812. referencedObject = newObject;
  4813. if (oldObject != 0)
  4814. oldObject->decReferenceCount();
  4815. }
  4816. return *this;
  4817. }
  4818. /** Destructor.
  4819. This will decrement the object's reference-count, and may delete it if it
  4820. gets to zero.
  4821. */
  4822. inline ~ReferenceCountedObjectPtr()
  4823. {
  4824. if (referencedObject != 0)
  4825. referencedObject->decReferenceCount();
  4826. }
  4827. /** Returns the object that this pointer references.
  4828. The pointer returned may be zero, of course.
  4829. */
  4830. inline operator ReferenceCountedObjectClass*() const throw()
  4831. {
  4832. return referencedObject;
  4833. }
  4834. /** Returns true if this pointer refers to the given object. */
  4835. inline bool operator== (ReferenceCountedObjectClass* const object) const throw()
  4836. {
  4837. return referencedObject == object;
  4838. }
  4839. /** Returns true if this pointer doesn't refer to the given object. */
  4840. inline bool operator!= (ReferenceCountedObjectClass* const object) const throw()
  4841. {
  4842. return referencedObject != object;
  4843. }
  4844. // the -> operator is called on the referenced object
  4845. inline ReferenceCountedObjectClass* operator->() const throw()
  4846. {
  4847. return referencedObject;
  4848. }
  4849. /** Returns the object that this pointer references.
  4850. The pointer returned may be zero, of course.
  4851. */
  4852. inline ReferenceCountedObjectClass* getObject() const throw()
  4853. {
  4854. return referencedObject;
  4855. }
  4856. private:
  4857. ReferenceCountedObjectClass* referencedObject;
  4858. };
  4859. #endif // __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  4860. /*** End of inlined file: juce_ReferenceCountedObject.h ***/
  4861. /**
  4862. Represents a dynamically implemented object.
  4863. This class is primarily intended for wrapping scripting language objects,
  4864. but could be used for other purposes.
  4865. An instance of a DynamicObject can be used to store named properties, and
  4866. by subclassing hasMethod() and invokeMethod(), you can give your object
  4867. methods.
  4868. */
  4869. class JUCE_API DynamicObject : public ReferenceCountedObject
  4870. {
  4871. public:
  4872. DynamicObject();
  4873. /** Destructor. */
  4874. virtual ~DynamicObject();
  4875. /** Returns true if the object has a property with this name.
  4876. Note that if the property is actually a method, this will return false.
  4877. */
  4878. virtual bool hasProperty (const Identifier& propertyName) const;
  4879. /** Returns a named property.
  4880. This returns a void if no such property exists.
  4881. */
  4882. virtual const var getProperty (const Identifier& propertyName) const;
  4883. /** Sets a named property. */
  4884. virtual void setProperty (const Identifier& propertyName, const var& newValue);
  4885. /** Removes a named property. */
  4886. virtual void removeProperty (const Identifier& propertyName);
  4887. /** Checks whether this object has the specified method.
  4888. The default implementation of this just checks whether there's a property
  4889. with this name that's actually a method, but this can be overridden for
  4890. building objects with dynamic invocation.
  4891. */
  4892. virtual bool hasMethod (const Identifier& methodName) const;
  4893. /** Invokes a named method on this object.
  4894. The default implementation looks up the named property, and if it's a method
  4895. call, then it invokes it.
  4896. This method is virtual to allow more dynamic invocation to used for objects
  4897. where the methods may not already be set as properies.
  4898. */
  4899. virtual const var invokeMethod (const Identifier& methodName,
  4900. const var* parameters,
  4901. int numParameters);
  4902. /** Sets up a method.
  4903. This is basically the same as calling setProperty (methodName, (var::MethodFunction) myFunction), but
  4904. helps to avoid accidentally invoking the wrong type of var constructor. It also makes
  4905. the code easier to read,
  4906. The compiler will probably force you to use an explicit cast your method to a (var::MethodFunction), e.g.
  4907. @code
  4908. setMethod ("doSomething", (var::MethodFunction) &MyClass::doSomething);
  4909. @endcode
  4910. */
  4911. void setMethod (const Identifier& methodName,
  4912. var::MethodFunction methodFunction);
  4913. /** Removes all properties and methods from the object. */
  4914. void clear();
  4915. juce_UseDebuggingNewOperator
  4916. private:
  4917. NamedValueSet properties;
  4918. };
  4919. #endif // __JUCE_DYNAMICOBJECT_JUCEHEADER__
  4920. /*** End of inlined file: juce_DynamicObject.h ***/
  4921. #endif
  4922. #ifndef __JUCE_ELEMENTCOMPARATOR_JUCEHEADER__
  4923. #endif
  4924. #ifndef __JUCE_HEAPBLOCK_JUCEHEADER__
  4925. #endif
  4926. #ifndef __JUCE_IDENTIFIER_JUCEHEADER__
  4927. #endif
  4928. #ifndef __JUCE_MEMORYBLOCK_JUCEHEADER__
  4929. #endif
  4930. #ifndef __JUCE_NAMEDVALUESET_JUCEHEADER__
  4931. #endif
  4932. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4933. /*** Start of inlined file: juce_OwnedArray.h ***/
  4934. #ifndef __JUCE_OWNEDARRAY_JUCEHEADER__
  4935. #define __JUCE_OWNEDARRAY_JUCEHEADER__
  4936. /*** Start of inlined file: juce_ScopedPointer.h ***/
  4937. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4938. #define __JUCE_SCOPEDPOINTER_JUCEHEADER__
  4939. /**
  4940. This class holds a pointer which is automatically deleted when this object goes
  4941. out of scope.
  4942. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  4943. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  4944. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  4945. created objects.
  4946. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  4947. to an object. If you use the assignment operator to assign a different object to a
  4948. ScopedPointer, the old one will be automatically deleted.
  4949. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  4950. object to which it points during its lifetime. This means that making a copy of a const
  4951. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  4952. old one.
  4953. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  4954. can use the release() method.
  4955. */
  4956. template <class ObjectType>
  4957. class ScopedPointer
  4958. {
  4959. public:
  4960. /** Creates a ScopedPointer containing a null pointer. */
  4961. inline ScopedPointer() throw() : object (0)
  4962. {
  4963. }
  4964. /** Creates a ScopedPointer that owns the specified object. */
  4965. inline ScopedPointer (ObjectType* const objectToTakePossessionOf) throw()
  4966. : object (objectToTakePossessionOf)
  4967. {
  4968. }
  4969. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  4970. Because a pointer can only belong to one ScopedPointer, this transfers
  4971. the pointer from the other object to this one, and the other object is reset to
  4972. be a null pointer.
  4973. */
  4974. ScopedPointer (ScopedPointer& objectToTransferFrom) throw()
  4975. : object (objectToTransferFrom.object)
  4976. {
  4977. objectToTransferFrom.object = 0;
  4978. }
  4979. /** Destructor.
  4980. This will delete the object that this ScopedPointer currently refers to.
  4981. */
  4982. inline ~ScopedPointer() { delete object; }
  4983. /** Changes this ScopedPointer to point to a new object.
  4984. Because a pointer can only belong to one ScopedPointer, this transfers
  4985. the pointer from the other object to this one, and the other object is reset to
  4986. be a null pointer.
  4987. If this ScopedPointer already points to an object, that object
  4988. will first be deleted.
  4989. */
  4990. ScopedPointer& operator= (ScopedPointer& objectToTransferFrom)
  4991. {
  4992. if (this != objectToTransferFrom.getAddress())
  4993. {
  4994. // Two ScopedPointers should never be able to refer to the same object - if
  4995. // this happens, you must have done something dodgy!
  4996. jassert (object == 0 || object != objectToTransferFrom.object);
  4997. ObjectType* const oldObject = object;
  4998. object = objectToTransferFrom.object;
  4999. objectToTransferFrom.object = 0;
  5000. delete oldObject;
  5001. }
  5002. return *this;
  5003. }
  5004. /** Changes this ScopedPointer to point to a new object.
  5005. If this ScopedPointer already points to an object, that object
  5006. will first be deleted.
  5007. The pointer that you pass is may be null.
  5008. */
  5009. ScopedPointer& operator= (ObjectType* const newObjectToTakePossessionOf)
  5010. {
  5011. if (object != newObjectToTakePossessionOf)
  5012. {
  5013. ObjectType* const oldObject = object;
  5014. object = newObjectToTakePossessionOf;
  5015. delete oldObject;
  5016. }
  5017. return *this;
  5018. }
  5019. /** Returns the object that this ScopedPointer refers to.
  5020. */
  5021. inline operator ObjectType*() const throw() { return object; }
  5022. /** Returns the object that this ScopedPointer refers to.
  5023. */
  5024. inline ObjectType& operator*() const throw() { return *object; }
  5025. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  5026. inline ObjectType* operator->() const throw() { return object; }
  5027. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  5028. inline ObjectType* const* operator&() const throw() { return static_cast <ObjectType* const*> (&object); }
  5029. /** Returns a reference to the address of the object that this ScopedPointer refers to. */
  5030. inline ObjectType** operator&() throw() { return static_cast <ObjectType**> (&object); }
  5031. /** Removes the current object from this ScopedPointer without deleting it.
  5032. This will return the current object, and set the ScopedPointer to a null pointer.
  5033. */
  5034. ObjectType* release() throw() { ObjectType* const o = object; object = 0; return o; }
  5035. /** Swaps this object with that of another ScopedPointer.
  5036. The two objects simply exchange their pointers.
  5037. */
  5038. void swapWith (ScopedPointer <ObjectType>& other) throw()
  5039. {
  5040. // Two ScopedPointers should never be able to refer to the same object - if
  5041. // this happens, you must have done something dodgy!
  5042. jassert (object != other.object);
  5043. swapVariables (object, other.object);
  5044. }
  5045. private:
  5046. ObjectType* object;
  5047. // (Required as an alternative to the overloaded & operator).
  5048. const ScopedPointer* getAddress() const throw() { return this; }
  5049. #if ! JUCE_MSVC // (MSVC can't deal with multiple copy constructors)
  5050. // This is private to stop people accidentally copying a const ScopedPointer (the compiler
  5051. // will let you do so by implicitly casting the source to its raw object pointer).
  5052. ScopedPointer (const ScopedPointer&);
  5053. #endif
  5054. };
  5055. /** Compares a ScopedPointer with another pointer.
  5056. This can be handy for checking whether this is a null pointer.
  5057. */
  5058. template <class ObjectType>
  5059. inline bool operator== (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5060. {
  5061. return static_cast <ObjectType*> (pointer1) == pointer2;
  5062. }
  5063. /** Compares a ScopedPointer with another pointer.
  5064. This can be handy for checking whether this is a null pointer.
  5065. */
  5066. template <class ObjectType>
  5067. inline bool operator!= (const ScopedPointer<ObjectType>& pointer1, const ObjectType* const pointer2) throw()
  5068. {
  5069. return static_cast <ObjectType*> (pointer1) != pointer2;
  5070. }
  5071. #endif // __JUCE_SCOPEDPOINTER_JUCEHEADER__
  5072. /*** End of inlined file: juce_ScopedPointer.h ***/
  5073. /** An array designed for holding objects.
  5074. This holds a list of pointers to objects, and will automatically
  5075. delete the objects when they are removed from the array, or when the
  5076. array is itself deleted.
  5077. Declare it in the form: OwnedArray<MyObjectClass>
  5078. ..and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
  5079. After adding objects, they are 'owned' by the array and will be deleted when
  5080. removed or replaced.
  5081. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  5082. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  5083. @see Array, ReferenceCountedArray, StringArray, CriticalSection
  5084. */
  5085. template <class ObjectClass,
  5086. class TypeOfCriticalSectionToUse = DummyCriticalSection>
  5087. class OwnedArray
  5088. {
  5089. public:
  5090. /** Creates an empty array. */
  5091. OwnedArray() throw()
  5092. : numUsed (0)
  5093. {
  5094. }
  5095. /** Deletes the array and also deletes any objects inside it.
  5096. To get rid of the array without deleting its objects, use its
  5097. clear (false) method before deleting it.
  5098. */
  5099. ~OwnedArray()
  5100. {
  5101. clear (true);
  5102. }
  5103. /** Clears the array, optionally deleting the objects inside it first. */
  5104. void clear (const bool deleteObjects = true)
  5105. {
  5106. const ScopedLockType lock (getLock());
  5107. if (deleteObjects)
  5108. {
  5109. while (numUsed > 0)
  5110. delete data.elements [--numUsed];
  5111. }
  5112. data.setAllocatedSize (0);
  5113. numUsed = 0;
  5114. }
  5115. /** Returns the number of items currently in the array.
  5116. @see operator[]
  5117. */
  5118. inline int size() const throw()
  5119. {
  5120. return numUsed;
  5121. }
  5122. /** Returns a pointer to the object at this index in the array.
  5123. If the index is out-of-range, this will return a null pointer, (and
  5124. it could be null anyway, because it's ok for the array to hold null
  5125. pointers as well as objects).
  5126. @see getUnchecked
  5127. */
  5128. inline ObjectClass* operator[] (const int index) const throw()
  5129. {
  5130. const ScopedLockType lock (getLock());
  5131. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  5132. : static_cast <ObjectClass*> (0);
  5133. }
  5134. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  5135. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  5136. it can be used when you're sure the index if always going to be legal.
  5137. */
  5138. inline ObjectClass* getUnchecked (const int index) const throw()
  5139. {
  5140. const ScopedLockType lock (getLock());
  5141. jassert (((unsigned int) index) < (unsigned int) numUsed);
  5142. return data.elements [index];
  5143. }
  5144. /** Returns a pointer to the first object in the array.
  5145. This will return a null pointer if the array's empty.
  5146. @see getLast
  5147. */
  5148. inline ObjectClass* getFirst() const throw()
  5149. {
  5150. const ScopedLockType lock (getLock());
  5151. return numUsed > 0 ? data.elements [0]
  5152. : static_cast <ObjectClass*> (0);
  5153. }
  5154. /** Returns a pointer to the last object in the array.
  5155. This will return a null pointer if the array's empty.
  5156. @see getFirst
  5157. */
  5158. inline ObjectClass* getLast() const throw()
  5159. {
  5160. const ScopedLockType lock (getLock());
  5161. return numUsed > 0 ? data.elements [numUsed - 1]
  5162. : static_cast <ObjectClass*> (0);
  5163. }
  5164. /** Returns a pointer to the actual array data.
  5165. This pointer will only be valid until the next time a non-const method
  5166. is called on the array.
  5167. */
  5168. inline ObjectClass** getRawDataPointer() throw()
  5169. {
  5170. return data.elements;
  5171. }
  5172. /** Finds the index of an object which might be in the array.
  5173. @param objectToLookFor the object to look for
  5174. @returns the index at which the object was found, or -1 if it's not found
  5175. */
  5176. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  5177. {
  5178. const ScopedLockType lock (getLock());
  5179. ObjectClass* const* e = data.elements.getData();
  5180. ObjectClass* const* const end = e + numUsed;
  5181. while (e != end)
  5182. {
  5183. if (objectToLookFor == *e)
  5184. return static_cast <int> (e - data.elements.getData());
  5185. ++e;
  5186. }
  5187. return -1;
  5188. }
  5189. /** Returns true if the array contains a specified object.
  5190. @param objectToLookFor the object to look for
  5191. @returns true if the object is in the array
  5192. */
  5193. bool contains (const ObjectClass* const objectToLookFor) const throw()
  5194. {
  5195. const ScopedLockType lock (getLock());
  5196. ObjectClass* const* e = data.elements.getData();
  5197. ObjectClass* const* const end = e + numUsed;
  5198. while (e != end)
  5199. {
  5200. if (objectToLookFor == *e)
  5201. return true;
  5202. ++e;
  5203. }
  5204. return false;
  5205. }
  5206. /** Appends a new object to the end of the array.
  5207. Note that the this object will be deleted by the OwnedArray when it
  5208. is removed, so be careful not to delete it somewhere else.
  5209. Also be careful not to add the same object to the array more than once,
  5210. as this will obviously cause deletion of dangling pointers.
  5211. @param newObject the new object to add to the array
  5212. @see set, insert, addIfNotAlreadyThere, addSorted
  5213. */
  5214. void add (const ObjectClass* const newObject) throw()
  5215. {
  5216. const ScopedLockType lock (getLock());
  5217. data.ensureAllocatedSize (numUsed + 1);
  5218. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5219. }
  5220. /** Inserts a new object into the array at the given index.
  5221. Note that the this object will be deleted by the OwnedArray when it
  5222. is removed, so be careful not to delete it somewhere else.
  5223. If the index is less than 0 or greater than the size of the array, the
  5224. element will be added to the end of the array.
  5225. Otherwise, it will be inserted into the array, moving all the later elements
  5226. along to make room.
  5227. Be careful not to add the same object to the array more than once,
  5228. as this will obviously cause deletion of dangling pointers.
  5229. @param indexToInsertAt the index at which the new element should be inserted
  5230. @param newObject the new object to add to the array
  5231. @see add, addSorted, addIfNotAlreadyThere, set
  5232. */
  5233. void insert (int indexToInsertAt,
  5234. const ObjectClass* const newObject) throw()
  5235. {
  5236. if (indexToInsertAt >= 0)
  5237. {
  5238. const ScopedLockType lock (getLock());
  5239. if (indexToInsertAt > numUsed)
  5240. indexToInsertAt = numUsed;
  5241. data.ensureAllocatedSize (numUsed + 1);
  5242. ObjectClass** const e = data.elements + indexToInsertAt;
  5243. const int numToMove = numUsed - indexToInsertAt;
  5244. if (numToMove > 0)
  5245. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  5246. *e = const_cast <ObjectClass*> (newObject);
  5247. ++numUsed;
  5248. }
  5249. else
  5250. {
  5251. add (newObject);
  5252. }
  5253. }
  5254. /** Appends a new object at the end of the array as long as the array doesn't
  5255. already contain it.
  5256. If the array already contains a matching object, nothing will be done.
  5257. @param newObject the new object to add to the array
  5258. */
  5259. void addIfNotAlreadyThere (const ObjectClass* const newObject) throw()
  5260. {
  5261. const ScopedLockType lock (getLock());
  5262. if (! contains (newObject))
  5263. add (newObject);
  5264. }
  5265. /** Replaces an object in the array with a different one.
  5266. If the index is less than zero, this method does nothing.
  5267. If the index is beyond the end of the array, the new object is added to the end of the array.
  5268. Be careful not to add the same object to the array more than once,
  5269. as this will obviously cause deletion of dangling pointers.
  5270. @param indexToChange the index whose value you want to change
  5271. @param newObject the new value to set for this index.
  5272. @param deleteOldElement whether to delete the object that's being replaced with the new one
  5273. @see add, insert, remove
  5274. */
  5275. void set (const int indexToChange,
  5276. const ObjectClass* const newObject,
  5277. const bool deleteOldElement = true)
  5278. {
  5279. if (indexToChange >= 0)
  5280. {
  5281. ScopedPointer <ObjectClass> toDelete;
  5282. const ScopedLockType lock (getLock());
  5283. if (indexToChange < numUsed)
  5284. {
  5285. if (deleteOldElement)
  5286. {
  5287. toDelete = data.elements [indexToChange];
  5288. if (toDelete == newObject)
  5289. toDelete = 0;
  5290. }
  5291. data.elements [indexToChange] = const_cast <ObjectClass*> (newObject);
  5292. }
  5293. else
  5294. {
  5295. data.ensureAllocatedSize (numUsed + 1);
  5296. data.elements [numUsed++] = const_cast <ObjectClass*> (newObject);
  5297. }
  5298. }
  5299. }
  5300. /** Adds elements from another array to the end of this array.
  5301. @param arrayToAddFrom the array from which to copy the elements
  5302. @param startIndex the first element of the other array to start copying from
  5303. @param numElementsToAdd how many elements to add from the other array. If this
  5304. value is negative or greater than the number of available elements,
  5305. all available elements will be copied.
  5306. @see add
  5307. */
  5308. template <class OtherArrayType>
  5309. void addArray (const OtherArrayType& arrayToAddFrom,
  5310. int startIndex = 0,
  5311. int numElementsToAdd = -1)
  5312. {
  5313. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5314. const ScopedLockType lock2 (getLock());
  5315. if (startIndex < 0)
  5316. {
  5317. jassertfalse;
  5318. startIndex = 0;
  5319. }
  5320. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5321. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5322. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5323. while (--numElementsToAdd >= 0)
  5324. {
  5325. data.elements [numUsed] = arrayToAddFrom.getUnchecked (startIndex++);
  5326. ++numUsed;
  5327. }
  5328. }
  5329. /** Adds copies of the elements in another array to the end of this array.
  5330. The other array must be either an OwnedArray of a compatible type of object, or an Array
  5331. containing pointers to the same kind of object. The objects involved must provide
  5332. a copy constructor, and this will be used to create new copies of each element, and
  5333. add them to this array.
  5334. @param arrayToAddFrom the array from which to copy the elements
  5335. @param startIndex the first element of the other array to start copying from
  5336. @param numElementsToAdd how many elements to add from the other array. If this
  5337. value is negative or greater than the number of available elements,
  5338. all available elements will be copied.
  5339. @see add
  5340. */
  5341. template <class OtherArrayType>
  5342. void addCopiesOf (const OtherArrayType& arrayToAddFrom,
  5343. int startIndex = 0,
  5344. int numElementsToAdd = -1)
  5345. {
  5346. const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
  5347. const ScopedLockType lock2 (getLock());
  5348. if (startIndex < 0)
  5349. {
  5350. jassertfalse;
  5351. startIndex = 0;
  5352. }
  5353. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  5354. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  5355. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  5356. while (--numElementsToAdd >= 0)
  5357. {
  5358. data.elements [numUsed] = new ObjectClass (*arrayToAddFrom.getUnchecked (startIndex++));
  5359. ++numUsed;
  5360. }
  5361. }
  5362. /** Inserts a new object into the array assuming that the array is sorted.
  5363. This will use a comparator to find the position at which the new object
  5364. should go. If the array isn't sorted, the behaviour of this
  5365. method will be unpredictable.
  5366. @param comparator the comparator to use to compare the elements - see the sort method
  5367. for details about this object's structure
  5368. @param newObject the new object to insert to the array
  5369. @see add, sort, indexOfSorted
  5370. */
  5371. template <class ElementComparator>
  5372. void addSorted (ElementComparator& comparator,
  5373. ObjectClass* const newObject) throw()
  5374. {
  5375. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5376. // avoids getting warning messages about the parameter being unused
  5377. const ScopedLockType lock (getLock());
  5378. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  5379. }
  5380. /** Finds the index of an object in the array, assuming that the array is sorted.
  5381. This will use a comparator to do a binary-chop to find the index of the given
  5382. element, if it exists. If the array isn't sorted, the behaviour of this
  5383. method will be unpredictable.
  5384. @param comparator the comparator to use to compare the elements - see the sort()
  5385. method for details about the form this object should take
  5386. @param objectToLookFor the object to search for
  5387. @returns the index of the element, or -1 if it's not found
  5388. @see addSorted, sort
  5389. */
  5390. template <class ElementComparator>
  5391. int indexOfSorted (ElementComparator& comparator,
  5392. const ObjectClass* const objectToLookFor) const throw()
  5393. {
  5394. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5395. // avoids getting warning messages about the parameter being unused
  5396. const ScopedLockType lock (getLock());
  5397. int start = 0;
  5398. int end = numUsed;
  5399. for (;;)
  5400. {
  5401. if (start >= end)
  5402. {
  5403. return -1;
  5404. }
  5405. else if (comparator.compareElements (objectToLookFor, data.elements [start]) == 0)
  5406. {
  5407. return start;
  5408. }
  5409. else
  5410. {
  5411. const int halfway = (start + end) >> 1;
  5412. if (halfway == start)
  5413. return -1;
  5414. else if (comparator.compareElements (objectToLookFor, data.elements [halfway]) >= 0)
  5415. start = halfway;
  5416. else
  5417. end = halfway;
  5418. }
  5419. }
  5420. }
  5421. /** Removes an object from the array.
  5422. This will remove the object at a given index (optionally also
  5423. deleting it) and move back all the subsequent objects to close the gap.
  5424. If the index passed in is out-of-range, nothing will happen.
  5425. @param indexToRemove the index of the element to remove
  5426. @param deleteObject whether to delete the object that is removed
  5427. @see removeObject, removeRange
  5428. */
  5429. void remove (const int indexToRemove,
  5430. const bool deleteObject = true)
  5431. {
  5432. ScopedPointer <ObjectClass> toDelete;
  5433. const ScopedLockType lock (getLock());
  5434. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5435. {
  5436. ObjectClass** const e = data.elements + indexToRemove;
  5437. if (deleteObject)
  5438. toDelete = *e;
  5439. --numUsed;
  5440. const int numToShift = numUsed - indexToRemove;
  5441. if (numToShift > 0)
  5442. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5443. if ((numUsed << 1) < data.numAllocated)
  5444. minimiseStorageOverheads();
  5445. }
  5446. }
  5447. /** Removes and returns an object from the array without deleting it.
  5448. This will remove the object at a given index and return it, moving back all
  5449. the subsequent objects to close the gap. If the index passed in is out-of-range,
  5450. nothing will happen.
  5451. @param indexToRemove the index of the element to remove
  5452. @see remove, removeObject, removeRange
  5453. */
  5454. ObjectClass* removeAndReturn (const int indexToRemove)
  5455. {
  5456. ObjectClass* removedItem = 0;
  5457. const ScopedLockType lock (getLock());
  5458. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  5459. {
  5460. ObjectClass** const e = data.elements + indexToRemove;
  5461. removedItem = *e;
  5462. --numUsed;
  5463. const int numToShift = numUsed - indexToRemove;
  5464. if (numToShift > 0)
  5465. memmove (e, e + 1, numToShift * sizeof (ObjectClass*));
  5466. if ((numUsed << 1) < data.numAllocated)
  5467. minimiseStorageOverheads();
  5468. }
  5469. return removedItem;
  5470. }
  5471. /** Removes a specified object from the array.
  5472. If the item isn't found, no action is taken.
  5473. @param objectToRemove the object to try to remove
  5474. @param deleteObject whether to delete the object (if it's found)
  5475. @see remove, removeRange
  5476. */
  5477. void removeObject (const ObjectClass* const objectToRemove,
  5478. const bool deleteObject = true)
  5479. {
  5480. const ScopedLockType lock (getLock());
  5481. ObjectClass** e = data.elements.getData();
  5482. for (int i = numUsed; --i >= 0;)
  5483. {
  5484. if (objectToRemove == *e)
  5485. {
  5486. remove (static_cast <int> (e - data.elements.getData()), deleteObject);
  5487. break;
  5488. }
  5489. ++e;
  5490. }
  5491. }
  5492. /** Removes a range of objects from the array.
  5493. This will remove a set of objects, starting from the given index,
  5494. and move any subsequent elements down to close the gap.
  5495. If the range extends beyond the bounds of the array, it will
  5496. be safely clipped to the size of the array.
  5497. @param startIndex the index of the first object to remove
  5498. @param numberToRemove how many objects should be removed
  5499. @param deleteObjects whether to delete the objects that get removed
  5500. @see remove, removeObject
  5501. */
  5502. void removeRange (int startIndex,
  5503. const int numberToRemove,
  5504. const bool deleteObjects = true)
  5505. {
  5506. const ScopedLockType lock (getLock());
  5507. const int endIndex = jlimit (0, numUsed, startIndex + numberToRemove);
  5508. startIndex = jlimit (0, numUsed, startIndex);
  5509. if (endIndex > startIndex)
  5510. {
  5511. if (deleteObjects)
  5512. {
  5513. for (int i = startIndex; i < endIndex; ++i)
  5514. {
  5515. delete data.elements [i];
  5516. data.elements [i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  5517. }
  5518. }
  5519. const int rangeSize = endIndex - startIndex;
  5520. ObjectClass** e = data.elements + startIndex;
  5521. int numToShift = numUsed - endIndex;
  5522. numUsed -= rangeSize;
  5523. while (--numToShift >= 0)
  5524. {
  5525. *e = e [rangeSize];
  5526. ++e;
  5527. }
  5528. if ((numUsed << 1) < data.numAllocated)
  5529. minimiseStorageOverheads();
  5530. }
  5531. }
  5532. /** Removes the last n objects from the array.
  5533. @param howManyToRemove how many objects to remove from the end of the array
  5534. @param deleteObjects whether to also delete the objects that are removed
  5535. @see remove, removeObject, removeRange
  5536. */
  5537. void removeLast (int howManyToRemove = 1,
  5538. const bool deleteObjects = true)
  5539. {
  5540. const ScopedLockType lock (getLock());
  5541. if (howManyToRemove >= numUsed)
  5542. clear (deleteObjects);
  5543. else
  5544. removeRange (numUsed - howManyToRemove, howManyToRemove, deleteObjects);
  5545. }
  5546. /** Swaps a pair of objects in the array.
  5547. If either of the indexes passed in is out-of-range, nothing will happen,
  5548. otherwise the two objects at these positions will be exchanged.
  5549. */
  5550. void swap (const int index1,
  5551. const int index2) throw()
  5552. {
  5553. const ScopedLockType lock (getLock());
  5554. if (((unsigned int) index1) < (unsigned int) numUsed
  5555. && ((unsigned int) index2) < (unsigned int) numUsed)
  5556. {
  5557. swapVariables (data.elements [index1],
  5558. data.elements [index2]);
  5559. }
  5560. }
  5561. /** Moves one of the objects to a different position.
  5562. This will move the object to a specified index, shuffling along
  5563. any intervening elements as required.
  5564. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5565. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5566. @param currentIndex the index of the object to be moved. If this isn't a
  5567. valid index, then nothing will be done
  5568. @param newIndex the index at which you'd like this object to end up. If this
  5569. is less than zero, it will be moved to the end of the array
  5570. */
  5571. void move (const int currentIndex,
  5572. int newIndex) throw()
  5573. {
  5574. if (currentIndex != newIndex)
  5575. {
  5576. const ScopedLockType lock (getLock());
  5577. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  5578. {
  5579. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  5580. newIndex = numUsed - 1;
  5581. ObjectClass* const value = data.elements [currentIndex];
  5582. if (newIndex > currentIndex)
  5583. {
  5584. memmove (data.elements + currentIndex,
  5585. data.elements + currentIndex + 1,
  5586. (newIndex - currentIndex) * sizeof (ObjectClass*));
  5587. }
  5588. else
  5589. {
  5590. memmove (data.elements + newIndex + 1,
  5591. data.elements + newIndex,
  5592. (currentIndex - newIndex) * sizeof (ObjectClass*));
  5593. }
  5594. data.elements [newIndex] = value;
  5595. }
  5596. }
  5597. }
  5598. /** This swaps the contents of this array with those of another array.
  5599. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  5600. because it just swaps their internal pointers.
  5601. */
  5602. void swapWithArray (OwnedArray& otherArray) throw()
  5603. {
  5604. const ScopedLockType lock1 (getLock());
  5605. const ScopedLockType lock2 (otherArray.getLock());
  5606. data.swapWith (otherArray.data);
  5607. swapVariables (numUsed, otherArray.numUsed);
  5608. }
  5609. /** Reduces the amount of storage being used by the array.
  5610. Arrays typically allocate slightly more storage than they need, and after
  5611. removing elements, they may have quite a lot of unused space allocated.
  5612. This method will reduce the amount of allocated storage to a minimum.
  5613. */
  5614. void minimiseStorageOverheads() throw()
  5615. {
  5616. const ScopedLockType lock (getLock());
  5617. data.shrinkToNoMoreThan (numUsed);
  5618. }
  5619. /** Increases the array's internal storage to hold a minimum number of elements.
  5620. Calling this before adding a large known number of elements means that
  5621. the array won't have to keep dynamically resizing itself as the elements
  5622. are added, and it'll therefore be more efficient.
  5623. */
  5624. void ensureStorageAllocated (const int minNumElements) throw()
  5625. {
  5626. const ScopedLockType lock (getLock());
  5627. data.ensureAllocatedSize (minNumElements);
  5628. }
  5629. /** Sorts the elements in the array.
  5630. This will use a comparator object to sort the elements into order. The object
  5631. passed must have a method of the form:
  5632. @code
  5633. int compareElements (ElementType first, ElementType second);
  5634. @endcode
  5635. ..and this method must return:
  5636. - a value of < 0 if the first comes before the second
  5637. - a value of 0 if the two objects are equivalent
  5638. - a value of > 0 if the second comes before the first
  5639. To improve performance, the compareElements() method can be declared as static or const.
  5640. @param comparator the comparator to use for comparing elements.
  5641. @param retainOrderOfEquivalentItems if this is true, then items
  5642. which the comparator says are equivalent will be
  5643. kept in the order in which they currently appear
  5644. in the array. This is slower to perform, but may
  5645. be important in some cases. If it's false, a faster
  5646. algorithm is used, but equivalent elements may be
  5647. rearranged.
  5648. @see sortArray, indexOfSorted
  5649. */
  5650. template <class ElementComparator>
  5651. void sort (ElementComparator& comparator,
  5652. const bool retainOrderOfEquivalentItems = false) const throw()
  5653. {
  5654. (void) comparator; // if you pass in an object with a static compareElements() method, this
  5655. // avoids getting warning messages about the parameter being unused
  5656. const ScopedLockType lock (getLock());
  5657. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  5658. }
  5659. /** Returns the CriticalSection that locks this array.
  5660. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  5661. an object of ScopedLockType as an RAII lock for it.
  5662. */
  5663. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  5664. /** Returns the type of scoped lock to use for locking this array */
  5665. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  5666. juce_UseDebuggingNewOperator
  5667. private:
  5668. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  5669. int numUsed;
  5670. // disallow copy constructor and assignment
  5671. OwnedArray (const OwnedArray&);
  5672. OwnedArray& operator= (const OwnedArray&);
  5673. };
  5674. #endif // __JUCE_OWNEDARRAY_JUCEHEADER__
  5675. /*** End of inlined file: juce_OwnedArray.h ***/
  5676. #endif
  5677. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5678. /*** Start of inlined file: juce_PropertySet.h ***/
  5679. #ifndef __JUCE_PROPERTYSET_JUCEHEADER__
  5680. #define __JUCE_PROPERTYSET_JUCEHEADER__
  5681. /*** Start of inlined file: juce_StringPairArray.h ***/
  5682. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5683. #define __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5684. /*** Start of inlined file: juce_StringArray.h ***/
  5685. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  5686. #define __JUCE_STRINGARRAY_JUCEHEADER__
  5687. /**
  5688. A special array for holding a list of strings.
  5689. @see String, StringPairArray
  5690. */
  5691. class JUCE_API StringArray
  5692. {
  5693. public:
  5694. /** Creates an empty string array */
  5695. StringArray() throw();
  5696. /** Creates a copy of another string array */
  5697. StringArray (const StringArray& other);
  5698. /** Creates an array containing a single string. */
  5699. explicit StringArray (const String& firstValue);
  5700. /** Creates a copy of an array of string literals.
  5701. @param strings an array of strings to add. Null pointers in the array will be
  5702. treated as empty strings
  5703. @param numberOfStrings how many items there are in the array
  5704. */
  5705. StringArray (const juce_wchar* const* strings, int numberOfStrings);
  5706. /** Creates a copy of an array of string literals.
  5707. @param strings an array of strings to add. Null pointers in the array will be
  5708. treated as empty strings
  5709. @param numberOfStrings how many items there are in the array
  5710. */
  5711. StringArray (const char* const* strings, int numberOfStrings);
  5712. /** Creates a copy of a null-terminated array of string literals.
  5713. Each item from the array passed-in is added, until it encounters a null pointer,
  5714. at which point it stops.
  5715. */
  5716. explicit StringArray (const juce_wchar* const* strings);
  5717. /** Creates a copy of a null-terminated array of string literals.
  5718. Each item from the array passed-in is added, until it encounters a null pointer,
  5719. at which point it stops.
  5720. */
  5721. explicit StringArray (const char* const* strings);
  5722. /** Destructor. */
  5723. ~StringArray();
  5724. /** Copies the contents of another string array into this one */
  5725. StringArray& operator= (const StringArray& other);
  5726. /** Compares two arrays.
  5727. Comparisons are case-sensitive.
  5728. @returns true only if the other array contains exactly the same strings in the same order
  5729. */
  5730. bool operator== (const StringArray& other) const throw();
  5731. /** Compares two arrays.
  5732. Comparisons are case-sensitive.
  5733. @returns false if the other array contains exactly the same strings in the same order
  5734. */
  5735. bool operator!= (const StringArray& other) const throw();
  5736. /** Returns the number of strings in the array */
  5737. inline int size() const throw() { return strings.size(); };
  5738. /** Returns one of the strings from the array.
  5739. If the index is out-of-range, an empty string is returned.
  5740. Obviously the reference returned shouldn't be stored for later use, as the
  5741. string it refers to may disappear when the array changes.
  5742. */
  5743. const String& operator[] (int index) const throw();
  5744. /** Returns a reference to one of the strings in the array.
  5745. This lets you modify a string in-place in the array, but you must be sure that
  5746. the index is in-range.
  5747. */
  5748. String& getReference (int index) throw();
  5749. /** Searches for a string in the array.
  5750. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5751. @returns true if the string is found inside the array
  5752. */
  5753. bool contains (const String& stringToLookFor,
  5754. bool ignoreCase = false) const;
  5755. /** Searches for a string in the array.
  5756. The comparison will be case-insensitive if the ignoreCase parameter is true.
  5757. @param stringToLookFor the string to try to find
  5758. @param ignoreCase whether the comparison should be case-insensitive
  5759. @param startIndex the first index to start searching from
  5760. @returns the index of the first occurrence of the string in this array,
  5761. or -1 if it isn't found.
  5762. */
  5763. int indexOf (const String& stringToLookFor,
  5764. bool ignoreCase = false,
  5765. int startIndex = 0) const;
  5766. /** Appends a string at the end of the array. */
  5767. void add (const String& stringToAdd);
  5768. /** Inserts a string into the array.
  5769. This will insert a string into the array at the given index, moving
  5770. up the other elements to make room for it.
  5771. If the index is less than zero or greater than the size of the array,
  5772. the new string will be added to the end of the array.
  5773. */
  5774. void insert (int index, const String& stringToAdd);
  5775. /** Adds a string to the array as long as it's not already in there.
  5776. The search can optionally be case-insensitive.
  5777. */
  5778. void addIfNotAlreadyThere (const String& stringToAdd, bool ignoreCase = false);
  5779. /** Replaces one of the strings in the array with another one.
  5780. If the index is higher than the array's size, the new string will be
  5781. added to the end of the array; if it's less than zero nothing happens.
  5782. */
  5783. void set (int index, const String& newString);
  5784. /** Appends some strings from another array to the end of this one.
  5785. @param other the array to add
  5786. @param startIndex the first element of the other array to add
  5787. @param numElementsToAdd the maximum number of elements to add (if this is
  5788. less than zero, they are all added)
  5789. */
  5790. void addArray (const StringArray& other,
  5791. int startIndex = 0,
  5792. int numElementsToAdd = -1);
  5793. /** Breaks up a string into tokens and adds them to this array.
  5794. This will tokenise the given string using whitespace characters as the
  5795. token delimiters, and will add these tokens to the end of the array.
  5796. @returns the number of tokens added
  5797. */
  5798. int addTokens (const String& stringToTokenise,
  5799. bool preserveQuotedStrings);
  5800. /** Breaks up a string into tokens and adds them to this array.
  5801. This will tokenise the given string (using the string passed in to define the
  5802. token delimiters), and will add these tokens to the end of the array.
  5803. @param stringToTokenise the string to tokenise
  5804. @param breakCharacters a string of characters, any of which will be considered
  5805. to be a token delimiter.
  5806. @param quoteCharacters if this string isn't empty, it defines a set of characters
  5807. which are treated as quotes. Any text occurring
  5808. between quotes is not broken up into tokens.
  5809. @returns the number of tokens added
  5810. */
  5811. int addTokens (const String& stringToTokenise,
  5812. const String& breakCharacters,
  5813. const String& quoteCharacters);
  5814. /** Breaks up a string into lines and adds them to this array.
  5815. This breaks a string down into lines separated by \\n or \\r\\n, and adds each line
  5816. to the array. Line-break characters are omitted from the strings that are added to
  5817. the array.
  5818. */
  5819. int addLines (const String& stringToBreakUp);
  5820. /** Removes all elements from the array. */
  5821. void clear();
  5822. /** Removes a string from the array.
  5823. If the index is out-of-range, no action will be taken.
  5824. */
  5825. void remove (int index);
  5826. /** Finds a string in the array and removes it.
  5827. This will remove the first occurrence of the given string from the array. The
  5828. comparison may be case-insensitive depending on the ignoreCase parameter.
  5829. */
  5830. void removeString (const String& stringToRemove,
  5831. bool ignoreCase = false);
  5832. /** Removes a range of elements from the array.
  5833. This will remove a set of elements, starting from the given index,
  5834. and move subsequent elements down to close the gap.
  5835. If the range extends beyond the bounds of the array, it will
  5836. be safely clipped to the size of the array.
  5837. @param startIndex the index of the first element to remove
  5838. @param numberToRemove how many elements should be removed
  5839. */
  5840. void removeRange (int startIndex, int numberToRemove);
  5841. /** Removes any duplicated elements from the array.
  5842. If any string appears in the array more than once, only the first occurrence of
  5843. it will be retained.
  5844. @param ignoreCase whether to use a case-insensitive comparison
  5845. */
  5846. void removeDuplicates (bool ignoreCase);
  5847. /** Removes empty strings from the array.
  5848. @param removeWhitespaceStrings if true, strings that only contain whitespace
  5849. characters will also be removed
  5850. */
  5851. void removeEmptyStrings (bool removeWhitespaceStrings = true);
  5852. /** Moves one of the strings to a different position.
  5853. This will move the string to a specified index, shuffling along
  5854. any intervening elements as required.
  5855. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  5856. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  5857. @param currentIndex the index of the value to be moved. If this isn't a
  5858. valid index, then nothing will be done
  5859. @param newIndex the index at which you'd like this value to end up. If this
  5860. is less than zero, the value will be moved to the end
  5861. of the array
  5862. */
  5863. void move (int currentIndex, int newIndex) throw();
  5864. /** Deletes any whitespace characters from the starts and ends of all the strings. */
  5865. void trim();
  5866. /** Adds numbers to the strings in the array, to make each string unique.
  5867. This will add numbers to the ends of groups of similar strings.
  5868. e.g. if there are two "moose" strings, they will become "moose (1)" and "moose (2)"
  5869. @param ignoreCaseWhenComparing whether the comparison used is case-insensitive
  5870. @param appendNumberToFirstInstance whether the first of a group of similar strings
  5871. also has a number appended to it.
  5872. @param preNumberString when adding a number, this string is added before the number.
  5873. If you pass 0, a default string will be used, which adds
  5874. brackets around the number.
  5875. @param postNumberString this string is appended after any numbers that are added.
  5876. If you pass 0, a default string will be used, which adds
  5877. brackets around the number.
  5878. */
  5879. void appendNumbersToDuplicates (bool ignoreCaseWhenComparing,
  5880. bool appendNumberToFirstInstance,
  5881. const juce_wchar* preNumberString = 0,
  5882. const juce_wchar* postNumberString = 0);
  5883. /** Joins the strings in the array together into one string.
  5884. This will join a range of elements from the array into a string, separating
  5885. them with a given string.
  5886. e.g. joinIntoString (",") will turn an array of "a" "b" and "c" into "a,b,c".
  5887. @param separatorString the string to insert between all the strings
  5888. @param startIndex the first element to join
  5889. @param numberOfElements how many elements to join together. If this is less
  5890. than zero, all available elements will be used.
  5891. */
  5892. const String joinIntoString (const String& separatorString,
  5893. int startIndex = 0,
  5894. int numberOfElements = -1) const;
  5895. /** Sorts the array into alphabetical order.
  5896. @param ignoreCase if true, the comparisons used will be case-sensitive.
  5897. */
  5898. void sort (bool ignoreCase);
  5899. /** Reduces the amount of storage being used by the array.
  5900. Arrays typically allocate slightly more storage than they need, and after
  5901. removing elements, they may have quite a lot of unused space allocated.
  5902. This method will reduce the amount of allocated storage to a minimum.
  5903. */
  5904. void minimiseStorageOverheads();
  5905. juce_UseDebuggingNewOperator
  5906. private:
  5907. Array <String> strings;
  5908. };
  5909. #endif // __JUCE_STRINGARRAY_JUCEHEADER__
  5910. /*** End of inlined file: juce_StringArray.h ***/
  5911. /**
  5912. A container for holding a set of strings which are keyed by another string.
  5913. @see StringArray
  5914. */
  5915. class JUCE_API StringPairArray
  5916. {
  5917. public:
  5918. /** Creates an empty array */
  5919. StringPairArray (bool ignoreCaseWhenComparingKeys = true);
  5920. /** Creates a copy of another array */
  5921. StringPairArray (const StringPairArray& other);
  5922. /** Destructor. */
  5923. ~StringPairArray();
  5924. /** Copies the contents of another string array into this one */
  5925. StringPairArray& operator= (const StringPairArray& other);
  5926. /** Compares two arrays.
  5927. Comparisons are case-sensitive.
  5928. @returns true only if the other array contains exactly the same strings with the same keys
  5929. */
  5930. bool operator== (const StringPairArray& other) const;
  5931. /** Compares two arrays.
  5932. Comparisons are case-sensitive.
  5933. @returns false if the other array contains exactly the same strings with the same keys
  5934. */
  5935. bool operator!= (const StringPairArray& other) const;
  5936. /** Finds the value corresponding to a key string.
  5937. If no such key is found, this will just return an empty string. To check whether
  5938. a given key actually exists (because it might actually be paired with an empty string), use
  5939. the getAllKeys() method to obtain a list.
  5940. Obviously the reference returned shouldn't be stored for later use, as the
  5941. string it refers to may disappear when the array changes.
  5942. @see getValue
  5943. */
  5944. const String& operator[] (const String& key) const;
  5945. /** Finds the value corresponding to a key string.
  5946. If no such key is found, this will just return the value provided as a default.
  5947. @see operator[]
  5948. */
  5949. const String getValue (const String& key, const String& defaultReturnValue) const;
  5950. /** Returns a list of all keys in the array. */
  5951. const StringArray& getAllKeys() const throw() { return keys; }
  5952. /** Returns a list of all values in the array. */
  5953. const StringArray& getAllValues() const throw() { return values; }
  5954. /** Returns the number of strings in the array */
  5955. inline int size() const throw() { return keys.size(); };
  5956. /** Adds or amends a key/value pair.
  5957. If a value already exists with this key, its value will be overwritten,
  5958. otherwise the key/value pair will be added to the array.
  5959. */
  5960. void set (const String& key, const String& value);
  5961. /** Adds the items from another array to this one.
  5962. This is equivalent to using set() to add each of the pairs from the other array.
  5963. */
  5964. void addArray (const StringPairArray& other);
  5965. /** Removes all elements from the array. */
  5966. void clear();
  5967. /** Removes a string from the array based on its key.
  5968. If the key isn't found, nothing will happen.
  5969. */
  5970. void remove (const String& key);
  5971. /** Removes a string from the array based on its index.
  5972. If the index is out-of-range, no action will be taken.
  5973. */
  5974. void remove (int index);
  5975. /** Indicates whether to use a case-insensitive search when looking up a key string.
  5976. */
  5977. void setIgnoresCase (bool shouldIgnoreCase);
  5978. /** Returns a descriptive string containing the items.
  5979. This is handy for dumping the contents of an array.
  5980. */
  5981. const String getDescription() const;
  5982. /** Reduces the amount of storage being used by the array.
  5983. Arrays typically allocate slightly more storage than they need, and after
  5984. removing elements, they may have quite a lot of unused space allocated.
  5985. This method will reduce the amount of allocated storage to a minimum.
  5986. */
  5987. void minimiseStorageOverheads();
  5988. juce_UseDebuggingNewOperator
  5989. private:
  5990. StringArray keys, values;
  5991. bool ignoreCase;
  5992. };
  5993. #endif // __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  5994. /*** End of inlined file: juce_StringPairArray.h ***/
  5995. /*** Start of inlined file: juce_XmlElement.h ***/
  5996. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  5997. #define __JUCE_XMLELEMENT_JUCEHEADER__
  5998. /*** Start of inlined file: juce_File.h ***/
  5999. #ifndef __JUCE_FILE_JUCEHEADER__
  6000. #define __JUCE_FILE_JUCEHEADER__
  6001. /*** Start of inlined file: juce_Time.h ***/
  6002. #ifndef __JUCE_TIME_JUCEHEADER__
  6003. #define __JUCE_TIME_JUCEHEADER__
  6004. /*** Start of inlined file: juce_RelativeTime.h ***/
  6005. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  6006. #define __JUCE_RELATIVETIME_JUCEHEADER__
  6007. /** A relative measure of time.
  6008. The time is stored as a number of seconds, at double-precision floating
  6009. point accuracy, and may be positive or negative.
  6010. If you need an absolute time, (i.e. a date + time), see the Time class.
  6011. */
  6012. class JUCE_API RelativeTime
  6013. {
  6014. public:
  6015. /** Creates a RelativeTime.
  6016. @param seconds the number of seconds, which may be +ve or -ve.
  6017. @see milliseconds, minutes, hours, days, weeks
  6018. */
  6019. explicit RelativeTime (double seconds = 0.0) throw();
  6020. /** Copies another relative time. */
  6021. RelativeTime (const RelativeTime& other) throw();
  6022. /** Copies another relative time. */
  6023. RelativeTime& operator= (const RelativeTime& other) throw();
  6024. /** Destructor. */
  6025. ~RelativeTime() throw();
  6026. /** Creates a new RelativeTime object representing a number of milliseconds.
  6027. @see minutes, hours, days, weeks
  6028. */
  6029. static const RelativeTime milliseconds (int milliseconds) throw();
  6030. /** Creates a new RelativeTime object representing a number of milliseconds.
  6031. @see minutes, hours, days, weeks
  6032. */
  6033. static const RelativeTime milliseconds (int64 milliseconds) throw();
  6034. /** Creates a new RelativeTime object representing a number of minutes.
  6035. @see milliseconds, hours, days, weeks
  6036. */
  6037. static const RelativeTime minutes (double numberOfMinutes) throw();
  6038. /** Creates a new RelativeTime object representing a number of hours.
  6039. @see milliseconds, minutes, days, weeks
  6040. */
  6041. static const RelativeTime hours (double numberOfHours) throw();
  6042. /** Creates a new RelativeTime object representing a number of days.
  6043. @see milliseconds, minutes, hours, weeks
  6044. */
  6045. static const RelativeTime days (double numberOfDays) throw();
  6046. /** Creates a new RelativeTime object representing a number of weeks.
  6047. @see milliseconds, minutes, hours, days
  6048. */
  6049. static const RelativeTime weeks (double numberOfWeeks) throw();
  6050. /** Returns the number of milliseconds this time represents.
  6051. @see milliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6052. */
  6053. int64 inMilliseconds() const throw();
  6054. /** Returns the number of seconds this time represents.
  6055. @see inMilliseconds, inMinutes, inHours, inDays, inWeeks
  6056. */
  6057. double inSeconds() const throw() { return seconds; }
  6058. /** Returns the number of minutes this time represents.
  6059. @see inMilliseconds, inSeconds, inHours, inDays, inWeeks
  6060. */
  6061. double inMinutes() const throw();
  6062. /** Returns the number of hours this time represents.
  6063. @see inMilliseconds, inSeconds, inMinutes, inDays, inWeeks
  6064. */
  6065. double inHours() const throw();
  6066. /** Returns the number of days this time represents.
  6067. @see inMilliseconds, inSeconds, inMinutes, inHours, inWeeks
  6068. */
  6069. double inDays() const throw();
  6070. /** Returns the number of weeks this time represents.
  6071. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays
  6072. */
  6073. double inWeeks() const throw();
  6074. /** Returns a readable textual description of the time.
  6075. The exact format of the string returned will depend on
  6076. the magnitude of the time - e.g.
  6077. "1 min 4 secs", "1 hr 45 mins", "2 weeks 5 days", "140 ms"
  6078. so that only the two most significant units are printed.
  6079. The returnValueForZeroTime value is the result that is returned if the
  6080. length is zero. Depending on your application you might want to use this
  6081. to return something more relevant like "empty" or "0 secs", etc.
  6082. @see inMilliseconds, inSeconds, inMinutes, inHours, inDays, inWeeks
  6083. */
  6084. const String getDescription (const String& returnValueForZeroTime = "0") const throw();
  6085. /** Compares two RelativeTimes. */
  6086. bool operator== (const RelativeTime& other) const throw();
  6087. /** Compares two RelativeTimes. */
  6088. bool operator!= (const RelativeTime& other) const throw();
  6089. /** Compares two RelativeTimes. */
  6090. bool operator> (const RelativeTime& other) const throw();
  6091. /** Compares two RelativeTimes. */
  6092. bool operator< (const RelativeTime& other) const throw();
  6093. /** Compares two RelativeTimes. */
  6094. bool operator>= (const RelativeTime& other) const throw();
  6095. /** Compares two RelativeTimes. */
  6096. bool operator<= (const RelativeTime& other) const throw();
  6097. /** Adds another RelativeTime to this one and returns the result. */
  6098. const RelativeTime operator+ (const RelativeTime& timeToAdd) const throw();
  6099. /** Subtracts another RelativeTime from this one and returns the result. */
  6100. const RelativeTime operator- (const RelativeTime& timeToSubtract) const throw();
  6101. /** Adds a number of seconds to this RelativeTime and returns the result. */
  6102. const RelativeTime operator+ (double secondsToAdd) const throw();
  6103. /** Subtracts a number of seconds from this RelativeTime and returns the result. */
  6104. const RelativeTime operator- (double secondsToSubtract) const throw();
  6105. /** Adds another RelativeTime to this one. */
  6106. const RelativeTime& operator+= (const RelativeTime& timeToAdd) throw();
  6107. /** Subtracts another RelativeTime from this one. */
  6108. const RelativeTime& operator-= (const RelativeTime& timeToSubtract) throw();
  6109. /** Adds a number of seconds to this time. */
  6110. const RelativeTime& operator+= (double secondsToAdd) throw();
  6111. /** Subtracts a number of seconds from this time. */
  6112. const RelativeTime& operator-= (double secondsToSubtract) throw();
  6113. juce_UseDebuggingNewOperator
  6114. private:
  6115. double seconds;
  6116. };
  6117. #endif // __JUCE_RELATIVETIME_JUCEHEADER__
  6118. /*** End of inlined file: juce_RelativeTime.h ***/
  6119. /**
  6120. Holds an absolute date and time.
  6121. Internally, the time is stored at millisecond precision.
  6122. @see RelativeTime
  6123. */
  6124. class JUCE_API Time
  6125. {
  6126. public:
  6127. /** Creates a Time object.
  6128. This default constructor creates a time of 1st January 1970, (which is
  6129. represented internally as 0ms).
  6130. To create a time object representing the current time, use getCurrentTime().
  6131. @see getCurrentTime
  6132. */
  6133. Time() throw();
  6134. /** Creates a copy of another Time object. */
  6135. Time (const Time& other) throw();
  6136. /** Creates a time based on a number of milliseconds.
  6137. The internal millisecond count is set to 0 (1st January 1970). To create a
  6138. time object set to the current time, use getCurrentTime().
  6139. @param millisecondsSinceEpoch the number of milliseconds since the unix
  6140. 'epoch' (midnight Jan 1st 1970).
  6141. @see getCurrentTime, currentTimeMillis
  6142. */
  6143. Time (int64 millisecondsSinceEpoch) throw();
  6144. /** Creates a time from a set of date components.
  6145. The timezone is assumed to be whatever the system is using as its locale.
  6146. @param year the year, in 4-digit format, e.g. 2004
  6147. @param month the month, in the range 0 to 11
  6148. @param day the day of the month, in the range 1 to 31
  6149. @param hours hours in 24-hour clock format, 0 to 23
  6150. @param minutes minutes 0 to 59
  6151. @param seconds seconds 0 to 59
  6152. @param milliseconds milliseconds 0 to 999
  6153. @param useLocalTime if true, encode using the current machine's local time; if
  6154. false, it will always work in GMT.
  6155. */
  6156. Time (int year,
  6157. int month,
  6158. int day,
  6159. int hours,
  6160. int minutes,
  6161. int seconds = 0,
  6162. int milliseconds = 0,
  6163. bool useLocalTime = true) throw();
  6164. /** Destructor. */
  6165. ~Time() throw();
  6166. /** Copies this time from another one. */
  6167. Time& operator= (const Time& other) throw();
  6168. /** Returns a Time object that is set to the current system time.
  6169. @see currentTimeMillis
  6170. */
  6171. static const Time JUCE_CALLTYPE getCurrentTime() throw();
  6172. /** Returns the time as a number of milliseconds.
  6173. @returns the number of milliseconds this Time object represents, since
  6174. midnight jan 1st 1970.
  6175. @see getMilliseconds
  6176. */
  6177. int64 toMilliseconds() const throw() { return millisSinceEpoch; }
  6178. /** Returns the year.
  6179. A 4-digit format is used, e.g. 2004.
  6180. */
  6181. int getYear() const throw();
  6182. /** Returns the number of the month.
  6183. The value returned is in the range 0 to 11.
  6184. @see getMonthName
  6185. */
  6186. int getMonth() const throw();
  6187. /** Returns the name of the month.
  6188. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6189. it'll return the long form, e.g. "January"
  6190. @see getMonth
  6191. */
  6192. const String getMonthName (bool threeLetterVersion) const throw();
  6193. /** Returns the day of the month.
  6194. The value returned is in the range 1 to 31.
  6195. */
  6196. int getDayOfMonth() const throw();
  6197. /** Returns the number of the day of the week.
  6198. The value returned is in the range 0 to 6 (0 = sunday, 1 = monday, etc).
  6199. */
  6200. int getDayOfWeek() const throw();
  6201. /** Returns the name of the weekday.
  6202. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6203. false, it'll return the full version, e.g. "Tuesday".
  6204. */
  6205. const String getWeekdayName (bool threeLetterVersion) const throw();
  6206. /** Returns the number of hours since midnight.
  6207. This is in 24-hour clock format, in the range 0 to 23.
  6208. @see getHoursInAmPmFormat, isAfternoon
  6209. */
  6210. int getHours() const throw();
  6211. /** Returns true if the time is in the afternoon.
  6212. So it returns true for "PM", false for "AM".
  6213. @see getHoursInAmPmFormat, getHours
  6214. */
  6215. bool isAfternoon() const throw();
  6216. /** Returns the hours in 12-hour clock format.
  6217. This will return a value 1 to 12 - use isAfternoon() to find out
  6218. whether this is in the afternoon or morning.
  6219. @see getHours, isAfternoon
  6220. */
  6221. int getHoursInAmPmFormat() const throw();
  6222. /** Returns the number of minutes, 0 to 59. */
  6223. int getMinutes() const throw();
  6224. /** Returns the number of seconds, 0 to 59. */
  6225. int getSeconds() const throw();
  6226. /** Returns the number of milliseconds, 0 to 999.
  6227. Unlike toMilliseconds(), this just returns the position within the
  6228. current second rather than the total number since the epoch.
  6229. @see toMilliseconds
  6230. */
  6231. int getMilliseconds() const throw();
  6232. /** Returns true if the local timezone uses a daylight saving correction. */
  6233. bool isDaylightSavingTime() const throw();
  6234. /** Returns a 3-character string to indicate the local timezone. */
  6235. const String getTimeZone() const throw();
  6236. /** Quick way of getting a string version of a date and time.
  6237. For a more powerful way of formatting the date and time, see the formatted() method.
  6238. @param includeDate whether to include the date in the string
  6239. @param includeTime whether to include the time in the string
  6240. @param includeSeconds if the time is being included, this provides an option not to include
  6241. the seconds in it
  6242. @param use24HourClock if the time is being included, sets whether to use am/pm or 24
  6243. hour notation.
  6244. @see formatted
  6245. */
  6246. const String toString (bool includeDate,
  6247. bool includeTime,
  6248. bool includeSeconds = true,
  6249. bool use24HourClock = false) const throw();
  6250. /** Converts this date/time to a string with a user-defined format.
  6251. This uses the C strftime() function to format this time as a string. To save you
  6252. looking it up, these are the escape codes that strftime uses (other codes might
  6253. work on some platforms and not others, but these are the common ones):
  6254. %a is replaced by the locale's abbreviated weekday name.
  6255. %A is replaced by the locale's full weekday name.
  6256. %b is replaced by the locale's abbreviated month name.
  6257. %B is replaced by the locale's full month name.
  6258. %c is replaced by the locale's appropriate date and time representation.
  6259. %d is replaced by the day of the month as a decimal number [01,31].
  6260. %H is replaced by the hour (24-hour clock) as a decimal number [00,23].
  6261. %I is replaced by the hour (12-hour clock) as a decimal number [01,12].
  6262. %j is replaced by the day of the year as a decimal number [001,366].
  6263. %m is replaced by the month as a decimal number [01,12].
  6264. %M is replaced by the minute as a decimal number [00,59].
  6265. %p is replaced by the locale's equivalent of either a.m. or p.m.
  6266. %S is replaced by the second as a decimal number [00,61].
  6267. %U is replaced by the week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  6268. %w is replaced by the weekday as a decimal number [0,6], with 0 representing Sunday.
  6269. %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.
  6270. %x is replaced by the locale's appropriate date representation.
  6271. %X is replaced by the locale's appropriate time representation.
  6272. %y is replaced by the year without century as a decimal number [00,99].
  6273. %Y is replaced by the year with century as a decimal number.
  6274. %Z is replaced by the timezone name or abbreviation, or by no bytes if no timezone information exists.
  6275. %% is replaced by %.
  6276. @see toString
  6277. */
  6278. const String formatted (const String& format) const throw();
  6279. /** Adds a RelativeTime to this time and returns the result. */
  6280. const Time operator+ (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch + delta.inMilliseconds()); }
  6281. /** Subtracts a RelativeTime from this time and returns the result. */
  6282. const Time operator- (const RelativeTime& delta) const throw() { return Time (millisSinceEpoch - delta.inMilliseconds()); }
  6283. /** Returns the relative time difference between this time and another one. */
  6284. const RelativeTime operator- (const Time& other) const throw() { return RelativeTime::milliseconds (millisSinceEpoch - other.millisSinceEpoch); }
  6285. /** Compares two Time objects. */
  6286. bool operator== (const Time& other) const throw() { return millisSinceEpoch == other.millisSinceEpoch; }
  6287. /** Compares two Time objects. */
  6288. bool operator!= (const Time& other) const throw() { return millisSinceEpoch != other.millisSinceEpoch; }
  6289. /** Compares two Time objects. */
  6290. bool operator< (const Time& other) const throw() { return millisSinceEpoch < other.millisSinceEpoch; }
  6291. /** Compares two Time objects. */
  6292. bool operator<= (const Time& other) const throw() { return millisSinceEpoch <= other.millisSinceEpoch; }
  6293. /** Compares two Time objects. */
  6294. bool operator> (const Time& other) const throw() { return millisSinceEpoch > other.millisSinceEpoch; }
  6295. /** Compares two Time objects. */
  6296. bool operator>= (const Time& other) const throw() { return millisSinceEpoch >= other.millisSinceEpoch; }
  6297. /** Tries to set the computer's clock.
  6298. @returns true if this succeeds, although depending on the system, the
  6299. application might not have sufficient privileges to do this.
  6300. */
  6301. bool setSystemTimeToThisTime() const;
  6302. /** Returns the name of a day of the week.
  6303. @param dayNumber the day, 0 to 6 (0 = sunday, 1 = monday, etc)
  6304. @param threeLetterVersion if true, it'll return a 3-letter abbreviation, e.g. "Tue"; if
  6305. false, it'll return the full version, e.g. "Tuesday".
  6306. */
  6307. static const String getWeekdayName (int dayNumber,
  6308. bool threeLetterVersion) throw();
  6309. /** Returns the name of one of the months.
  6310. @param monthNumber the month, 0 to 11
  6311. @param threeLetterVersion if true, it'll be a 3-letter abbreviation, e.g. "Jan"; if false
  6312. it'll return the long form, e.g. "January"
  6313. */
  6314. static const String getMonthName (int monthNumber,
  6315. bool threeLetterVersion) throw();
  6316. // Static methods for getting system timers directly..
  6317. /** Returns the current system time.
  6318. Returns the number of milliseconds since midnight jan 1st 1970.
  6319. Should be accurate to within a few millisecs, depending on platform,
  6320. hardware, etc.
  6321. */
  6322. static int64 currentTimeMillis() throw();
  6323. /** Returns the number of millisecs since system startup.
  6324. Should be accurate to within a few millisecs, depending on platform,
  6325. hardware, etc.
  6326. @see getApproximateMillisecondCounter
  6327. */
  6328. static uint32 getMillisecondCounter() throw();
  6329. /** Returns the number of millisecs since system startup.
  6330. Same as getMillisecondCounter(), but returns a more accurate value, using
  6331. the high-res timer.
  6332. @see getMillisecondCounter
  6333. */
  6334. static double getMillisecondCounterHiRes() throw();
  6335. /** Waits until the getMillisecondCounter() reaches a given value.
  6336. This will make the thread sleep as efficiently as it can while it's waiting.
  6337. */
  6338. static void waitForMillisecondCounter (uint32 targetTime) throw();
  6339. /** Less-accurate but faster version of getMillisecondCounter().
  6340. This will return the last value that getMillisecondCounter() returned, so doesn't
  6341. need to make a system call, but is less accurate - it shouldn't be more than
  6342. 100ms away from the correct time, though, so is still accurate enough for a
  6343. lot of purposes.
  6344. @see getMillisecondCounter
  6345. */
  6346. static uint32 getApproximateMillisecondCounter() throw();
  6347. // High-resolution timers..
  6348. /** Returns the current high-resolution counter's tick-count.
  6349. This is a similar idea to getMillisecondCounter(), but with a higher
  6350. resolution.
  6351. @see getHighResolutionTicksPerSecond, highResolutionTicksToSeconds,
  6352. secondsToHighResolutionTicks
  6353. */
  6354. static int64 getHighResolutionTicks() throw();
  6355. /** Returns the resolution of the high-resolution counter in ticks per second.
  6356. @see getHighResolutionTicks, highResolutionTicksToSeconds,
  6357. secondsToHighResolutionTicks
  6358. */
  6359. static int64 getHighResolutionTicksPerSecond() throw();
  6360. /** Converts a number of high-resolution ticks into seconds.
  6361. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6362. secondsToHighResolutionTicks
  6363. */
  6364. static double highResolutionTicksToSeconds (int64 ticks) throw();
  6365. /** Converts a number seconds into high-resolution ticks.
  6366. @see getHighResolutionTicks, getHighResolutionTicksPerSecond,
  6367. highResolutionTicksToSeconds
  6368. */
  6369. static int64 secondsToHighResolutionTicks (double seconds) throw();
  6370. private:
  6371. int64 millisSinceEpoch;
  6372. };
  6373. #endif // __JUCE_TIME_JUCEHEADER__
  6374. /*** End of inlined file: juce_Time.h ***/
  6375. class FileInputStream;
  6376. class FileOutputStream;
  6377. /**
  6378. Represents a local file or directory.
  6379. This class encapsulates the absolute pathname of a file or directory, and
  6380. has methods for finding out about the file and changing its properties.
  6381. To read or write to the file, there are methods for returning an input or
  6382. output stream.
  6383. @see FileInputStream, FileOutputStream
  6384. */
  6385. class JUCE_API File
  6386. {
  6387. public:
  6388. /** Creates an (invalid) file object.
  6389. The file is initially set to an empty path, so getFullPath() will return
  6390. an empty string, and comparing the file to File::nonexistent will return
  6391. true.
  6392. You can use its operator= method to point it at a proper file.
  6393. */
  6394. File() {}
  6395. /** Creates a file from an absolute path.
  6396. If the path supplied is a relative path, it is taken to be relative
  6397. to the current working directory (see File::getCurrentWorkingDirectory()),
  6398. but this isn't a recommended way of creating a file, because you
  6399. never know what the CWD is going to be.
  6400. On the Mac/Linux, the path can include "~" notation for referring to
  6401. user home directories.
  6402. */
  6403. File (const String& path);
  6404. /** Creates a copy of another file object. */
  6405. File (const File& other);
  6406. /** Destructor. */
  6407. ~File() {}
  6408. /** Sets the file based on an absolute pathname.
  6409. If the path supplied is a relative path, it is taken to be relative
  6410. to the current working directory (see File::getCurrentWorkingDirectory()),
  6411. but this isn't a recommended way of creating a file, because you
  6412. never know what the CWD is going to be.
  6413. On the Mac/Linux, the path can include "~" notation for referring to
  6414. user home directories.
  6415. */
  6416. File& operator= (const String& newFilePath);
  6417. /** Copies from another file object. */
  6418. File& operator= (const File& otherFile);
  6419. /** This static constant is used for referring to an 'invalid' file. */
  6420. static const File nonexistent;
  6421. /** Checks whether the file actually exists.
  6422. @returns true if the file exists, either as a file or a directory.
  6423. @see existsAsFile, isDirectory
  6424. */
  6425. bool exists() const;
  6426. /** Checks whether the file exists and is a file rather than a directory.
  6427. @returns true only if this is a real file, false if it's a directory
  6428. or doesn't exist
  6429. @see exists, isDirectory
  6430. */
  6431. bool existsAsFile() const;
  6432. /** Checks whether the file is a directory that exists.
  6433. @returns true only if the file is a directory which actually exists, so
  6434. false if it's a file or doesn't exist at all
  6435. @see exists, existsAsFile
  6436. */
  6437. bool isDirectory() const;
  6438. /** Returns the size of the file in bytes.
  6439. @returns the number of bytes in the file, or 0 if it doesn't exist.
  6440. */
  6441. int64 getSize() const;
  6442. /** Utility function to convert a file size in bytes to a neat string description.
  6443. So for example 100 would return "100 bytes", 2000 would return "2 KB",
  6444. 2000000 would produce "2 MB", etc.
  6445. */
  6446. static const String descriptionOfSizeInBytes (int64 bytes);
  6447. /** Returns the complete, absolute path of this file.
  6448. This includes the filename and all its parent folders. On Windows it'll
  6449. also include the drive letter prefix; on Mac or Linux it'll be a complete
  6450. path starting from the root folder.
  6451. If you just want the file's name, you should use getFileName() or
  6452. getFileNameWithoutExtension().
  6453. @see getFileName, getRelativePathFrom
  6454. */
  6455. const String& getFullPathName() const throw() { return fullPath; }
  6456. /** Returns the last section of the pathname.
  6457. Returns just the final part of the path - e.g. if the whole path
  6458. is "/moose/fish/foo.txt" this will return "foo.txt".
  6459. For a directory, it returns the final part of the path - e.g. for the
  6460. directory "/moose/fish" it'll return "fish".
  6461. If the filename begins with a dot, it'll return the whole filename, e.g. for
  6462. "/moose/.fish", it'll return ".fish"
  6463. @see getFullPathName, getFileNameWithoutExtension
  6464. */
  6465. const String getFileName() const;
  6466. /** Creates a relative path that refers to a file relatively to a given directory.
  6467. e.g. File ("/moose/foo.txt").getRelativePathFrom ("/moose/fish/haddock")
  6468. would return "../../foo.txt".
  6469. If it's not possible to navigate from one file to the other, an absolute
  6470. path is returned. If the paths are invalid, an empty string may also be
  6471. returned.
  6472. @param directoryToBeRelativeTo the directory which the resultant string will
  6473. be relative to. If this is actually a file rather than
  6474. a directory, its parent directory will be used instead.
  6475. If it doesn't exist, it's assumed to be a directory.
  6476. @see getChildFile, isAbsolutePath
  6477. */
  6478. const String getRelativePathFrom (const File& directoryToBeRelativeTo) const;
  6479. /** Returns the file's extension.
  6480. Returns the file extension of this file, also including the dot.
  6481. e.g. "/moose/fish/foo.txt" would return ".txt"
  6482. @see hasFileExtension, withFileExtension, getFileNameWithoutExtension
  6483. */
  6484. const String getFileExtension() const;
  6485. /** Checks whether the file has a given extension.
  6486. @param extensionToTest the extension to look for - it doesn't matter whether or
  6487. not this string has a dot at the start, so ".wav" and "wav"
  6488. will have the same effect. The comparison used is
  6489. case-insensitve. To compare with multiple extensions, this
  6490. parameter can contain multiple strings, separated by semi-colons -
  6491. so, for example: hasFileExtension (".jpeg;png;gif") would return
  6492. true if the file has any of those three extensions.
  6493. @see getFileExtension, withFileExtension, getFileNameWithoutExtension
  6494. */
  6495. bool hasFileExtension (const String& extensionToTest) const;
  6496. /** Returns a version of this file with a different file extension.
  6497. e.g. File ("/moose/fish/foo.txt").withFileExtension ("html") returns "/moose/fish/foo.html"
  6498. @param newExtension the new extension, either with or without a dot at the start (this
  6499. doesn't make any difference). To get remove a file's extension altogether,
  6500. pass an empty string into this function.
  6501. @see getFileName, getFileExtension, hasFileExtension, getFileNameWithoutExtension
  6502. */
  6503. const File withFileExtension (const String& newExtension) const;
  6504. /** Returns the last part of the filename, without its file extension.
  6505. e.g. for "/moose/fish/foo.txt" this will return "foo".
  6506. @see getFileName, getFileExtension, hasFileExtension, withFileExtension
  6507. */
  6508. const String getFileNameWithoutExtension() const;
  6509. /** Returns a 32-bit hash-code that identifies this file.
  6510. This is based on the filename. Obviously it's possible, although unlikely, that
  6511. two files will have the same hash-code.
  6512. */
  6513. int hashCode() const;
  6514. /** Returns a 64-bit hash-code that identifies this file.
  6515. This is based on the filename. Obviously it's possible, although unlikely, that
  6516. two files will have the same hash-code.
  6517. */
  6518. int64 hashCode64() const;
  6519. /** Returns a file based on a relative path.
  6520. This will find a child file or directory of the current object.
  6521. e.g.
  6522. File ("/moose/fish").getChildFile ("foo.txt") will produce "/moose/fish/foo.txt".
  6523. File ("/moose/fish").getChildFile ("../foo.txt") will produce "/moose/foo.txt".
  6524. If the string is actually an absolute path, it will be treated as such, e.g.
  6525. File ("/moose/fish").getChildFile ("/foo.txt") will produce "/foo.txt"
  6526. @see getSiblingFile, getParentDirectory, getRelativePathFrom, isAChildOf
  6527. */
  6528. const File getChildFile (String relativePath) const;
  6529. /** Returns a file which is in the same directory as this one.
  6530. This is equivalent to getParentDirectory().getChildFile (name).
  6531. @see getChildFile, getParentDirectory
  6532. */
  6533. const File getSiblingFile (const String& siblingFileName) const;
  6534. /** Returns the directory that contains this file or directory.
  6535. e.g. for "/moose/fish/foo.txt" this will return "/moose/fish".
  6536. */
  6537. const File getParentDirectory() const;
  6538. /** Checks whether a file is somewhere inside a directory.
  6539. Returns true if this file is somewhere inside a subdirectory of the directory
  6540. that is passed in. Neither file actually has to exist, because the function
  6541. just checks the paths for similarities.
  6542. e.g. File ("/moose/fish/foo.txt").isAChildOf ("/moose") is true.
  6543. File ("/moose/fish/foo.txt").isAChildOf ("/moose/fish") is also true.
  6544. */
  6545. bool isAChildOf (const File& potentialParentDirectory) const;
  6546. /** Chooses a filename relative to this one that doesn't already exist.
  6547. If this file is a directory, this will return a child file of this
  6548. directory that doesn't exist, by adding numbers to a prefix and suffix until
  6549. it finds one that isn't already there.
  6550. If the prefix + the suffix doesn't exist, it won't bother adding a number.
  6551. e.g. File ("/moose/fish").getNonexistentChildFile ("foo", ".txt", true) might
  6552. return "/moose/fish/foo(2).txt" if there's already a file called "foo.txt".
  6553. @param prefix the string to use for the filename before the number
  6554. @param suffix the string to add to the filename after the number
  6555. @param putNumbersInBrackets if true, this will create filenames in the
  6556. format "prefix(number)suffix", if false, it will leave the
  6557. brackets out.
  6558. */
  6559. const File getNonexistentChildFile (const String& prefix,
  6560. const String& suffix,
  6561. bool putNumbersInBrackets = true) const;
  6562. /** Chooses a filename for a sibling file to this one that doesn't already exist.
  6563. If this file doesn't exist, this will just return itself, otherwise it
  6564. will return an appropriate sibling that doesn't exist, e.g. if a file
  6565. "/moose/fish/foo.txt" exists, this might return "/moose/fish/foo(2).txt".
  6566. @param putNumbersInBrackets whether to add brackets around the numbers that
  6567. get appended to the new filename.
  6568. */
  6569. const File getNonexistentSibling (bool putNumbersInBrackets = true) const;
  6570. /** Compares the pathnames for two files. */
  6571. bool operator== (const File& otherFile) const;
  6572. /** Compares the pathnames for two files. */
  6573. bool operator!= (const File& otherFile) const;
  6574. /** Compares the pathnames for two files. */
  6575. bool operator< (const File& otherFile) const;
  6576. /** Compares the pathnames for two files. */
  6577. bool operator> (const File& otherFile) const;
  6578. /** Checks whether a file can be created or written to.
  6579. @returns true if it's possible to create and write to this file. If the file
  6580. doesn't already exist, this will check its parent directory to
  6581. see if writing is allowed.
  6582. @see setReadOnly
  6583. */
  6584. bool hasWriteAccess() const;
  6585. /** Changes the write-permission of a file or directory.
  6586. @param shouldBeReadOnly whether to add or remove write-permission
  6587. @param applyRecursively if the file is a directory and this is true, it will
  6588. recurse through all the subfolders changing the permissions
  6589. of all files
  6590. @returns true if it manages to change the file's permissions.
  6591. @see hasWriteAccess
  6592. */
  6593. bool setReadOnly (bool shouldBeReadOnly,
  6594. bool applyRecursively = false) const;
  6595. /** Returns true if this file is a hidden or system file.
  6596. The criteria for deciding whether a file is hidden are platform-dependent.
  6597. */
  6598. bool isHidden() const;
  6599. /** If this file is a link, this returns the file that it points to.
  6600. If this file isn't actually link, it'll just return itself.
  6601. */
  6602. const File getLinkedTarget() const;
  6603. /** Returns the last modification time of this file.
  6604. @returns the time, or an invalid time if the file doesn't exist.
  6605. @see setLastModificationTime, getLastAccessTime, getCreationTime
  6606. */
  6607. const Time getLastModificationTime() const;
  6608. /** Returns the last time this file was accessed.
  6609. @returns the time, or an invalid time if the file doesn't exist.
  6610. @see setLastAccessTime, getLastModificationTime, getCreationTime
  6611. */
  6612. const Time getLastAccessTime() const;
  6613. /** Returns the time that this file was created.
  6614. @returns the time, or an invalid time if the file doesn't exist.
  6615. @see getLastModificationTime, getLastAccessTime
  6616. */
  6617. const Time getCreationTime() const;
  6618. /** Changes the modification time for this file.
  6619. @param newTime the time to apply to the file
  6620. @returns true if it manages to change the file's time.
  6621. @see getLastModificationTime, setLastAccessTime, setCreationTime
  6622. */
  6623. bool setLastModificationTime (const Time& newTime) const;
  6624. /** Changes the last-access time for this file.
  6625. @param newTime the time to apply to the file
  6626. @returns true if it manages to change the file's time.
  6627. @see getLastAccessTime, setLastModificationTime, setCreationTime
  6628. */
  6629. bool setLastAccessTime (const Time& newTime) const;
  6630. /** Changes the creation date for this file.
  6631. @param newTime the time to apply to the file
  6632. @returns true if it manages to change the file's time.
  6633. @see getCreationTime, setLastModificationTime, setLastAccessTime
  6634. */
  6635. bool setCreationTime (const Time& newTime) const;
  6636. /** If possible, this will try to create a version string for the given file.
  6637. The OS may be able to look at the file and give a version for it - e.g. with
  6638. executables, bundles, dlls, etc. If no version is available, this will
  6639. return an empty string.
  6640. */
  6641. const String getVersion() const;
  6642. /** Creates an empty file if it doesn't already exist.
  6643. If the file that this object refers to doesn't exist, this will create a file
  6644. of zero size.
  6645. If it already exists or is a directory, this method will do nothing.
  6646. @returns true if the file has been created (or if it already existed).
  6647. @see createDirectory
  6648. */
  6649. bool create() const;
  6650. /** Creates a new directory for this filename.
  6651. This will try to create the file as a directory, and fill also create
  6652. any parent directories it needs in order to complete the operation.
  6653. @returns true if the directory has been created successfully, (or if it
  6654. already existed beforehand).
  6655. @see create
  6656. */
  6657. bool createDirectory() const;
  6658. /** Deletes a file.
  6659. If this file is actually a directory, it may not be deleted correctly if it
  6660. contains files. See deleteRecursively() as a better way of deleting directories.
  6661. @returns true if the file has been successfully deleted (or if it didn't exist to
  6662. begin with).
  6663. @see deleteRecursively
  6664. */
  6665. bool deleteFile() const;
  6666. /** Deletes a file or directory and all its subdirectories.
  6667. If this file is a directory, this will try to delete it and all its subfolders. If
  6668. it's just a file, it will just try to delete the file.
  6669. @returns true if the file and all its subfolders have been successfully deleted
  6670. (or if it didn't exist to begin with).
  6671. @see deleteFile
  6672. */
  6673. bool deleteRecursively() const;
  6674. /** Moves this file or folder to the trash.
  6675. @returns true if the operation succeeded. It could fail if the trash is full, or
  6676. if the file is write-protected, so you should check the return value
  6677. and act appropriately.
  6678. */
  6679. bool moveToTrash() const;
  6680. /** Moves or renames a file.
  6681. Tries to move a file to a different location.
  6682. If the target file already exists, this will attempt to delete it first, and
  6683. will fail if this can't be done.
  6684. Note that the destination file isn't the directory to put it in, it's the actual
  6685. filename that you want the new file to have.
  6686. @returns true if the operation succeeds
  6687. */
  6688. bool moveFileTo (const File& targetLocation) const;
  6689. /** Copies a file.
  6690. Tries to copy a file to a different location.
  6691. If the target file already exists, this will attempt to delete it first, and
  6692. will fail if this can't be done.
  6693. @returns true if the operation succeeds
  6694. */
  6695. bool copyFileTo (const File& targetLocation) const;
  6696. /** Copies a directory.
  6697. Tries to copy an entire directory, recursively.
  6698. If this file isn't a directory or if any target files can't be created, this
  6699. will return false.
  6700. @param newDirectory the directory that this one should be copied to. Note that this
  6701. is the name of the actual directory to create, not the directory
  6702. into which the new one should be placed, so there must be enough
  6703. write privileges to create it if it doesn't exist. Any files inside
  6704. it will be overwritten by similarly named ones that are copied.
  6705. */
  6706. bool copyDirectoryTo (const File& newDirectory) const;
  6707. /** Used in file searching, to specify whether to return files, directories, or both.
  6708. */
  6709. enum TypesOfFileToFind
  6710. {
  6711. findDirectories = 1, /**< Use this flag to indicate that you want to find directories. */
  6712. findFiles = 2, /**< Use this flag to indicate that you want to find files. */
  6713. findFilesAndDirectories = 3, /**< Use this flag to indicate that you want to find both files and directories. */
  6714. ignoreHiddenFiles = 4 /**< Add this flag to avoid returning any hidden files in the results. */
  6715. };
  6716. /** Searches inside a directory for files matching a wildcard pattern.
  6717. Assuming that this file is a directory, this method will search it
  6718. for either files or subdirectories whose names match a filename pattern.
  6719. @param results an array to which File objects will be added for the
  6720. files that the search comes up with
  6721. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6722. return files, directories, or both. If the ignoreHiddenFiles flag
  6723. is also added to this value, hidden files won't be returned
  6724. @param searchRecursively if true, all subdirectories will be recursed into to do
  6725. an exhaustive search
  6726. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6727. @returns the number of results that have been found
  6728. @see getNumberOfChildFiles, DirectoryIterator
  6729. */
  6730. int findChildFiles (Array<File>& results,
  6731. int whatToLookFor,
  6732. bool searchRecursively,
  6733. const String& wildCardPattern = "*") const;
  6734. /** Searches inside a directory and counts how many files match a wildcard pattern.
  6735. Assuming that this file is a directory, this method will search it
  6736. for either files or subdirectories whose names match a filename pattern,
  6737. and will return the number of matches found.
  6738. This isn't a recursive call, and will only search this directory, not
  6739. its children.
  6740. @param whatToLookFor a value from the TypesOfFileToFind enum, specifying whether to
  6741. count files, directories, or both. If the ignoreHiddenFiles flag
  6742. is also added to this value, hidden files won't be counted
  6743. @param wildCardPattern the filename pattern to search for, e.g. "*.txt"
  6744. @returns the number of matches found
  6745. @see findChildFiles, DirectoryIterator
  6746. */
  6747. int getNumberOfChildFiles (int whatToLookFor,
  6748. const String& wildCardPattern = "*") const;
  6749. /** Returns true if this file is a directory that contains one or more subdirectories.
  6750. @see isDirectory, findChildFiles
  6751. */
  6752. bool containsSubDirectories() const;
  6753. /** Creates a stream to read from this file.
  6754. @returns a stream that will read from this file (initially positioned at the
  6755. start of the file), or 0 if the file can't be opened for some reason
  6756. @see createOutputStream, loadFileAsData
  6757. */
  6758. FileInputStream* createInputStream() const;
  6759. /** Creates a stream to write to this file.
  6760. If the file exists, the stream that is returned will be positioned ready for
  6761. writing at the end of the file, so you might want to use deleteFile() first
  6762. to write to an empty file.
  6763. @returns a stream that will write to this file (initially positioned at the
  6764. end of the file), or 0 if the file can't be opened for some reason
  6765. @see createInputStream, appendData, appendText
  6766. */
  6767. FileOutputStream* createOutputStream (int bufferSize = 0x8000) const;
  6768. /** Loads a file's contents into memory as a block of binary data.
  6769. Of course, trying to load a very large file into memory will blow up, so
  6770. it's better to check first.
  6771. @param result the data block to which the file's contents should be appended - note
  6772. that if the memory block might already contain some data, you
  6773. might want to clear it first
  6774. @returns true if the file could all be read into memory
  6775. */
  6776. bool loadFileAsData (MemoryBlock& result) const;
  6777. /** Reads a file into memory as a string.
  6778. Attempts to load the entire file as a zero-terminated string.
  6779. This makes use of InputStream::readEntireStreamAsString, which should
  6780. automatically cope with unicode/acsii file formats.
  6781. */
  6782. const String loadFileAsString() const;
  6783. /** Appends a block of binary data to the end of the file.
  6784. This will try to write the given buffer to the end of the file.
  6785. @returns false if it can't write to the file for some reason
  6786. */
  6787. bool appendData (const void* dataToAppend,
  6788. int numberOfBytes) const;
  6789. /** Replaces this file's contents with a given block of data.
  6790. This will delete the file and replace it with the given data.
  6791. A nice feature of this method is that it's safe - instead of deleting
  6792. the file first and then re-writing it, it creates a new temporary file,
  6793. writes the data to that, and then moves the new file to replace the existing
  6794. file. This means that if the power gets pulled out or something crashes,
  6795. you're a lot less likely to end up with an empty file..
  6796. Returns true if the operation succeeds, or false if it fails.
  6797. @see appendText
  6798. */
  6799. bool replaceWithData (const void* dataToWrite,
  6800. int numberOfBytes) const;
  6801. /** Appends a string to the end of the file.
  6802. This will try to append a text string to the file, as either 16-bit unicode
  6803. or 8-bit characters in the default system encoding.
  6804. It can also write the 'ff fe' unicode header bytes before the text to indicate
  6805. the endianness of the file.
  6806. Any single \\n characters in the string are replaced with \\r\\n before it is written.
  6807. @see replaceWithText
  6808. */
  6809. bool appendText (const String& textToAppend,
  6810. bool asUnicode = false,
  6811. bool writeUnicodeHeaderBytes = false) const;
  6812. /** Replaces this file's contents with a given text string.
  6813. This will delete the file and replace it with the given text.
  6814. A nice feature of this method is that it's safe - instead of deleting
  6815. the file first and then re-writing it, it creates a new temporary file,
  6816. writes the text to that, and then moves the new file to replace the existing
  6817. file. This means that if the power gets pulled out or something crashes,
  6818. you're a lot less likely to end up with an empty file..
  6819. For an explanation of the parameters here, see the appendText() method.
  6820. Returns true if the operation succeeds, or false if it fails.
  6821. @see appendText
  6822. */
  6823. bool replaceWithText (const String& textToWrite,
  6824. bool asUnicode = false,
  6825. bool writeUnicodeHeaderBytes = false) const;
  6826. /** Attempts to scan the contents of this file and compare it to another file, returning
  6827. true if this is possible and they match byte-for-byte.
  6828. */
  6829. bool hasIdenticalContentTo (const File& other) const;
  6830. /** Creates a set of files to represent each file root.
  6831. e.g. on Windows this will create files for "c:\", "d:\" etc according
  6832. to which ones are available. On the Mac/Linux, this will probably
  6833. just add a single entry for "/".
  6834. */
  6835. static void findFileSystemRoots (Array<File>& results);
  6836. /** Finds the name of the drive on which this file lives.
  6837. @returns the volume label of the drive, or an empty string if this isn't possible
  6838. */
  6839. const String getVolumeLabel() const;
  6840. /** Returns the serial number of the volume on which this file lives.
  6841. @returns the serial number, or zero if there's a problem doing this
  6842. */
  6843. int getVolumeSerialNumber() const;
  6844. /** Returns the number of bytes free on the drive that this file lives on.
  6845. @returns the number of bytes free, or 0 if there's a problem finding this out
  6846. @see getVolumeTotalSize
  6847. */
  6848. int64 getBytesFreeOnVolume() const;
  6849. /** Returns the total size of the drive that contains this file.
  6850. @returns the total number of bytes that the volume can hold
  6851. @see getBytesFreeOnVolume
  6852. */
  6853. int64 getVolumeTotalSize() const;
  6854. /** Returns true if this file is on a CD or DVD drive. */
  6855. bool isOnCDRomDrive() const;
  6856. /** Returns true if this file is on a hard disk.
  6857. This will fail if it's a network drive, but will still be true for
  6858. removable hard-disks.
  6859. */
  6860. bool isOnHardDisk() const;
  6861. /** Returns true if this file is on a removable disk drive.
  6862. This might be a usb-drive, a CD-rom, or maybe a network drive.
  6863. */
  6864. bool isOnRemovableDrive() const;
  6865. /** Launches the file as a process.
  6866. - if the file is executable, this will run it.
  6867. - if it's a document of some kind, it will launch the document with its
  6868. default viewer application.
  6869. - if it's a folder, it will be opened in Explorer, Finder, or equivalent.
  6870. @see revealToUser
  6871. */
  6872. bool startAsProcess (const String& parameters = String::empty) const;
  6873. /** Opens Finder, Explorer, or whatever the OS uses, to show the user this file's location.
  6874. @see startAsProcess
  6875. */
  6876. void revealToUser() const;
  6877. /** A set of types of location that can be passed to the getSpecialLocation() method.
  6878. */
  6879. enum SpecialLocationType
  6880. {
  6881. /** The user's home folder. This is the same as using File ("~"). */
  6882. userHomeDirectory,
  6883. /** The user's default documents folder. On Windows, this might be the user's
  6884. "My Documents" folder. On the Mac it'll be their "Documents" folder. Linux
  6885. doesn't tend to have one of these, so it might just return their home folder.
  6886. */
  6887. userDocumentsDirectory,
  6888. /** The folder that contains the user's desktop objects. */
  6889. userDesktopDirectory,
  6890. /** The folder in which applications store their persistent user-specific settings.
  6891. On Windows, this might be "\Documents and Settings\username\Application Data".
  6892. On the Mac, it might be "~/Library". If you're going to store your settings in here,
  6893. always create your own sub-folder to put them in, to avoid making a mess.
  6894. */
  6895. userApplicationDataDirectory,
  6896. /** An equivalent of the userApplicationDataDirectory folder that is shared by all users
  6897. of the computer, rather than just the current user.
  6898. On the Mac it'll be "/Library", on Windows, it could be something like
  6899. "\Documents and Settings\All Users\Application Data".
  6900. Depending on the setup, this folder may be read-only.
  6901. */
  6902. commonApplicationDataDirectory,
  6903. /** The folder that should be used for temporary files.
  6904. Always delete them when you're finished, to keep the user's computer tidy!
  6905. */
  6906. tempDirectory,
  6907. /** Returns this application's executable file.
  6908. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6909. host app.
  6910. On the mac this will return the unix binary, not the package folder - see
  6911. currentApplicationFile for that.
  6912. See also invokedExecutableFile, which is similar, but if the exe was launched from a
  6913. file link, invokedExecutableFile will return the name of the link.
  6914. */
  6915. currentExecutableFile,
  6916. /** Returns this application's location.
  6917. If running as a plug-in or DLL, this will (where possible) be the DLL rather than the
  6918. host app.
  6919. On the mac this will return the package folder (if it's in one), not the unix binary
  6920. that's inside it - compare with currentExecutableFile.
  6921. */
  6922. currentApplicationFile,
  6923. /** Returns the file that was invoked to launch this executable.
  6924. This may differ from currentExecutableFile if the app was started from e.g. a link - this
  6925. will return the name of the link that was used, whereas currentExecutableFile will return
  6926. the actual location of the target executable.
  6927. */
  6928. invokedExecutableFile,
  6929. /** The directory in which applications normally get installed.
  6930. So on windows, this would be something like "c:\program files", on the
  6931. Mac "/Applications", or "/usr" on linux.
  6932. */
  6933. globalApplicationsDirectory,
  6934. /** The most likely place where a user might store their music files.
  6935. */
  6936. userMusicDirectory,
  6937. /** The most likely place where a user might store their movie files.
  6938. */
  6939. userMoviesDirectory,
  6940. };
  6941. /** Finds the location of a special type of file or directory, such as a home folder or
  6942. documents folder.
  6943. @see SpecialLocationType
  6944. */
  6945. static const File JUCE_CALLTYPE getSpecialLocation (const SpecialLocationType type);
  6946. /** Returns a temporary file in the system's temp directory.
  6947. This will try to return the name of a non-existent temp file.
  6948. To get the temp folder, you can use getSpecialLocation (File::tempDirectory).
  6949. */
  6950. static const File createTempFile (const String& fileNameEnding);
  6951. /** Returns the current working directory.
  6952. @see setAsCurrentWorkingDirectory
  6953. */
  6954. static const File getCurrentWorkingDirectory();
  6955. /** Sets the current working directory to be this file.
  6956. For this to work the file must point to a valid directory.
  6957. @returns true if the current directory has been changed.
  6958. @see getCurrentWorkingDirectory
  6959. */
  6960. bool setAsCurrentWorkingDirectory() const;
  6961. /** The system-specific file separator character.
  6962. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6963. */
  6964. static const juce_wchar separator;
  6965. /** The system-specific file separator character, as a string.
  6966. On Windows, this will be '\', on Mac/Linux, it'll be '/'
  6967. */
  6968. static const String separatorString;
  6969. /** Removes illegal characters from a filename.
  6970. This will return a copy of the given string after removing characters
  6971. that are not allowed in a legal filename, and possibly shortening the
  6972. string if it's too long.
  6973. Because this will remove slashes, don't use it on an absolute pathname.
  6974. @see createLegalPathName
  6975. */
  6976. static const String createLegalFileName (const String& fileNameToFix);
  6977. /** Removes illegal characters from a pathname.
  6978. Similar to createLegalFileName(), but this won't remove slashes, so can
  6979. be used on a complete pathname.
  6980. @see createLegalFileName
  6981. */
  6982. static const String createLegalPathName (const String& pathNameToFix);
  6983. /** Indicates whether filenames are case-sensitive on the current operating system.
  6984. */
  6985. static bool areFileNamesCaseSensitive();
  6986. /** Returns true if the string seems to be a fully-specified absolute path.
  6987. */
  6988. static bool isAbsolutePath (const String& path);
  6989. /** Creates a file that simply contains this string, without doing the sanity-checking
  6990. that the normal constructors do.
  6991. Best to avoid this unless you really know what you're doing.
  6992. */
  6993. static const File createFileWithoutCheckingPath (const String& path);
  6994. /** Adds a separator character to the end of a path if it doesn't already have one. */
  6995. static const String addTrailingSeparator (const String& path);
  6996. juce_UseDebuggingNewOperator
  6997. private:
  6998. String fullPath;
  6999. // internal way of contructing a file without checking the path
  7000. friend class DirectoryIterator;
  7001. File (const String&, int);
  7002. const String getPathUpToLastSlash() const;
  7003. void createDirectoryInternal (const String& fileName) const;
  7004. bool copyInternal (const File& dest) const;
  7005. bool moveInternal (const File& dest) const;
  7006. bool setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const;
  7007. void getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const;
  7008. bool setFileReadOnlyInternal (bool shouldBeReadOnly) const;
  7009. static const String parseAbsolutePath (const String& path);
  7010. static bool fileTypeMatches (int whatToLookFor, bool isDir, bool isHidden);
  7011. };
  7012. #endif // __JUCE_FILE_JUCEHEADER__
  7013. /*** End of inlined file: juce_File.h ***/
  7014. /** A handy macro to make it easy to iterate all the child elements in an XmlElement.
  7015. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7016. will be the name of a pointer to each child element.
  7017. E.g. @code
  7018. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7019. forEachXmlChildElement (*myParentXml, child)
  7020. {
  7021. if (child->hasTagName ("FOO"))
  7022. doSomethingWithXmlElement (child);
  7023. }
  7024. @endcode
  7025. @see forEachXmlChildElementWithTagName
  7026. */
  7027. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  7028. \
  7029. for (XmlElement* childElementVariableName = (parentXmlElement).getFirstChildElement(); \
  7030. childElementVariableName != 0; \
  7031. childElementVariableName = childElementVariableName->getNextElement())
  7032. /** A macro that makes it easy to iterate all the child elements of an XmlElement
  7033. which have a specified tag.
  7034. This does the same job as the forEachXmlChildElement macro, but only for those
  7035. elements that have a particular tag name.
  7036. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  7037. will be the name of a pointer to each child element. The requiredTagName is the
  7038. tag name to match.
  7039. E.g. @code
  7040. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  7041. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  7042. {
  7043. // the child object is now guaranteed to be a <MYTAG> element..
  7044. doSomethingWithMYTAGElement (child);
  7045. }
  7046. @endcode
  7047. @see forEachXmlChildElement
  7048. */
  7049. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  7050. \
  7051. for (XmlElement* childElementVariableName = (parentXmlElement).getChildByName (requiredTagName); \
  7052. childElementVariableName != 0; \
  7053. childElementVariableName = childElementVariableName->getNextElementWithTagName (requiredTagName))
  7054. /** Used to build a tree of elements representing an XML document.
  7055. An XML document can be parsed into a tree of XmlElements, each of which
  7056. represents an XML tag structure, and which may itself contain other
  7057. nested elements.
  7058. An XmlElement can also be converted back into a text document, and has
  7059. lots of useful methods for manipulating its attributes and sub-elements,
  7060. so XmlElements can actually be used as a handy general-purpose data
  7061. structure.
  7062. Here's an example of parsing some elements: @code
  7063. // check we're looking at the right kind of document..
  7064. if (myElement->hasTagName ("ANIMALS"))
  7065. {
  7066. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  7067. forEachXmlChildElement (*myElement, e)
  7068. {
  7069. if (e->hasTagName ("GIRAFFE"))
  7070. {
  7071. // found a giraffe, so use some of its attributes..
  7072. String giraffeName = e->getStringAttribute ("name");
  7073. int giraffeAge = e->getIntAttribute ("age");
  7074. bool isFriendly = e->getBoolAttribute ("friendly");
  7075. }
  7076. }
  7077. }
  7078. @endcode
  7079. And here's an example of how to create an XML document from scratch: @code
  7080. // create an outer node called "ANIMALS"
  7081. XmlElement animalsList ("ANIMALS");
  7082. for (int i = 0; i < numAnimals; ++i)
  7083. {
  7084. // create an inner element..
  7085. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  7086. giraffe->setAttribute ("name", "nigel");
  7087. giraffe->setAttribute ("age", 10);
  7088. giraffe->setAttribute ("friendly", true);
  7089. // ..and add our new element to the parent node
  7090. animalsList.addChildElement (giraffe);
  7091. }
  7092. // now we can turn the whole thing into a text document..
  7093. String myXmlDoc = animalsList.createDocument (String::empty);
  7094. @endcode
  7095. @see XmlDocument
  7096. */
  7097. class JUCE_API XmlElement
  7098. {
  7099. public:
  7100. /** Creates an XmlElement with this tag name. */
  7101. explicit XmlElement (const String& tagName) throw();
  7102. /** Creates a (deep) copy of another element. */
  7103. XmlElement (const XmlElement& other);
  7104. /** Creates a (deep) copy of another element. */
  7105. XmlElement& operator= (const XmlElement& other);
  7106. /** Deleting an XmlElement will also delete all its child elements. */
  7107. ~XmlElement() throw();
  7108. /** Compares two XmlElements to see if they contain the same text and attiributes.
  7109. The elements are only considered equivalent if they contain the same attiributes
  7110. with the same values, and have the same sub-nodes.
  7111. @param other the other element to compare to
  7112. @param ignoreOrderOfAttributes if true, this means that two elements with the
  7113. same attributes in a different order will be
  7114. considered the same; if false, the attributes must
  7115. be in the same order as well
  7116. */
  7117. bool isEquivalentTo (const XmlElement* other,
  7118. bool ignoreOrderOfAttributes) const throw();
  7119. /** Returns an XML text document that represents this element.
  7120. The string returned can be parsed to recreate the same XmlElement that
  7121. was used to create it.
  7122. @param dtdToUse the DTD to add to the document
  7123. @param allOnOneLine if true, this means that the document will not contain any
  7124. linefeeds, so it'll be smaller but not very easy to read.
  7125. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7126. document
  7127. @param encodingType the character encoding format string to put into the xml
  7128. header
  7129. @param lineWrapLength the line length that will be used before items get placed on
  7130. a new line. This isn't an absolute maximum length, it just
  7131. determines how lists of attributes get broken up
  7132. @see writeToStream, writeToFile
  7133. */
  7134. const String createDocument (const String& dtdToUse,
  7135. bool allOnOneLine = false,
  7136. bool includeXmlHeader = true,
  7137. const String& encodingType = "UTF-8",
  7138. int lineWrapLength = 60) const;
  7139. /** Writes the document to a stream as UTF-8.
  7140. @param output the stream to write to
  7141. @param dtdToUse the DTD to add to the document
  7142. @param allOnOneLine if true, this means that the document will not contain any
  7143. linefeeds, so it'll be smaller but not very easy to read.
  7144. @param includeXmlHeader whether to add the "<?xml version..etc" line at the start of the
  7145. document
  7146. @param encodingType the character encoding format string to put into the xml
  7147. header
  7148. @param lineWrapLength the line length that will be used before items get placed on
  7149. a new line. This isn't an absolute maximum length, it just
  7150. determines how lists of attributes get broken up
  7151. @see writeToFile, createDocument
  7152. */
  7153. void writeToStream (OutputStream& output,
  7154. const String& dtdToUse,
  7155. bool allOnOneLine = false,
  7156. bool includeXmlHeader = true,
  7157. const String& encodingType = "UTF-8",
  7158. int lineWrapLength = 60) const;
  7159. /** Writes the element to a file as an XML document.
  7160. To improve safety in case something goes wrong while writing the file, this
  7161. will actually write the document to a new temporary file in the same
  7162. directory as the destination file, and if this succeeds, it will rename this
  7163. new file as the destination file (overwriting any existing file that was there).
  7164. @param destinationFile the file to write to. If this already exists, it will be
  7165. overwritten.
  7166. @param dtdToUse the DTD to add to the document
  7167. @param encodingType the character encoding format string to put into the xml
  7168. header
  7169. @param lineWrapLength the line length that will be used before items get placed on
  7170. a new line. This isn't an absolute maximum length, it just
  7171. determines how lists of attributes get broken up
  7172. @returns true if the file is written successfully; false if something goes wrong
  7173. in the process
  7174. @see createDocument
  7175. */
  7176. bool writeToFile (const File& destinationFile,
  7177. const String& dtdToUse,
  7178. const String& encodingType = "UTF-8",
  7179. int lineWrapLength = 60) const;
  7180. /** Returns this element's tag type name.
  7181. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return
  7182. "MOOSE".
  7183. @see hasTagName
  7184. */
  7185. inline const String& getTagName() const throw() { return tagName; }
  7186. /** Tests whether this element has a particular tag name.
  7187. @param possibleTagName the tag name you're comparing it with
  7188. @see getTagName
  7189. */
  7190. bool hasTagName (const String& possibleTagName) const throw();
  7191. /** Returns the number of XML attributes this element contains.
  7192. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  7193. return 2.
  7194. */
  7195. int getNumAttributes() const throw();
  7196. /** Returns the name of one of the elements attributes.
  7197. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7198. getAttributeName(1) would return "antlers".
  7199. @see getAttributeValue, getStringAttribute
  7200. */
  7201. const String& getAttributeName (int attributeIndex) const throw();
  7202. /** Returns the value of one of the elements attributes.
  7203. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  7204. getAttributeName(1) would return "2".
  7205. @see getAttributeName, getStringAttribute
  7206. */
  7207. const String& getAttributeValue (int attributeIndex) const throw();
  7208. // Attribute-handling methods..
  7209. /** Checks whether the element contains an attribute with a certain name. */
  7210. bool hasAttribute (const String& attributeName) const throw();
  7211. /** Returns the value of a named attribute.
  7212. @param attributeName the name of the attribute to look up
  7213. */
  7214. const String& getStringAttribute (const String& attributeName) const throw();
  7215. /** Returns the value of a named attribute.
  7216. @param attributeName the name of the attribute to look up
  7217. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7218. with this name
  7219. */
  7220. const String getStringAttribute (const String& attributeName,
  7221. const String& defaultReturnValue) const;
  7222. /** Compares the value of a named attribute with a value passed-in.
  7223. @param attributeName the name of the attribute to look up
  7224. @param stringToCompareAgainst the value to compare it with
  7225. @param ignoreCase whether the comparison should be case-insensitive
  7226. @returns true if the value of the attribute is the same as the string passed-in;
  7227. false if it's different (or if no such attribute exists)
  7228. */
  7229. bool compareAttribute (const String& attributeName,
  7230. const String& stringToCompareAgainst,
  7231. bool ignoreCase = false) const throw();
  7232. /** Returns the value of a named attribute as an integer.
  7233. This will try to find the attribute and convert it to an integer (using
  7234. the String::getIntValue() method).
  7235. @param attributeName the name of the attribute to look up
  7236. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7237. with this name
  7238. @see setAttribute
  7239. */
  7240. int getIntAttribute (const String& attributeName,
  7241. int defaultReturnValue = 0) const;
  7242. /** Returns the value of a named attribute as floating-point.
  7243. This will try to find the attribute and convert it to an integer (using
  7244. the String::getDoubleValue() method).
  7245. @param attributeName the name of the attribute to look up
  7246. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7247. with this name
  7248. @see setAttribute
  7249. */
  7250. double getDoubleAttribute (const String& attributeName,
  7251. double defaultReturnValue = 0.0) const;
  7252. /** Returns the value of a named attribute as a boolean.
  7253. This will try to find the attribute and interpret it as a boolean. To do this,
  7254. it'll return true if the value is "1", "true", "y", etc, or false for other
  7255. values.
  7256. @param attributeName the name of the attribute to look up
  7257. @param defaultReturnValue a value to return if the element doesn't have an attribute
  7258. with this name
  7259. */
  7260. bool getBoolAttribute (const String& attributeName,
  7261. bool defaultReturnValue = false) const;
  7262. /** Adds a named attribute to the element.
  7263. If the element already contains an attribute with this name, it's value will
  7264. be updated to the new value. If there's no such attribute yet, a new one will
  7265. be added.
  7266. Note that there are other setAttribute() methods that take integers,
  7267. doubles, etc. to make it easy to store numbers.
  7268. @param attributeName the name of the attribute to set
  7269. @param newValue the value to set it to
  7270. @see removeAttribute
  7271. */
  7272. void setAttribute (const String& attributeName,
  7273. const String& newValue);
  7274. /** Adds a named attribute to the element, setting it to an integer value.
  7275. If the element already contains an attribute with this name, it's value will
  7276. be updated to the new value. If there's no such attribute yet, a new one will
  7277. be added.
  7278. Note that there are other setAttribute() methods that take integers,
  7279. doubles, etc. to make it easy to store numbers.
  7280. @param attributeName the name of the attribute to set
  7281. @param newValue the value to set it to
  7282. */
  7283. void setAttribute (const String& attributeName,
  7284. int newValue);
  7285. /** Adds a named attribute to the element, setting it to a floating-point value.
  7286. If the element already contains an attribute with this name, it's value will
  7287. be updated to the new value. If there's no such attribute yet, a new one will
  7288. be added.
  7289. Note that there are other setAttribute() methods that take integers,
  7290. doubles, etc. to make it easy to store numbers.
  7291. @param attributeName the name of the attribute to set
  7292. @param newValue the value to set it to
  7293. */
  7294. void setAttribute (const String& attributeName,
  7295. double newValue);
  7296. /** Removes a named attribute from the element.
  7297. @param attributeName the name of the attribute to remove
  7298. @see removeAllAttributes
  7299. */
  7300. void removeAttribute (const String& attributeName) throw();
  7301. /** Removes all attributes from this element.
  7302. */
  7303. void removeAllAttributes() throw();
  7304. // Child element methods..
  7305. /** Returns the first of this element's sub-elements.
  7306. see getNextElement() for an example of how to iterate the sub-elements.
  7307. @see forEachXmlChildElement
  7308. */
  7309. XmlElement* getFirstChildElement() const throw() { return firstChildElement; }
  7310. /** Returns the next of this element's siblings.
  7311. This can be used for iterating an element's sub-elements, e.g.
  7312. @code
  7313. XmlElement* child = myXmlDocument->getFirstChildElement();
  7314. while (child != 0)
  7315. {
  7316. ...do stuff with this child..
  7317. child = child->getNextElement();
  7318. }
  7319. @endcode
  7320. Note that when iterating the child elements, some of them might be
  7321. text elements as well as XML tags - use isTextElement() to work this
  7322. out.
  7323. Also, it's much easier and neater to use this method indirectly via the
  7324. forEachXmlChildElement macro.
  7325. @returns the sibling element that follows this one, or zero if this is the last
  7326. element in its parent
  7327. @see getNextElement, isTextElement, forEachXmlChildElement
  7328. */
  7329. inline XmlElement* getNextElement() const throw() { return nextElement; }
  7330. /** Returns the next of this element's siblings which has the specified tag
  7331. name.
  7332. This is like getNextElement(), but will scan through the list until it
  7333. finds an element with the given tag name.
  7334. @see getNextElement, forEachXmlChildElementWithTagName
  7335. */
  7336. XmlElement* getNextElementWithTagName (const String& requiredTagName) const;
  7337. /** Returns the number of sub-elements in this element.
  7338. @see getChildElement
  7339. */
  7340. int getNumChildElements() const throw();
  7341. /** Returns the sub-element at a certain index.
  7342. It's not very efficient to iterate the sub-elements by index - see
  7343. getNextElement() for an example of how best to iterate.
  7344. @returns the n'th child of this element, or 0 if the index is out-of-range
  7345. @see getNextElement, isTextElement, getChildByName
  7346. */
  7347. XmlElement* getChildElement (int index) const throw();
  7348. /** Returns the first sub-element with a given tag-name.
  7349. @param tagNameToLookFor the tag name of the element you want to find
  7350. @returns the first element with this tag name, or 0 if none is found
  7351. @see getNextElement, isTextElement, getChildElement
  7352. */
  7353. XmlElement* getChildByName (const String& tagNameToLookFor) const throw();
  7354. /** Appends an element to this element's list of children.
  7355. Child elements are deleted automatically when their parent is deleted, so
  7356. make sure the object that you pass in will not be deleted by anything else,
  7357. and make sure it's not already the child of another element.
  7358. @see getFirstChildElement, getNextElement, getNumChildElements,
  7359. getChildElement, removeChildElement
  7360. */
  7361. void addChildElement (XmlElement* const newChildElement) throw();
  7362. /** Inserts an element into this element's list of children.
  7363. Child elements are deleted automatically when their parent is deleted, so
  7364. make sure the object that you pass in will not be deleted by anything else,
  7365. and make sure it's not already the child of another element.
  7366. @param newChildNode the element to add
  7367. @param indexToInsertAt the index at which to insert the new element - if this is
  7368. below zero, it will be added to the end of the list
  7369. @see addChildElement, insertChildElement
  7370. */
  7371. void insertChildElement (XmlElement* newChildNode,
  7372. int indexToInsertAt) throw();
  7373. /** Creates a new element with the given name and returns it, after adding it
  7374. as a child element.
  7375. This is a handy method that means that instead of writing this:
  7376. @code
  7377. XmlElement* newElement = new XmlElement ("foobar");
  7378. myParentElement->addChildElement (newElement);
  7379. @endcode
  7380. ..you could just write this:
  7381. @code
  7382. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  7383. @endcode
  7384. */
  7385. XmlElement* createNewChildElement (const String& tagName);
  7386. /** Replaces one of this element's children with another node.
  7387. If the current element passed-in isn't actually a child of this element,
  7388. this will return false and the new one won't be added. Otherwise, the
  7389. existing element will be deleted, replaced with the new one, and it
  7390. will return true.
  7391. */
  7392. bool replaceChildElement (XmlElement* currentChildElement,
  7393. XmlElement* newChildNode) throw();
  7394. /** Removes a child element.
  7395. @param childToRemove the child to look for and remove
  7396. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  7397. just remove it
  7398. */
  7399. void removeChildElement (XmlElement* childToRemove,
  7400. bool shouldDeleteTheChild) throw();
  7401. /** Deletes all the child elements in the element.
  7402. @see removeChildElement, deleteAllChildElementsWithTagName
  7403. */
  7404. void deleteAllChildElements() throw();
  7405. /** Deletes all the child elements with a given tag name.
  7406. @see removeChildElement
  7407. */
  7408. void deleteAllChildElementsWithTagName (const String& tagName) throw();
  7409. /** Returns true if the given element is a child of this one. */
  7410. bool containsChildElement (const XmlElement* const possibleChild) const throw();
  7411. /** Recursively searches all sub-elements to find one that contains the specified
  7412. child element.
  7413. */
  7414. XmlElement* findParentElementOf (const XmlElement* elementToLookFor) throw();
  7415. /** Sorts the child elements using a comparator.
  7416. This will use a comparator object to sort the elements into order. The object
  7417. passed must have a method of the form:
  7418. @code
  7419. int compareElements (const XmlElement* first, const XmlElement* second);
  7420. @endcode
  7421. ..and this method must return:
  7422. - a value of < 0 if the first comes before the second
  7423. - a value of 0 if the two objects are equivalent
  7424. - a value of > 0 if the second comes before the first
  7425. To improve performance, the compareElements() method can be declared as static or const.
  7426. @param comparator the comparator to use for comparing elements.
  7427. @param retainOrderOfEquivalentItems if this is true, then items
  7428. which the comparator says are equivalent will be
  7429. kept in the order in which they currently appear
  7430. in the array. This is slower to perform, but may
  7431. be important in some cases. If it's false, a faster
  7432. algorithm is used, but equivalent elements may be
  7433. rearranged.
  7434. */
  7435. template <class ElementComparator>
  7436. void sortChildElements (ElementComparator& comparator,
  7437. bool retainOrderOfEquivalentItems = false)
  7438. {
  7439. const int num = getNumChildElements();
  7440. if (num > 1)
  7441. {
  7442. HeapBlock <XmlElement*> elems (num);
  7443. getChildElementsAsArray (elems);
  7444. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  7445. reorderChildElements (elems, num);
  7446. }
  7447. }
  7448. /** Returns true if this element is a section of text.
  7449. Elements can either be an XML tag element or a secton of text, so this
  7450. is used to find out what kind of element this one is.
  7451. @see getAllText, addTextElement, deleteAllTextElements
  7452. */
  7453. bool isTextElement() const throw();
  7454. /** Returns the text for a text element.
  7455. Note that if you have an element like this:
  7456. @code<xyz>hello</xyz>@endcode
  7457. then calling getText on the "xyz" element won't return "hello", because that is
  7458. actually stored in a special text sub-element inside the xyz element. To get the
  7459. "hello" string, you could either call getText on the (unnamed) sub-element, or
  7460. use getAllSubText() to do this automatically.
  7461. @see isTextElement, getAllSubText, getChildElementAllSubText
  7462. */
  7463. const String& getText() const throw();
  7464. /** Sets the text in a text element.
  7465. Note that this is only a valid call if this element is a text element. If it's
  7466. not, then no action will be performed.
  7467. */
  7468. void setText (const String& newText);
  7469. /** Returns all the text from this element's child nodes.
  7470. This iterates all the child elements and when it finds text elements,
  7471. it concatenates their text into a big string which it returns.
  7472. E.g. @code<xyz> hello <x></x> there </xyz>@endcode
  7473. if you called getAllSubText on the "xyz" element, it'd return "hello there".
  7474. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  7475. */
  7476. const String getAllSubText() const;
  7477. /** Returns all the sub-text of a named child element.
  7478. If there is a child element with the given tag name, this will return
  7479. all of its sub-text (by calling getAllSubText() on it). If there is
  7480. no such child element, this will return the default string passed-in.
  7481. @see getAllSubText
  7482. */
  7483. const String getChildElementAllSubText (const String& childTagName,
  7484. const String& defaultReturnValue) const;
  7485. /** Appends a section of text to this element.
  7486. @see isTextElement, getText, getAllSubText
  7487. */
  7488. void addTextElement (const String& text);
  7489. /** Removes all the text elements from this element.
  7490. @see isTextElement, getText, getAllSubText, addTextElement
  7491. */
  7492. void deleteAllTextElements() throw();
  7493. /** Creates a text element that can be added to a parent element.
  7494. */
  7495. static XmlElement* createTextElement (const String& text);
  7496. juce_UseDebuggingNewOperator
  7497. private:
  7498. friend class XmlDocument;
  7499. String tagName;
  7500. XmlElement* firstChildElement;
  7501. XmlElement* nextElement;
  7502. struct XmlAttributeNode
  7503. {
  7504. XmlAttributeNode (const XmlAttributeNode& other) throw();
  7505. XmlAttributeNode (const String& name, const String& value) throw();
  7506. String name, value;
  7507. XmlAttributeNode* next;
  7508. private:
  7509. XmlAttributeNode& operator= (const XmlAttributeNode&);
  7510. };
  7511. XmlAttributeNode* attributes;
  7512. XmlElement (int) throw();
  7513. void copyChildrenAndAttributesFrom (const XmlElement& other);
  7514. void writeElementAsText (OutputStream& out, int indentationLevel, int lineWrapLength) const;
  7515. void getChildElementsAsArray (XmlElement**) const throw();
  7516. void reorderChildElements (XmlElement** const, const int) throw();
  7517. };
  7518. #endif // __JUCE_XMLELEMENT_JUCEHEADER__
  7519. /*** End of inlined file: juce_XmlElement.h ***/
  7520. /**
  7521. A set of named property values, which can be strings, integers, floating point, etc.
  7522. Effectively, this just wraps a StringPairArray in an interface that makes it easier
  7523. to load and save types other than strings.
  7524. See the PropertiesFile class for a subclass of this, which automatically broadcasts change
  7525. messages and saves/loads the list from a file.
  7526. */
  7527. class JUCE_API PropertySet
  7528. {
  7529. public:
  7530. /** Creates an empty PropertySet.
  7531. @param ignoreCaseOfKeyNames if true, the names of properties are compared in a
  7532. case-insensitive way
  7533. */
  7534. PropertySet (const bool ignoreCaseOfKeyNames = false) throw();
  7535. /** Creates a copy of another PropertySet.
  7536. */
  7537. PropertySet (const PropertySet& other) throw();
  7538. /** Copies another PropertySet over this one.
  7539. */
  7540. PropertySet& operator= (const PropertySet& other) throw();
  7541. /** Destructor. */
  7542. virtual ~PropertySet();
  7543. /** Returns one of the properties as a string.
  7544. If the value isn't found in this set, then this will look for it in a fallback
  7545. property set (if you've specified one with the setFallbackPropertySet() method),
  7546. and if it can't find one there, it'll return the default value passed-in.
  7547. @param keyName the name of the property to retrieve
  7548. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7549. */
  7550. const String getValue (const String& keyName,
  7551. const String& defaultReturnValue = String::empty) const throw();
  7552. /** Returns one of the properties as an integer.
  7553. If the value isn't found in this set, then this will look for it in a fallback
  7554. property set (if you've specified one with the setFallbackPropertySet() method),
  7555. and if it can't find one there, it'll return the default value passed-in.
  7556. @param keyName the name of the property to retrieve
  7557. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7558. */
  7559. int getIntValue (const String& keyName,
  7560. const int defaultReturnValue = 0) const throw();
  7561. /** Returns one of the properties as an double.
  7562. If the value isn't found in this set, then this will look for it in a fallback
  7563. property set (if you've specified one with the setFallbackPropertySet() method),
  7564. and if it can't find one there, it'll return the default value passed-in.
  7565. @param keyName the name of the property to retrieve
  7566. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7567. */
  7568. double getDoubleValue (const String& keyName,
  7569. const double defaultReturnValue = 0.0) const throw();
  7570. /** Returns one of the properties as an boolean.
  7571. The result will be true if the string found for this key name can be parsed as a non-zero
  7572. integer.
  7573. If the value isn't found in this set, then this will look for it in a fallback
  7574. property set (if you've specified one with the setFallbackPropertySet() method),
  7575. and if it can't find one there, it'll return the default value passed-in.
  7576. @param keyName the name of the property to retrieve
  7577. @param defaultReturnValue a value to return if the named property doesn't actually exist
  7578. */
  7579. bool getBoolValue (const String& keyName,
  7580. const bool defaultReturnValue = false) const throw();
  7581. /** Returns one of the properties as an XML element.
  7582. The result will a new XMLElement object that the caller must delete. If may return 0 if the
  7583. key isn't found, or if the entry contains an string that isn't valid XML.
  7584. If the value isn't found in this set, then this will look for it in a fallback
  7585. property set (if you've specified one with the setFallbackPropertySet() method),
  7586. and if it can't find one there, it'll return the default value passed-in.
  7587. @param keyName the name of the property to retrieve
  7588. */
  7589. XmlElement* getXmlValue (const String& keyName) const;
  7590. /** Sets a named property as a string.
  7591. @param keyName the name of the property to set. (This mustn't be an empty string)
  7592. @param value the new value to set it to
  7593. */
  7594. void setValue (const String& keyName, const String& value) throw();
  7595. /** Sets a named property to an integer.
  7596. @param keyName the name of the property to set. (This mustn't be an empty string)
  7597. @param value the new value to set it to
  7598. */
  7599. void setValue (const String& keyName, const int value) throw();
  7600. /** Sets a named property to a double.
  7601. @param keyName the name of the property to set. (This mustn't be an empty string)
  7602. @param value the new value to set it to
  7603. */
  7604. void setValue (const String& keyName, const double value) throw();
  7605. /** Sets a named property to a boolean.
  7606. @param keyName the name of the property to set. (This mustn't be an empty string)
  7607. @param value the new value to set it to
  7608. */
  7609. void setValue (const String& keyName, const bool value) throw();
  7610. /** Sets a named property to an XML element.
  7611. @param keyName the name of the property to set. (This mustn't be an empty string)
  7612. @param xml the new element to set it to. If this is zero, the value will be set to
  7613. an empty string
  7614. @see getXmlValue
  7615. */
  7616. void setValue (const String& keyName, const XmlElement* const xml);
  7617. /** Deletes a property.
  7618. @param keyName the name of the property to delete. (This mustn't be an empty string)
  7619. */
  7620. void removeValue (const String& keyName) throw();
  7621. /** Returns true if the properies include the given key. */
  7622. bool containsKey (const String& keyName) const throw();
  7623. /** Removes all values. */
  7624. void clear();
  7625. /** Returns the keys/value pair array containing all the properties. */
  7626. StringPairArray& getAllProperties() throw() { return properties; }
  7627. /** Returns the lock used when reading or writing to this set */
  7628. const CriticalSection& getLock() const throw() { return lock; }
  7629. /** Returns an XML element which encapsulates all the items in this property set.
  7630. The string parameter is the tag name that should be used for the node.
  7631. @see restoreFromXml
  7632. */
  7633. XmlElement* createXml (const String& nodeName) const throw();
  7634. /** Reloads a set of properties that were previously stored as XML.
  7635. The node passed in must have been created by the createXml() method.
  7636. @see createXml
  7637. */
  7638. void restoreFromXml (const XmlElement& xml) throw();
  7639. /** Sets up a second PopertySet that will be used to look up any values that aren't
  7640. set in this one.
  7641. If you set this up to be a pointer to a second property set, then whenever one
  7642. of the getValue() methods fails to find an entry in this set, it will look up that
  7643. value in the fallback set, and if it finds it, it will return that.
  7644. Make sure that you don't delete the fallback set while it's still being used by
  7645. another set! To remove the fallback set, just call this method with a null pointer.
  7646. @see getFallbackPropertySet
  7647. */
  7648. void setFallbackPropertySet (PropertySet* fallbackProperties) throw();
  7649. /** Returns the fallback property set.
  7650. @see setFallbackPropertySet
  7651. */
  7652. PropertySet* getFallbackPropertySet() const throw() { return fallbackProperties; }
  7653. juce_UseDebuggingNewOperator
  7654. protected:
  7655. /** Subclasses can override this to be told when one of the properies has been changed.
  7656. */
  7657. virtual void propertyChanged();
  7658. private:
  7659. StringPairArray properties;
  7660. PropertySet* fallbackProperties;
  7661. CriticalSection lock;
  7662. bool ignoreCaseOfKeys;
  7663. };
  7664. #endif // __JUCE_PROPERTYSET_JUCEHEADER__
  7665. /*** End of inlined file: juce_PropertySet.h ***/
  7666. #endif
  7667. #ifndef __JUCE_RANGE_JUCEHEADER__
  7668. /*** Start of inlined file: juce_Range.h ***/
  7669. #ifndef __JUCE_RANGE_JUCEHEADER__
  7670. #define __JUCE_RANGE_JUCEHEADER__
  7671. /** A general-purpose range object, that simply represents any linear range with
  7672. a start and end point.
  7673. The templated parameter is expected to be a primitive integer or floating point
  7674. type, though class types could also be used if they behave in a number-like way.
  7675. */
  7676. template <typename ValueType>
  7677. class Range
  7678. {
  7679. public:
  7680. /** Constructs an empty range. */
  7681. Range() throw()
  7682. : start (ValueType()), end (ValueType())
  7683. {
  7684. }
  7685. /** Constructs a range with given start and end values. */
  7686. Range (const ValueType start_, const ValueType end_) throw()
  7687. : start (start_), end (jmax (start_, end_))
  7688. {
  7689. }
  7690. /** Constructs a copy of another range. */
  7691. Range (const Range& other) throw()
  7692. : start (other.start), end (other.end)
  7693. {
  7694. }
  7695. /** Copies another range object. */
  7696. Range& operator= (const Range& other) throw()
  7697. {
  7698. start = other.start;
  7699. end = other.end;
  7700. return *this;
  7701. }
  7702. /** Destructor. */
  7703. ~Range() throw()
  7704. {
  7705. }
  7706. /** Returns the range that lies between two positions (in either order). */
  7707. static const Range between (const ValueType position1, const ValueType position2) throw()
  7708. {
  7709. return (position1 < position2) ? Range (position1, position2)
  7710. : Range (position2, position1);
  7711. }
  7712. /** Returns a range with the specified start position and a length of zero. */
  7713. static const Range emptyRange (const ValueType start) throw()
  7714. {
  7715. return Range (start, start);
  7716. }
  7717. /** Returns the start of the range. */
  7718. inline ValueType getStart() const throw() { return start; }
  7719. /** Returns the length of the range. */
  7720. inline ValueType getLength() const throw() { return end - start; }
  7721. /** Returns the end of the range. */
  7722. inline ValueType getEnd() const throw() { return end; }
  7723. /** Returns true if the range has a length of zero. */
  7724. inline bool isEmpty() const throw() { return start == end; }
  7725. /** Changes the start position of the range, leaving the end position unchanged.
  7726. If the new start position is higher than the current end of the range, the end point
  7727. will be pushed along to equal it, leaving an empty range at the new position.
  7728. */
  7729. void setStart (const ValueType newStart) throw()
  7730. {
  7731. start = newStart;
  7732. if (end < newStart)
  7733. end = newStart;
  7734. }
  7735. /** Returns a range with the same end as this one, but a different start.
  7736. If the new start position is higher than the current end of the range, the end point
  7737. will be pushed along to equal it, returning an empty range at the new position.
  7738. */
  7739. const Range withStart (const ValueType newStart) const throw()
  7740. {
  7741. return Range (newStart, jmax (newStart, end));
  7742. }
  7743. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7744. const Range movedToStartAt (const ValueType newStart) const throw()
  7745. {
  7746. return Range (newStart, newStart + getLength());
  7747. }
  7748. /** Changes the end position of the range, leaving the start unchanged.
  7749. If the new end position is below the current start of the range, the start point
  7750. will be pushed back to equal the new end point.
  7751. */
  7752. void setEnd (const ValueType newEnd) throw()
  7753. {
  7754. end = newEnd;
  7755. if (newEnd < start)
  7756. start = newEnd;
  7757. }
  7758. /** Returns a range with the same start position as this one, but a different end.
  7759. If the new end position is below the current start of the range, the start point
  7760. will be pushed back to equal the new end point.
  7761. */
  7762. const Range withEnd (const ValueType newEnd) const throw()
  7763. {
  7764. return Range (jmin (start, newEnd), newEnd);
  7765. }
  7766. /** Returns a range with the same length as this one, but moved to have the given start position. */
  7767. const Range movedToEndAt (const ValueType newEnd) const throw()
  7768. {
  7769. return Range (newEnd - getLength(), newEnd);
  7770. }
  7771. /** Changes the length of the range.
  7772. Lengths less than zero are treated as zero.
  7773. */
  7774. void setLength (const ValueType newLength) throw()
  7775. {
  7776. end = start + jmax (ValueType(), newLength);
  7777. }
  7778. /** Returns a range with the same start as this one, but a different length.
  7779. Lengths less than zero are treated as zero.
  7780. */
  7781. const Range withLength (const ValueType newLength) const throw()
  7782. {
  7783. return Range (start, start + newLength);
  7784. }
  7785. /** Adds an amount to the start and end of the range. */
  7786. inline const Range& operator+= (const ValueType amountToAdd) throw()
  7787. {
  7788. start += amountToAdd;
  7789. end += amountToAdd;
  7790. return *this;
  7791. }
  7792. /** Subtracts an amount from the start and end of the range. */
  7793. inline const Range& operator-= (const ValueType amountToSubtract) throw()
  7794. {
  7795. start -= amountToSubtract;
  7796. end -= amountToSubtract;
  7797. return *this;
  7798. }
  7799. /** Returns a range that is equal to this one with an amount added to its
  7800. start and end.
  7801. */
  7802. const Range operator+ (const ValueType amountToAdd) const throw()
  7803. {
  7804. return Range (start + amountToAdd, end + amountToAdd);
  7805. }
  7806. /** Returns a range that is equal to this one with the specified amount
  7807. subtracted from its start and end. */
  7808. const Range operator- (const ValueType amountToSubtract) const throw()
  7809. {
  7810. return Range (start - amountToSubtract, end - amountToSubtract);
  7811. }
  7812. bool operator== (const Range& other) const throw() { return start == other.start && end == other.end; }
  7813. bool operator!= (const Range& other) const throw() { return start != other.start || end != other.end; }
  7814. /** Returns true if the given position lies inside this range. */
  7815. bool contains (const ValueType position) const throw()
  7816. {
  7817. return start <= position && position < end;
  7818. }
  7819. /** Returns the nearest value to the one supplied, which lies within the range. */
  7820. ValueType clipValue (const ValueType value) const throw()
  7821. {
  7822. return jlimit (start, end, value);
  7823. }
  7824. /** Returns true if the given range lies entirely inside this range. */
  7825. bool contains (const Range& other) const throw()
  7826. {
  7827. return start <= other.start && end >= other.end;
  7828. }
  7829. /** Returns true if the given range intersects this one. */
  7830. bool intersects (const Range& other) const throw()
  7831. {
  7832. return other.start < end && start < other.end;
  7833. }
  7834. /** Returns the range that is the intersection of the two ranges, or an empty range
  7835. with an undefined start position if they don't overlap. */
  7836. const Range getIntersectionWith (const Range& other) const throw()
  7837. {
  7838. return Range (jmax (start, other.start),
  7839. jmin (end, other.end));
  7840. }
  7841. /** Returns the smallest range that contains both this one and the other one. */
  7842. const Range getUnionWith (const Range& other) const throw()
  7843. {
  7844. return Range (jmin (start, other.start),
  7845. jmax (end, other.end));
  7846. }
  7847. /** Returns a given range, after moving it forwards or backwards to fit it
  7848. within this range.
  7849. If the supplied range has a greater length than this one, the return value
  7850. will be this range.
  7851. Otherwise, if the supplied range is smaller than this one, the return value
  7852. will be the new range, shifted forwards or backwards so that it doesn't extend
  7853. beyond this one, but keeping its original length.
  7854. */
  7855. const Range constrainRange (const Range& rangeToConstrain) const throw()
  7856. {
  7857. const ValueType otherLen = rangeToConstrain.getLength();
  7858. return getLength() <= otherLen
  7859. ? *this
  7860. : rangeToConstrain.movedToStartAt (jlimit (start, end - otherLen, rangeToConstrain.getStart()));
  7861. }
  7862. juce_UseDebuggingNewOperator
  7863. private:
  7864. ValueType start, end;
  7865. };
  7866. #endif // __JUCE_RANGE_JUCEHEADER__
  7867. /*** End of inlined file: juce_Range.h ***/
  7868. #endif
  7869. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7870. /*** Start of inlined file: juce_ReferenceCountedArray.h ***/
  7871. #ifndef __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7872. #define __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  7873. /**
  7874. Holds a list of objects derived from ReferenceCountedObject.
  7875. A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
  7876. and takes care of incrementing and decrementing their ref counts when they
  7877. are added and removed from the array.
  7878. To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
  7879. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  7880. @see Array, OwnedArray, StringArray
  7881. */
  7882. template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  7883. class ReferenceCountedArray
  7884. {
  7885. public:
  7886. /** Creates an empty array.
  7887. @see ReferenceCountedObject, Array, OwnedArray
  7888. */
  7889. ReferenceCountedArray() throw()
  7890. : numUsed (0)
  7891. {
  7892. }
  7893. /** Creates a copy of another array */
  7894. ReferenceCountedArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7895. {
  7896. const ScopedLockType lock (other.getLock());
  7897. numUsed = other.numUsed;
  7898. data.setAllocatedSize (numUsed);
  7899. memcpy (data.elements, other.data.elements, numUsed * sizeof (ObjectClass*));
  7900. for (int i = numUsed; --i >= 0;)
  7901. if (data.elements[i] != 0)
  7902. data.elements[i]->incReferenceCount();
  7903. }
  7904. /** Copies another array into this one.
  7905. Any existing objects in this array will first be released.
  7906. */
  7907. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& operator= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) throw()
  7908. {
  7909. if (this != &other)
  7910. {
  7911. ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse> otherCopy (other);
  7912. swapWithArray (otherCopy);
  7913. }
  7914. return *this;
  7915. }
  7916. /** Destructor.
  7917. Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
  7918. */
  7919. ~ReferenceCountedArray()
  7920. {
  7921. clear();
  7922. }
  7923. /** Removes all objects from the array.
  7924. Any objects in the array that are not referenced from elsewhere will be deleted.
  7925. */
  7926. void clear()
  7927. {
  7928. const ScopedLockType lock (getLock());
  7929. while (numUsed > 0)
  7930. if (data.elements [--numUsed] != 0)
  7931. data.elements [numUsed]->decReferenceCount();
  7932. jassert (numUsed == 0);
  7933. data.setAllocatedSize (0);
  7934. }
  7935. /** Returns the current number of objects in the array. */
  7936. inline int size() const throw()
  7937. {
  7938. return numUsed;
  7939. }
  7940. /** Returns a pointer to the object at this index in the array.
  7941. If the index is out-of-range, this will return a null pointer, (and
  7942. it could be null anyway, because it's ok for the array to hold null
  7943. pointers as well as objects).
  7944. @see getUnchecked
  7945. */
  7946. inline const ReferenceCountedObjectPtr<ObjectClass> operator[] (const int index) const throw()
  7947. {
  7948. const ScopedLockType lock (getLock());
  7949. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  7950. : static_cast <ObjectClass*> (0);
  7951. }
  7952. /** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
  7953. This is a faster and less safe version of operator[] which doesn't check the index passed in, so
  7954. it can be used when you're sure the index if always going to be legal.
  7955. */
  7956. inline const ReferenceCountedObjectPtr<ObjectClass> getUnchecked (const int index) const throw()
  7957. {
  7958. const ScopedLockType lock (getLock());
  7959. jassert (((unsigned int) index) < (unsigned int) numUsed);
  7960. return data.elements [index];
  7961. }
  7962. /** Returns a pointer to the first object in the array.
  7963. This will return a null pointer if the array's empty.
  7964. @see getLast
  7965. */
  7966. inline const ReferenceCountedObjectPtr<ObjectClass> getFirst() const throw()
  7967. {
  7968. const ScopedLockType lock (getLock());
  7969. return numUsed > 0 ? data.elements [0]
  7970. : static_cast <ObjectClass*> (0);
  7971. }
  7972. /** Returns a pointer to the last object in the array.
  7973. This will return a null pointer if the array's empty.
  7974. @see getFirst
  7975. */
  7976. inline const ReferenceCountedObjectPtr<ObjectClass> getLast() const throw()
  7977. {
  7978. const ScopedLockType lock (getLock());
  7979. return numUsed > 0 ? data.elements [numUsed - 1]
  7980. : static_cast <ObjectClass*> (0);
  7981. }
  7982. /** Finds the index of the first occurrence of an object in the array.
  7983. @param objectToLookFor the object to look for
  7984. @returns the index at which the object was found, or -1 if it's not found
  7985. */
  7986. int indexOf (const ObjectClass* const objectToLookFor) const throw()
  7987. {
  7988. const ScopedLockType lock (getLock());
  7989. ObjectClass** e = data.elements.getData();
  7990. ObjectClass** const end = e + numUsed;
  7991. while (e != end)
  7992. {
  7993. if (objectToLookFor == *e)
  7994. return static_cast <int> (e - data.elements.getData());
  7995. ++e;
  7996. }
  7997. return -1;
  7998. }
  7999. /** Returns true if the array contains a specified object.
  8000. @param objectToLookFor the object to look for
  8001. @returns true if the object is in the array
  8002. */
  8003. bool contains (const ObjectClass* const objectToLookFor) const throw()
  8004. {
  8005. const ScopedLockType lock (getLock());
  8006. ObjectClass** e = data.elements.getData();
  8007. ObjectClass** const end = e + numUsed;
  8008. while (e != end)
  8009. {
  8010. if (objectToLookFor == *e)
  8011. return true;
  8012. ++e;
  8013. }
  8014. return false;
  8015. }
  8016. /** Appends a new object to the end of the array.
  8017. This will increase the new object's reference count.
  8018. @param newObject the new object to add to the array
  8019. @see set, insert, addIfNotAlreadyThere, addSorted, addArray
  8020. */
  8021. void add (ObjectClass* const newObject) throw()
  8022. {
  8023. const ScopedLockType lock (getLock());
  8024. data.ensureAllocatedSize (numUsed + 1);
  8025. data.elements [numUsed++] = newObject;
  8026. if (newObject != 0)
  8027. newObject->incReferenceCount();
  8028. }
  8029. /** Inserts a new object into the array at the given index.
  8030. If the index is less than 0 or greater than the size of the array, the
  8031. element will be added to the end of the array.
  8032. Otherwise, it will be inserted into the array, moving all the later elements
  8033. along to make room.
  8034. This will increase the new object's reference count.
  8035. @param indexToInsertAt the index at which the new element should be inserted
  8036. @param newObject the new object to add to the array
  8037. @see add, addSorted, addIfNotAlreadyThere, set
  8038. */
  8039. void insert (int indexToInsertAt,
  8040. ObjectClass* const newObject) throw()
  8041. {
  8042. if (indexToInsertAt >= 0)
  8043. {
  8044. const ScopedLockType lock (getLock());
  8045. if (indexToInsertAt > numUsed)
  8046. indexToInsertAt = numUsed;
  8047. data.ensureAllocatedSize (numUsed + 1);
  8048. ObjectClass** const e = data.elements + indexToInsertAt;
  8049. const int numToMove = numUsed - indexToInsertAt;
  8050. if (numToMove > 0)
  8051. memmove (e + 1, e, numToMove * sizeof (ObjectClass*));
  8052. *e = newObject;
  8053. if (newObject != 0)
  8054. newObject->incReferenceCount();
  8055. ++numUsed;
  8056. }
  8057. else
  8058. {
  8059. add (newObject);
  8060. }
  8061. }
  8062. /** Appends a new object at the end of the array as long as the array doesn't
  8063. already contain it.
  8064. If the array already contains a matching object, nothing will be done.
  8065. @param newObject the new object to add to the array
  8066. */
  8067. void addIfNotAlreadyThere (ObjectClass* const newObject) throw()
  8068. {
  8069. const ScopedLockType lock (getLock());
  8070. if (! contains (newObject))
  8071. add (newObject);
  8072. }
  8073. /** Replaces an object in the array with a different one.
  8074. If the index is less than zero, this method does nothing.
  8075. If the index is beyond the end of the array, the new object is added to the end of the array.
  8076. The object being added has its reference count increased, and if it's replacing
  8077. another object, then that one has its reference count decreased, and may be deleted.
  8078. @param indexToChange the index whose value you want to change
  8079. @param newObject the new value to set for this index.
  8080. @see add, insert, remove
  8081. */
  8082. void set (const int indexToChange,
  8083. ObjectClass* const newObject)
  8084. {
  8085. if (indexToChange >= 0)
  8086. {
  8087. const ScopedLockType lock (getLock());
  8088. if (newObject != 0)
  8089. newObject->incReferenceCount();
  8090. if (indexToChange < numUsed)
  8091. {
  8092. if (data.elements [indexToChange] != 0)
  8093. data.elements [indexToChange]->decReferenceCount();
  8094. data.elements [indexToChange] = newObject;
  8095. }
  8096. else
  8097. {
  8098. data.ensureAllocatedSize (numUsed + 1);
  8099. data.elements [numUsed++] = newObject;
  8100. }
  8101. }
  8102. }
  8103. /** Adds elements from another array to the end of this array.
  8104. @param arrayToAddFrom the array from which to copy the elements
  8105. @param startIndex the first element of the other array to start copying from
  8106. @param numElementsToAdd how many elements to add from the other array. If this
  8107. value is negative or greater than the number of available elements,
  8108. all available elements will be copied.
  8109. @see add
  8110. */
  8111. void addArray (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& arrayToAddFrom,
  8112. int startIndex = 0,
  8113. int numElementsToAdd = -1) throw()
  8114. {
  8115. arrayToAddFrom.lockArray();
  8116. const ScopedLockType lock (getLock());
  8117. if (startIndex < 0)
  8118. {
  8119. jassertfalse;
  8120. startIndex = 0;
  8121. }
  8122. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
  8123. numElementsToAdd = arrayToAddFrom.size() - startIndex;
  8124. if (numElementsToAdd > 0)
  8125. {
  8126. data.ensureAllocatedSize (numUsed + numElementsToAdd);
  8127. while (--numElementsToAdd >= 0)
  8128. add (arrayToAddFrom.getUnchecked (startIndex++));
  8129. }
  8130. arrayToAddFrom.unlockArray();
  8131. }
  8132. /** Inserts a new object into the array assuming that the array is sorted.
  8133. This will use a comparator to find the position at which the new object
  8134. should go. If the array isn't sorted, the behaviour of this
  8135. method will be unpredictable.
  8136. @param comparator the comparator object to use to compare the elements - see the
  8137. sort() method for details about this object's form
  8138. @param newObject the new object to insert to the array
  8139. @see add, sort
  8140. */
  8141. template <class ElementComparator>
  8142. void addSorted (ElementComparator& comparator,
  8143. ObjectClass* newObject) throw()
  8144. {
  8145. const ScopedLockType lock (getLock());
  8146. insert (findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed), newObject);
  8147. }
  8148. /** Inserts or replaces an object in the array, assuming it is sorted.
  8149. This is similar to addSorted, but if a matching element already exists, then it will be
  8150. replaced by the new one, rather than the new one being added as well.
  8151. */
  8152. template <class ElementComparator>
  8153. void addOrReplaceSorted (ElementComparator& comparator,
  8154. ObjectClass* newObject) throw()
  8155. {
  8156. const ScopedLockType lock (getLock());
  8157. const int index = findInsertIndexInSortedArray (comparator, data.elements.getData(), newObject, 0, numUsed);
  8158. if (index > 0 && comparator.compareElements (newObject, data.elements [index - 1]) == 0)
  8159. set (index - 1, newObject); // replace an existing object that matches
  8160. else
  8161. insert (index, newObject); // no match, so insert the new one
  8162. }
  8163. /** Removes an object from the array.
  8164. This will remove the object at a given index and move back all the
  8165. subsequent objects to close the gap.
  8166. If the index passed in is out-of-range, nothing will happen.
  8167. The object that is removed will have its reference count decreased,
  8168. and may be deleted if not referenced from elsewhere.
  8169. @param indexToRemove the index of the element to remove
  8170. @see removeObject, removeRange
  8171. */
  8172. void remove (const int indexToRemove)
  8173. {
  8174. const ScopedLockType lock (getLock());
  8175. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8176. {
  8177. ObjectClass** const e = data.elements + indexToRemove;
  8178. if (*e != 0)
  8179. (*e)->decReferenceCount();
  8180. --numUsed;
  8181. const int numberToShift = numUsed - indexToRemove;
  8182. if (numberToShift > 0)
  8183. memmove (e, e + 1, numberToShift * sizeof (ObjectClass*));
  8184. if ((numUsed << 1) < data.numAllocated)
  8185. minimiseStorageOverheads();
  8186. }
  8187. }
  8188. /** Removes the first occurrence of a specified object from the array.
  8189. If the item isn't found, no action is taken. If it is found, it is
  8190. removed and has its reference count decreased.
  8191. @param objectToRemove the object to try to remove
  8192. @see remove, removeRange
  8193. */
  8194. void removeObject (ObjectClass* const objectToRemove)
  8195. {
  8196. const ScopedLockType lock (getLock());
  8197. remove (indexOf (objectToRemove));
  8198. }
  8199. /** Removes a range of objects from the array.
  8200. This will remove a set of objects, starting from the given index,
  8201. and move any subsequent elements down to close the gap.
  8202. If the range extends beyond the bounds of the array, it will
  8203. be safely clipped to the size of the array.
  8204. The objects that are removed will have their reference counts decreased,
  8205. and may be deleted if not referenced from elsewhere.
  8206. @param startIndex the index of the first object to remove
  8207. @param numberToRemove how many objects should be removed
  8208. @see remove, removeObject
  8209. */
  8210. void removeRange (const int startIndex,
  8211. const int numberToRemove)
  8212. {
  8213. const ScopedLockType lock (getLock());
  8214. const int start = jlimit (0, numUsed, startIndex);
  8215. const int end = jlimit (0, numUsed, startIndex + numberToRemove);
  8216. if (end > start)
  8217. {
  8218. int i;
  8219. for (i = start; i < end; ++i)
  8220. {
  8221. if (data.elements[i] != 0)
  8222. {
  8223. data.elements[i]->decReferenceCount();
  8224. data.elements[i] = 0; // (in case one of the destructors accesses this array and hits a dangling pointer)
  8225. }
  8226. }
  8227. const int rangeSize = end - start;
  8228. ObjectClass** e = data.elements + start;
  8229. i = numUsed - end;
  8230. numUsed -= rangeSize;
  8231. while (--i >= 0)
  8232. {
  8233. *e = e [rangeSize];
  8234. ++e;
  8235. }
  8236. if ((numUsed << 1) < data.numAllocated)
  8237. minimiseStorageOverheads();
  8238. }
  8239. }
  8240. /** Removes the last n objects from the array.
  8241. The objects that are removed will have their reference counts decreased,
  8242. and may be deleted if not referenced from elsewhere.
  8243. @param howManyToRemove how many objects to remove from the end of the array
  8244. @see remove, removeObject, removeRange
  8245. */
  8246. void removeLast (int howManyToRemove = 1)
  8247. {
  8248. const ScopedLockType lock (getLock());
  8249. if (howManyToRemove > numUsed)
  8250. howManyToRemove = numUsed;
  8251. while (--howManyToRemove >= 0)
  8252. remove (numUsed - 1);
  8253. }
  8254. /** Swaps a pair of objects in the array.
  8255. If either of the indexes passed in is out-of-range, nothing will happen,
  8256. otherwise the two objects at these positions will be exchanged.
  8257. */
  8258. void swap (const int index1,
  8259. const int index2) throw()
  8260. {
  8261. const ScopedLockType lock (getLock());
  8262. if (((unsigned int) index1) < (unsigned int) numUsed
  8263. && ((unsigned int) index2) < (unsigned int) numUsed)
  8264. {
  8265. swapVariables (data.elements [index1],
  8266. data.elements [index2]);
  8267. }
  8268. }
  8269. /** Moves one of the objects to a different position.
  8270. This will move the object to a specified index, shuffling along
  8271. any intervening elements as required.
  8272. So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
  8273. move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  8274. @param currentIndex the index of the object to be moved. If this isn't a
  8275. valid index, then nothing will be done
  8276. @param newIndex the index at which you'd like this object to end up. If this
  8277. is less than zero, it will be moved to the end of the array
  8278. */
  8279. void move (const int currentIndex,
  8280. int newIndex) throw()
  8281. {
  8282. if (currentIndex != newIndex)
  8283. {
  8284. const ScopedLockType lock (getLock());
  8285. if (((unsigned int) currentIndex) < (unsigned int) numUsed)
  8286. {
  8287. if (((unsigned int) newIndex) >= (unsigned int) numUsed)
  8288. newIndex = numUsed - 1;
  8289. ObjectClass* const value = data.elements [currentIndex];
  8290. if (newIndex > currentIndex)
  8291. {
  8292. memmove (data.elements + currentIndex,
  8293. data.elements + currentIndex + 1,
  8294. (newIndex - currentIndex) * sizeof (ObjectClass*));
  8295. }
  8296. else
  8297. {
  8298. memmove (data.elements + newIndex + 1,
  8299. data.elements + newIndex,
  8300. (currentIndex - newIndex) * sizeof (ObjectClass*));
  8301. }
  8302. data.elements [newIndex] = value;
  8303. }
  8304. }
  8305. }
  8306. /** This swaps the contents of this array with those of another array.
  8307. If you need to exchange two arrays, this is vastly quicker than using copy-by-value
  8308. because it just swaps their internal pointers.
  8309. */
  8310. void swapWithArray (ReferenceCountedArray& otherArray) throw()
  8311. {
  8312. const ScopedLockType lock1 (getLock());
  8313. const ScopedLockType lock2 (otherArray.getLock());
  8314. data.swapWith (otherArray.data);
  8315. swapVariables (numUsed, otherArray.numUsed);
  8316. }
  8317. /** Compares this array to another one.
  8318. @returns true only if the other array contains the same objects in the same order
  8319. */
  8320. bool operator== (const ReferenceCountedArray& other) const throw()
  8321. {
  8322. const ScopedLockType lock2 (other.getLock());
  8323. const ScopedLockType lock1 (getLock());
  8324. if (numUsed != other.numUsed)
  8325. return false;
  8326. for (int i = numUsed; --i >= 0;)
  8327. if (data.elements [i] != other.data.elements [i])
  8328. return false;
  8329. return true;
  8330. }
  8331. /** Compares this array to another one.
  8332. @see operator==
  8333. */
  8334. bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const throw()
  8335. {
  8336. return ! operator== (other);
  8337. }
  8338. /** Sorts the elements in the array.
  8339. This will use a comparator object to sort the elements into order. The object
  8340. passed must have a method of the form:
  8341. @code
  8342. int compareElements (ElementType first, ElementType second);
  8343. @endcode
  8344. ..and this method must return:
  8345. - a value of < 0 if the first comes before the second
  8346. - a value of 0 if the two objects are equivalent
  8347. - a value of > 0 if the second comes before the first
  8348. To improve performance, the compareElements() method can be declared as static or const.
  8349. @param comparator the comparator to use for comparing elements.
  8350. @param retainOrderOfEquivalentItems if this is true, then items
  8351. which the comparator says are equivalent will be
  8352. kept in the order in which they currently appear
  8353. in the array. This is slower to perform, but may
  8354. be important in some cases. If it's false, a faster
  8355. algorithm is used, but equivalent elements may be
  8356. rearranged.
  8357. @see sortArray
  8358. */
  8359. template <class ElementComparator>
  8360. void sort (ElementComparator& comparator,
  8361. const bool retainOrderOfEquivalentItems = false) const throw()
  8362. {
  8363. (void) comparator; // if you pass in an object with a static compareElements() method, this
  8364. // avoids getting warning messages about the parameter being unused
  8365. const ScopedLockType lock (getLock());
  8366. sortArray (comparator, data.elements.getData(), 0, size() - 1, retainOrderOfEquivalentItems);
  8367. }
  8368. /** Reduces the amount of storage being used by the array.
  8369. Arrays typically allocate slightly more storage than they need, and after
  8370. removing elements, they may have quite a lot of unused space allocated.
  8371. This method will reduce the amount of allocated storage to a minimum.
  8372. */
  8373. void minimiseStorageOverheads() throw()
  8374. {
  8375. const ScopedLockType lock (getLock());
  8376. data.shrinkToNoMoreThan (numUsed);
  8377. }
  8378. /** Returns the CriticalSection that locks this array.
  8379. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8380. an object of ScopedLockType as an RAII lock for it.
  8381. */
  8382. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8383. /** Returns the type of scoped lock to use for locking this array */
  8384. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8385. juce_UseDebuggingNewOperator
  8386. private:
  8387. ArrayAllocationBase <ObjectClass*, TypeOfCriticalSectionToUse> data;
  8388. int numUsed;
  8389. };
  8390. #endif // __JUCE_REFERENCECOUNTEDARRAY_JUCEHEADER__
  8391. /*** End of inlined file: juce_ReferenceCountedArray.h ***/
  8392. #endif
  8393. #ifndef __JUCE_REFERENCECOUNTEDOBJECT_JUCEHEADER__
  8394. #endif
  8395. #ifndef __JUCE_SCOPEDPOINTER_JUCEHEADER__
  8396. #endif
  8397. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8398. /*** Start of inlined file: juce_SortedSet.h ***/
  8399. #ifndef __JUCE_SORTEDSET_JUCEHEADER__
  8400. #define __JUCE_SORTEDSET_JUCEHEADER__
  8401. #if JUCE_MSVC
  8402. #pragma warning (push)
  8403. #pragma warning (disable: 4512)
  8404. #endif
  8405. /**
  8406. Holds a set of unique primitive objects, such as ints or doubles.
  8407. A set can only hold one item with a given value, so if for example it's a
  8408. set of integers, attempting to add the same integer twice will do nothing
  8409. the second time.
  8410. Internally, the list of items is kept sorted (which means that whatever
  8411. kind of primitive type is used must support the ==, <, >, <= and >= operators
  8412. to determine the order), and searching the set for known values is very fast
  8413. because it uses a binary-chop method.
  8414. Note that if you're using a class or struct as the element type, it must be
  8415. capable of being copied or moved with a straightforward memcpy, rather than
  8416. needing construction and destruction code.
  8417. To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
  8418. TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
  8419. @see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
  8420. */
  8421. template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
  8422. class SortedSet
  8423. {
  8424. public:
  8425. /** Creates an empty set. */
  8426. SortedSet() throw()
  8427. : numUsed (0)
  8428. {
  8429. }
  8430. /** Creates a copy of another set.
  8431. @param other the set to copy
  8432. */
  8433. SortedSet (const SortedSet& other) throw()
  8434. {
  8435. const ScopedLockType lock (other.getLock());
  8436. numUsed = other.numUsed;
  8437. data.setAllocatedSize (other.numUsed);
  8438. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8439. }
  8440. /** Destructor. */
  8441. ~SortedSet() throw()
  8442. {
  8443. }
  8444. /** Copies another set over this one.
  8445. @param other the set to copy
  8446. */
  8447. SortedSet& operator= (const SortedSet& other) throw()
  8448. {
  8449. if (this != &other)
  8450. {
  8451. const ScopedLockType lock1 (other.getLock());
  8452. const ScopedLockType lock2 (getLock());
  8453. data.ensureAllocatedSize (other.size());
  8454. numUsed = other.numUsed;
  8455. memcpy (data.elements, other.data.elements, numUsed * sizeof (ElementType));
  8456. minimiseStorageOverheads();
  8457. }
  8458. return *this;
  8459. }
  8460. /** Compares this set to another one.
  8461. Two sets are considered equal if they both contain the same set of
  8462. elements.
  8463. @param other the other set to compare with
  8464. */
  8465. bool operator== (const SortedSet<ElementType>& other) const throw()
  8466. {
  8467. const ScopedLockType lock (getLock());
  8468. if (numUsed != other.numUsed)
  8469. return false;
  8470. for (int i = numUsed; --i >= 0;)
  8471. if (data.elements[i] != other.data.elements[i])
  8472. return false;
  8473. return true;
  8474. }
  8475. /** Compares this set to another one.
  8476. Two sets are considered equal if they both contain the same set of
  8477. elements.
  8478. @param other the other set to compare with
  8479. */
  8480. bool operator!= (const SortedSet<ElementType>& other) const throw()
  8481. {
  8482. return ! operator== (other);
  8483. }
  8484. /** Removes all elements from the set.
  8485. This will remove all the elements, and free any storage that the set is
  8486. using. To clear it without freeing the storage, use the clearQuick()
  8487. method instead.
  8488. @see clearQuick
  8489. */
  8490. void clear() throw()
  8491. {
  8492. const ScopedLockType lock (getLock());
  8493. data.setAllocatedSize (0);
  8494. numUsed = 0;
  8495. }
  8496. /** Removes all elements from the set without freeing the array's allocated storage.
  8497. @see clear
  8498. */
  8499. void clearQuick() throw()
  8500. {
  8501. const ScopedLockType lock (getLock());
  8502. numUsed = 0;
  8503. }
  8504. /** Returns the current number of elements in the set.
  8505. */
  8506. inline int size() const throw()
  8507. {
  8508. return numUsed;
  8509. }
  8510. /** Returns one of the elements in the set.
  8511. If the index passed in is beyond the range of valid elements, this
  8512. will return zero.
  8513. If you're certain that the index will always be a valid element, you
  8514. can call getUnchecked() instead, which is faster.
  8515. @param index the index of the element being requested (0 is the first element in the set)
  8516. @see getUnchecked, getFirst, getLast
  8517. */
  8518. inline ElementType operator[] (const int index) const throw()
  8519. {
  8520. const ScopedLockType lock (getLock());
  8521. return (((unsigned int) index) < (unsigned int) numUsed) ? data.elements [index]
  8522. : ElementType();
  8523. }
  8524. /** Returns one of the elements in the set, without checking the index passed in.
  8525. Unlike the operator[] method, this will try to return an element without
  8526. checking that the index is within the bounds of the set, so should only
  8527. be used when you're confident that it will always be a valid index.
  8528. @param index the index of the element being requested (0 is the first element in the set)
  8529. @see operator[], getFirst, getLast
  8530. */
  8531. inline ElementType getUnchecked (const int index) const throw()
  8532. {
  8533. const ScopedLockType lock (getLock());
  8534. jassert (((unsigned int) index) < (unsigned int) numUsed);
  8535. return data.elements [index];
  8536. }
  8537. /** Returns the first element in the set, or 0 if the set is empty.
  8538. @see operator[], getUnchecked, getLast
  8539. */
  8540. inline ElementType getFirst() const throw()
  8541. {
  8542. const ScopedLockType lock (getLock());
  8543. return numUsed > 0 ? data.elements [0] : ElementType();
  8544. }
  8545. /** Returns the last element in the set, or 0 if the set is empty.
  8546. @see operator[], getUnchecked, getFirst
  8547. */
  8548. inline ElementType getLast() const throw()
  8549. {
  8550. const ScopedLockType lock (getLock());
  8551. return numUsed > 0 ? data.elements [numUsed - 1] : ElementType();
  8552. }
  8553. /** Finds the index of the first element which matches the value passed in.
  8554. This will search the set for the given object, and return the index
  8555. of its first occurrence. If the object isn't found, the method will return -1.
  8556. @param elementToLookFor the value or object to look for
  8557. @returns the index of the object, or -1 if it's not found
  8558. */
  8559. int indexOf (const ElementType elementToLookFor) const throw()
  8560. {
  8561. const ScopedLockType lock (getLock());
  8562. int start = 0;
  8563. int end = numUsed;
  8564. for (;;)
  8565. {
  8566. if (start >= end)
  8567. {
  8568. return -1;
  8569. }
  8570. else if (elementToLookFor == data.elements [start])
  8571. {
  8572. return start;
  8573. }
  8574. else
  8575. {
  8576. const int halfway = (start + end) >> 1;
  8577. if (halfway == start)
  8578. return -1;
  8579. else if (elementToLookFor >= data.elements [halfway])
  8580. start = halfway;
  8581. else
  8582. end = halfway;
  8583. }
  8584. }
  8585. }
  8586. /** Returns true if the set contains at least one occurrence of an object.
  8587. @param elementToLookFor the value or object to look for
  8588. @returns true if the item is found
  8589. */
  8590. bool contains (const ElementType elementToLookFor) const throw()
  8591. {
  8592. const ScopedLockType lock (getLock());
  8593. int start = 0;
  8594. int end = numUsed;
  8595. for (;;)
  8596. {
  8597. if (start >= end)
  8598. {
  8599. return false;
  8600. }
  8601. else if (elementToLookFor == data.elements [start])
  8602. {
  8603. return true;
  8604. }
  8605. else
  8606. {
  8607. const int halfway = (start + end) >> 1;
  8608. if (halfway == start)
  8609. return false;
  8610. else if (elementToLookFor >= data.elements [halfway])
  8611. start = halfway;
  8612. else
  8613. end = halfway;
  8614. }
  8615. }
  8616. }
  8617. /** Adds a new element to the set, (as long as it's not already in there).
  8618. @param newElement the new object to add to the set
  8619. @see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
  8620. */
  8621. void add (const ElementType newElement) throw()
  8622. {
  8623. const ScopedLockType lock (getLock());
  8624. int start = 0;
  8625. int end = numUsed;
  8626. for (;;)
  8627. {
  8628. if (start >= end)
  8629. {
  8630. jassert (start <= end);
  8631. insertInternal (start, newElement);
  8632. break;
  8633. }
  8634. else if (newElement == data.elements [start])
  8635. {
  8636. break;
  8637. }
  8638. else
  8639. {
  8640. const int halfway = (start + end) >> 1;
  8641. if (halfway == start)
  8642. {
  8643. if (newElement >= data.elements [halfway])
  8644. insertInternal (start + 1, newElement);
  8645. else
  8646. insertInternal (start, newElement);
  8647. break;
  8648. }
  8649. else if (newElement >= data.elements [halfway])
  8650. start = halfway;
  8651. else
  8652. end = halfway;
  8653. }
  8654. }
  8655. }
  8656. /** Adds elements from an array to this set.
  8657. @param elementsToAdd the array of elements to add
  8658. @param numElementsToAdd how many elements are in this other array
  8659. @see add
  8660. */
  8661. void addArray (const ElementType* elementsToAdd,
  8662. int numElementsToAdd) throw()
  8663. {
  8664. const ScopedLockType lock (getLock());
  8665. while (--numElementsToAdd >= 0)
  8666. add (*elementsToAdd++);
  8667. }
  8668. /** Adds elements from another set to this one.
  8669. @param setToAddFrom the set from which to copy the elements
  8670. @param startIndex the first element of the other set to start copying from
  8671. @param numElementsToAdd how many elements to add from the other set. If this
  8672. value is negative or greater than the number of available elements,
  8673. all available elements will be copied.
  8674. @see add
  8675. */
  8676. template <class OtherSetType>
  8677. void addSet (const OtherSetType& setToAddFrom,
  8678. int startIndex = 0,
  8679. int numElementsToAdd = -1) throw()
  8680. {
  8681. const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
  8682. const ScopedLockType lock2 (getLock());
  8683. jassert (this != &setToAddFrom);
  8684. if (this != &setToAddFrom)
  8685. {
  8686. if (startIndex < 0)
  8687. {
  8688. jassertfalse;
  8689. startIndex = 0;
  8690. }
  8691. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
  8692. numElementsToAdd = setToAddFrom.size() - startIndex;
  8693. addArray (setToAddFrom.elements + startIndex, numElementsToAdd);
  8694. }
  8695. }
  8696. /** Removes an element from the set.
  8697. This will remove the element at a given index.
  8698. If the index passed in is out-of-range, nothing will happen.
  8699. @param indexToRemove the index of the element to remove
  8700. @returns the element that has been removed
  8701. @see removeValue, removeRange
  8702. */
  8703. ElementType remove (const int indexToRemove) throw()
  8704. {
  8705. const ScopedLockType lock (getLock());
  8706. if (((unsigned int) indexToRemove) < (unsigned int) numUsed)
  8707. {
  8708. --numUsed;
  8709. ElementType* const e = data.elements + indexToRemove;
  8710. ElementType const removed = *e;
  8711. const int numberToShift = numUsed - indexToRemove;
  8712. if (numberToShift > 0)
  8713. memmove (e, e + 1, numberToShift * sizeof (ElementType));
  8714. if ((numUsed << 1) < data.numAllocated)
  8715. minimiseStorageOverheads();
  8716. return removed;
  8717. }
  8718. return 0;
  8719. }
  8720. /** Removes an item from the set.
  8721. This will remove the given element from the set, if it's there.
  8722. @param valueToRemove the object to try to remove
  8723. @see remove, removeRange
  8724. */
  8725. void removeValue (const ElementType valueToRemove) throw()
  8726. {
  8727. const ScopedLockType lock (getLock());
  8728. remove (indexOf (valueToRemove));
  8729. }
  8730. /** Removes any elements which are also in another set.
  8731. @param otherSet the other set in which to look for elements to remove
  8732. @see removeValuesNotIn, remove, removeValue, removeRange
  8733. */
  8734. template <class OtherSetType>
  8735. void removeValuesIn (const OtherSetType& otherSet) throw()
  8736. {
  8737. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8738. const ScopedLockType lock2 (getLock());
  8739. if (this == &otherSet)
  8740. {
  8741. clear();
  8742. }
  8743. else
  8744. {
  8745. if (otherSet.size() > 0)
  8746. {
  8747. for (int i = numUsed; --i >= 0;)
  8748. if (otherSet.contains (data.elements [i]))
  8749. remove (i);
  8750. }
  8751. }
  8752. }
  8753. /** Removes any elements which are not found in another set.
  8754. Only elements which occur in this other set will be retained.
  8755. @param otherSet the set in which to look for elements NOT to remove
  8756. @see removeValuesIn, remove, removeValue, removeRange
  8757. */
  8758. template <class OtherSetType>
  8759. void removeValuesNotIn (const OtherSetType& otherSet) throw()
  8760. {
  8761. const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
  8762. const ScopedLockType lock2 (getLock());
  8763. if (this != &otherSet)
  8764. {
  8765. if (otherSet.size() <= 0)
  8766. {
  8767. clear();
  8768. }
  8769. else
  8770. {
  8771. for (int i = numUsed; --i >= 0;)
  8772. if (! otherSet.contains (data.elements [i]))
  8773. remove (i);
  8774. }
  8775. }
  8776. }
  8777. /** Reduces the amount of storage being used by the set.
  8778. Sets typically allocate slightly more storage than they need, and after
  8779. removing elements, they may have quite a lot of unused space allocated.
  8780. This method will reduce the amount of allocated storage to a minimum.
  8781. */
  8782. void minimiseStorageOverheads() throw()
  8783. {
  8784. const ScopedLockType lock (getLock());
  8785. data.shrinkToNoMoreThan (numUsed);
  8786. }
  8787. /** Returns the CriticalSection that locks this array.
  8788. To lock, you can call getLock().enter() and getLock().exit(), or preferably use
  8789. an object of ScopedLockType as an RAII lock for it.
  8790. */
  8791. inline const TypeOfCriticalSectionToUse& getLock() const throw() { return data; }
  8792. /** Returns the type of scoped lock to use for locking this array */
  8793. typedef typename TypeOfCriticalSectionToUse::ScopedLockType ScopedLockType;
  8794. juce_UseDebuggingNewOperator
  8795. private:
  8796. ArrayAllocationBase <ElementType, TypeOfCriticalSectionToUse> data;
  8797. int numUsed;
  8798. void insertInternal (const int indexToInsertAt, const ElementType newElement) throw()
  8799. {
  8800. data.ensureAllocatedSize (numUsed + 1);
  8801. ElementType* const insertPos = data.elements + indexToInsertAt;
  8802. const int numberToMove = numUsed - indexToInsertAt;
  8803. if (numberToMove > 0)
  8804. memmove (insertPos + 1, insertPos, numberToMove * sizeof (ElementType));
  8805. *insertPos = newElement;
  8806. ++numUsed;
  8807. }
  8808. };
  8809. #if JUCE_MSVC
  8810. #pragma warning (pop)
  8811. #endif
  8812. #endif // __JUCE_SORTEDSET_JUCEHEADER__
  8813. /*** End of inlined file: juce_SortedSet.h ***/
  8814. #endif
  8815. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8816. /*** Start of inlined file: juce_SparseSet.h ***/
  8817. #ifndef __JUCE_SPARSESET_JUCEHEADER__
  8818. #define __JUCE_SPARSESET_JUCEHEADER__
  8819. /**
  8820. Holds a set of primitive values, storing them as a set of ranges.
  8821. This container acts like an array, but can efficiently hold large continguous
  8822. ranges of values. It's quite a specialised class, mostly useful for things
  8823. like keeping the set of selected rows in a listbox.
  8824. The type used as a template paramter must be an integer type, such as int, short,
  8825. int64, etc.
  8826. */
  8827. template <class Type>
  8828. class SparseSet
  8829. {
  8830. public:
  8831. /** Creates a new empty set. */
  8832. SparseSet()
  8833. {
  8834. }
  8835. /** Creates a copy of another SparseSet. */
  8836. SparseSet (const SparseSet<Type>& other)
  8837. : values (other.values)
  8838. {
  8839. }
  8840. /** Destructor. */
  8841. ~SparseSet()
  8842. {
  8843. }
  8844. /** Clears the set. */
  8845. void clear()
  8846. {
  8847. values.clear();
  8848. }
  8849. /** Checks whether the set is empty.
  8850. This is much quicker than using (size() == 0).
  8851. */
  8852. bool isEmpty() const throw()
  8853. {
  8854. return values.size() == 0;
  8855. }
  8856. /** Returns the number of values in the set.
  8857. Because of the way the data is stored, this method can take longer if there
  8858. are a lot of items in the set. Use isEmpty() for a quick test of whether there
  8859. are any items.
  8860. */
  8861. Type size() const
  8862. {
  8863. Type total (0);
  8864. for (int i = 0; i < values.size(); i += 2)
  8865. total += values.getUnchecked (i + 1) - values.getUnchecked (i);
  8866. return total;
  8867. }
  8868. /** Returns one of the values in the set.
  8869. @param index the index of the value to retrieve, in the range 0 to (size() - 1).
  8870. @returns the value at this index, or 0 if it's out-of-range
  8871. */
  8872. Type operator[] (Type index) const
  8873. {
  8874. for (int i = 0; i < values.size(); i += 2)
  8875. {
  8876. const Type start (values.getUnchecked (i));
  8877. const Type len (values.getUnchecked (i + 1) - start);
  8878. if (index < len)
  8879. return start + index;
  8880. index -= len;
  8881. }
  8882. return Type (0);
  8883. }
  8884. /** Checks whether a particular value is in the set. */
  8885. bool contains (const Type valueToLookFor) const
  8886. {
  8887. for (int i = 0; i < values.size(); ++i)
  8888. if (valueToLookFor < values.getUnchecked(i))
  8889. return (i & 1) != 0;
  8890. return false;
  8891. }
  8892. /** Returns the number of contiguous blocks of values.
  8893. @see getRange
  8894. */
  8895. int getNumRanges() const throw()
  8896. {
  8897. return values.size() >> 1;
  8898. }
  8899. /** Returns one of the contiguous ranges of values stored.
  8900. @param rangeIndex the index of the range to look up, between 0
  8901. and (getNumRanges() - 1)
  8902. @see getTotalRange
  8903. */
  8904. const Range<Type> getRange (const int rangeIndex) const
  8905. {
  8906. if (((unsigned int) rangeIndex) < (unsigned int) getNumRanges())
  8907. return Range<Type> (values.getUnchecked (rangeIndex << 1),
  8908. values.getUnchecked ((rangeIndex << 1) + 1));
  8909. else
  8910. return Range<Type>();
  8911. }
  8912. /** Returns the range between the lowest and highest values in the set.
  8913. @see getRange
  8914. */
  8915. const Range<Type> getTotalRange() const
  8916. {
  8917. if (values.size() > 0)
  8918. {
  8919. jassert ((values.size() & 1) == 0);
  8920. return Range<Type> (values.getUnchecked (0),
  8921. values.getUnchecked (values.size() - 1));
  8922. }
  8923. return Range<Type>();
  8924. }
  8925. /** Adds a range of contiguous values to the set.
  8926. e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
  8927. */
  8928. void addRange (const Range<Type>& range)
  8929. {
  8930. jassert (range.getLength() >= 0);
  8931. if (range.getLength() > 0)
  8932. {
  8933. removeRange (range);
  8934. values.addUsingDefaultSort (range.getStart());
  8935. values.addUsingDefaultSort (range.getEnd());
  8936. simplify();
  8937. }
  8938. }
  8939. /** Removes a range of values from the set.
  8940. e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
  8941. */
  8942. void removeRange (const Range<Type>& rangeToRemove)
  8943. {
  8944. jassert (rangeToRemove.getLength() >= 0);
  8945. if (rangeToRemove.getLength() > 0
  8946. && values.size() > 0
  8947. && rangeToRemove.getStart() < values.getUnchecked (values.size() - 1)
  8948. && values.getUnchecked(0) < rangeToRemove.getEnd())
  8949. {
  8950. const bool onAtStart = contains (rangeToRemove.getStart() - 1);
  8951. const Type lastValue (jmin (rangeToRemove.getEnd(), values.getLast()));
  8952. const bool onAtEnd = contains (lastValue);
  8953. for (int i = values.size(); --i >= 0;)
  8954. {
  8955. if (values.getUnchecked(i) <= lastValue)
  8956. {
  8957. while (values.getUnchecked(i) >= rangeToRemove.getStart())
  8958. {
  8959. values.remove (i);
  8960. if (--i < 0)
  8961. break;
  8962. }
  8963. break;
  8964. }
  8965. }
  8966. if (onAtStart) values.addUsingDefaultSort (rangeToRemove.getStart());
  8967. if (onAtEnd) values.addUsingDefaultSort (lastValue);
  8968. simplify();
  8969. }
  8970. }
  8971. /** Does an XOR of the values in a given range. */
  8972. void invertRange (const Range<Type>& range)
  8973. {
  8974. SparseSet newItems;
  8975. newItems.addRange (range);
  8976. int i;
  8977. for (i = getNumRanges(); --i >= 0;)
  8978. newItems.removeRange (getRange (i));
  8979. removeRange (range);
  8980. for (i = newItems.getNumRanges(); --i >= 0;)
  8981. addRange (newItems.getRange(i));
  8982. }
  8983. /** Checks whether any part of a given range overlaps any part of this set. */
  8984. bool overlapsRange (const Range<Type>& range)
  8985. {
  8986. if (range.getLength() > 0)
  8987. {
  8988. for (int i = getNumRanges(); --i >= 0;)
  8989. {
  8990. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  8991. return false;
  8992. if (values.getUnchecked (i << 1) < range.getEnd())
  8993. return true;
  8994. }
  8995. }
  8996. return false;
  8997. }
  8998. /** Checks whether the whole of a given range is contained within this one. */
  8999. bool containsRange (const Range<Type>& range)
  9000. {
  9001. if (range.getLength() > 0)
  9002. {
  9003. for (int i = getNumRanges(); --i >= 0;)
  9004. {
  9005. if (values.getUnchecked ((i << 1) + 1) <= range.getStart())
  9006. return false;
  9007. if (values.getUnchecked (i << 1) <= range.getStart()
  9008. && range.getEnd() <= values.getUnchecked ((i << 1) + 1))
  9009. return true;
  9010. }
  9011. }
  9012. return false;
  9013. }
  9014. bool operator== (const SparseSet<Type>& other) throw()
  9015. {
  9016. return values == other.values;
  9017. }
  9018. bool operator!= (const SparseSet<Type>& other) throw()
  9019. {
  9020. return values != other.values;
  9021. }
  9022. juce_UseDebuggingNewOperator
  9023. private:
  9024. // alternating start/end values of ranges of values that are present.
  9025. Array<Type, DummyCriticalSection> values;
  9026. void simplify()
  9027. {
  9028. jassert ((values.size() & 1) == 0);
  9029. for (int i = values.size(); --i > 0;)
  9030. if (values.getUnchecked(i) == values.getUnchecked (i - 1))
  9031. values.removeRange (--i, 2);
  9032. }
  9033. };
  9034. #endif // __JUCE_SPARSESET_JUCEHEADER__
  9035. /*** End of inlined file: juce_SparseSet.h ***/
  9036. #endif
  9037. #ifndef __JUCE_VALUE_JUCEHEADER__
  9038. /*** Start of inlined file: juce_Value.h ***/
  9039. #ifndef __JUCE_VALUE_JUCEHEADER__
  9040. #define __JUCE_VALUE_JUCEHEADER__
  9041. /*** Start of inlined file: juce_AsyncUpdater.h ***/
  9042. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  9043. #define __JUCE_ASYNCUPDATER_JUCEHEADER__
  9044. /*** Start of inlined file: juce_MessageListener.h ***/
  9045. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  9046. #define __JUCE_MESSAGELISTENER_JUCEHEADER__
  9047. /*** Start of inlined file: juce_Message.h ***/
  9048. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  9049. #define __JUCE_MESSAGE_JUCEHEADER__
  9050. class MessageListener;
  9051. class MessageManager;
  9052. /** The base class for objects that can be delivered to a MessageListener.
  9053. The simplest Message object contains a few integer and pointer parameters
  9054. that the user can set, and this is enough for a lot of purposes. For passing more
  9055. complex data, subclasses of Message can also be used.
  9056. @see MessageListener, MessageManager, ActionListener, ChangeListener
  9057. */
  9058. class JUCE_API Message
  9059. {
  9060. public:
  9061. /** Creates an uninitialised message.
  9062. The class's variables will also be left uninitialised.
  9063. */
  9064. Message() throw();
  9065. /** Creates a message object, filling in the member variables.
  9066. The corresponding public member variables will be set from the parameters
  9067. passed in.
  9068. */
  9069. Message (int intParameter1,
  9070. int intParameter2,
  9071. int intParameter3,
  9072. void* pointerParameter) throw();
  9073. /** Destructor. */
  9074. virtual ~Message() throw();
  9075. // These values can be used for carrying simple data that the application needs to
  9076. // pass around. For more complex messages, just create a subclass.
  9077. int intParameter1; /**< user-defined integer value. */
  9078. int intParameter2; /**< user-defined integer value. */
  9079. int intParameter3; /**< user-defined integer value. */
  9080. void* pointerParameter; /**< user-defined pointer value. */
  9081. juce_UseDebuggingNewOperator
  9082. private:
  9083. friend class MessageListener;
  9084. friend class MessageManager;
  9085. MessageListener* messageRecipient;
  9086. Message (const Message&);
  9087. Message& operator= (const Message&);
  9088. };
  9089. #endif // __JUCE_MESSAGE_JUCEHEADER__
  9090. /*** End of inlined file: juce_Message.h ***/
  9091. /**
  9092. MessageListener subclasses can post and receive Message objects.
  9093. @see Message, MessageManager, ActionListener, ChangeListener
  9094. */
  9095. class JUCE_API MessageListener
  9096. {
  9097. protected:
  9098. /** Creates a MessageListener. */
  9099. MessageListener() throw();
  9100. public:
  9101. /** Destructor.
  9102. When a MessageListener is deleted, it removes itself from a global list
  9103. of registered listeners, so that the isValidMessageListener() method
  9104. will no longer return true.
  9105. */
  9106. virtual ~MessageListener();
  9107. /** This is the callback method that receives incoming messages.
  9108. This is called by the MessageManager from its dispatch loop.
  9109. @see postMessage
  9110. */
  9111. virtual void handleMessage (const Message& message) = 0;
  9112. /** Sends a message to the message queue, for asynchronous delivery to this listener
  9113. later on.
  9114. This method can be called safely by any thread.
  9115. @param message the message object to send - this will be deleted
  9116. automatically by the message queue, so don't keep any
  9117. references to it after calling this method.
  9118. @see handleMessage
  9119. */
  9120. void postMessage (Message* message) const throw();
  9121. /** Checks whether this MessageListener has been deleted.
  9122. Although not foolproof, this method is safe to call on dangling or null
  9123. pointers. A list of active MessageListeners is kept internally, so this
  9124. checks whether the object is on this list or not.
  9125. Note that it's possible to get a false-positive here, if an object is
  9126. deleted and another is subsequently created that happens to be at the
  9127. exact same memory location, but I can't think of a good way of avoiding
  9128. this.
  9129. */
  9130. bool isValidMessageListener() const throw();
  9131. };
  9132. #endif // __JUCE_MESSAGELISTENER_JUCEHEADER__
  9133. /*** End of inlined file: juce_MessageListener.h ***/
  9134. /**
  9135. Has a callback method that is triggered asynchronously.
  9136. This object allows an asynchronous callback function to be triggered, for
  9137. tasks such as coalescing multiple updates into a single callback later on.
  9138. Basically, one or more calls to the triggerAsyncUpdate() will result in the
  9139. message thread calling handleAsyncUpdate() as soon as it can.
  9140. */
  9141. class JUCE_API AsyncUpdater
  9142. {
  9143. public:
  9144. /** Creates an AsyncUpdater object. */
  9145. AsyncUpdater() throw();
  9146. /** Destructor.
  9147. If there are any pending callbacks when the object is deleted, these are lost.
  9148. */
  9149. virtual ~AsyncUpdater();
  9150. /** Causes the callback to be triggered at a later time.
  9151. This method returns immediately, having made sure that a callback
  9152. to the handleAsyncUpdate() method will occur as soon as possible.
  9153. If an update callback is already pending but hasn't happened yet, calls
  9154. to this method will be ignored.
  9155. It's thread-safe to call this method from any number of threads without
  9156. needing to worry about locking.
  9157. */
  9158. void triggerAsyncUpdate() throw();
  9159. /** This will stop any pending updates from happening.
  9160. If called after triggerAsyncUpdate() and before the handleAsyncUpdate()
  9161. callback happens, this will cancel the handleAsyncUpdate() callback.
  9162. */
  9163. void cancelPendingUpdate() throw();
  9164. /** If an update has been triggered and is pending, this will invoke it
  9165. synchronously.
  9166. Use this as a kind of "flush" operation - if an update is pending, the
  9167. handleAsyncUpdate() method will be called immediately; if no update is
  9168. pending, then nothing will be done.
  9169. */
  9170. void handleUpdateNowIfNeeded();
  9171. /** Called back to do whatever your class needs to do.
  9172. This method is called by the message thread at the next convenient time
  9173. after the triggerAsyncUpdate() method has been called.
  9174. */
  9175. virtual void handleAsyncUpdate() = 0;
  9176. private:
  9177. class AsyncUpdaterInternal : public MessageListener
  9178. {
  9179. public:
  9180. AsyncUpdaterInternal() throw() {}
  9181. ~AsyncUpdaterInternal() {}
  9182. void handleMessage (const Message&);
  9183. AsyncUpdater* owner;
  9184. private:
  9185. AsyncUpdaterInternal (const AsyncUpdaterInternal&);
  9186. AsyncUpdaterInternal& operator= (const AsyncUpdaterInternal&);
  9187. };
  9188. AsyncUpdaterInternal internalAsyncHandler;
  9189. bool asyncMessagePending;
  9190. };
  9191. #endif // __JUCE_ASYNCUPDATER_JUCEHEADER__
  9192. /*** End of inlined file: juce_AsyncUpdater.h ***/
  9193. /*** Start of inlined file: juce_ListenerList.h ***/
  9194. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  9195. #define __JUCE_LISTENERLIST_JUCEHEADER__
  9196. /**
  9197. Holds a set of objects and can invoke a member function callback on each object
  9198. in the set with a single call.
  9199. Use a ListenerList to manage a set of objects which need a callback, and you
  9200. can invoke a member function by simply calling call() or callChecked().
  9201. E.g.
  9202. @code
  9203. class MyListenerType
  9204. {
  9205. public:
  9206. void myCallbackMethod (int foo, bool bar);
  9207. };
  9208. ListenerList <MyListenerType> listeners;
  9209. listeners.add (someCallbackObjects...);
  9210. // This will invoke myCallbackMethod (1234, true) on each of the objects
  9211. // in the list...
  9212. listeners.call (&MyListenerType::myCallbackMethod, 1234, true);
  9213. @endcode
  9214. If you add or remove listeners from the list during one of the callbacks - i.e. while
  9215. it's in the middle of iterating the listeners, then it's guaranteed that no listeners
  9216. will be mistakenly called after they've been removed, but it may mean that some of the
  9217. listeners could be called more than once, or not at all, depending on the list's order.
  9218. Sometimes, there's a chance that invoking one of the callbacks might result in the
  9219. list itself being deleted while it's still iterating - to survive this situation, you can
  9220. use callChecked() instead of call(), passing it a local object to act as a "BailOutChecker".
  9221. The BailOutChecker must implement a method of the form "bool shouldBailOut()", and
  9222. the list will check this after each callback to determine whether it should abort the
  9223. operation. For an example of a bail-out checker, see the Component::BailOutChecker class,
  9224. which can be used to check when a Component has been deleted. See also
  9225. ListenerList::DummyBailOutChecker, which is a dummy checker that always returns false.
  9226. */
  9227. template <class ListenerClass,
  9228. class ArrayType = Array <ListenerClass*> >
  9229. class ListenerList
  9230. {
  9231. // Horrible macros required to support VC6/7..
  9232. #if defined (_MSC_VER) && _MSC_VER <= 1400
  9233. #define LL_TEMPLATE(a) typename P##a, typename Q##a
  9234. #define LL_PARAM(a) Q##a& param##a
  9235. #else
  9236. #define LL_TEMPLATE(a) typename P##a
  9237. #define LL_PARAM(a) PARAMETER_TYPE(P##a) param##a
  9238. #endif
  9239. public:
  9240. /** Creates an empty list. */
  9241. ListenerList()
  9242. {
  9243. }
  9244. /** Destructor. */
  9245. ~ListenerList()
  9246. {
  9247. }
  9248. /** Adds a listener to the list.
  9249. A listener can only be added once, so if the listener is already in the list,
  9250. this method has no effect.
  9251. @see remove
  9252. */
  9253. void add (ListenerClass* const listenerToAdd)
  9254. {
  9255. // Listeners can't be null pointers!
  9256. jassert (listenerToAdd != 0);
  9257. if (listenerToAdd != 0)
  9258. listeners.addIfNotAlreadyThere (listenerToAdd);
  9259. }
  9260. /** Removes a listener from the list.
  9261. If the listener wasn't in the list, this has no effect.
  9262. */
  9263. void remove (ListenerClass* const listenerToRemove)
  9264. {
  9265. // Listeners can't be null pointers!
  9266. jassert (listenerToRemove != 0);
  9267. listeners.removeValue (listenerToRemove);
  9268. }
  9269. /** Returns the number of registered listeners. */
  9270. int size() const throw()
  9271. {
  9272. return listeners.size();
  9273. }
  9274. /** Returns true if any listeners are registered. */
  9275. bool isEmpty() const throw()
  9276. {
  9277. return listeners.size() == 0;
  9278. }
  9279. /** Returns true if the specified listener has been added to the list. */
  9280. bool contains (ListenerClass* const listener) const throw()
  9281. {
  9282. return listeners.contains (listener);
  9283. }
  9284. /** Calls a member function on each listener in the list, with no parameters. */
  9285. void call (void (ListenerClass::*callbackFunction) ())
  9286. {
  9287. callChecked (static_cast <const DummyBailOutChecker&> (DummyBailOutChecker()), callbackFunction);
  9288. }
  9289. /** Calls a member function on each listener in the list, with no parameters and a bail-out-checker.
  9290. See the class description for info about writing a bail-out checker. */
  9291. template <class BailOutCheckerType>
  9292. void callChecked (const BailOutCheckerType& bailOutChecker,
  9293. void (ListenerClass::*callbackFunction) ())
  9294. {
  9295. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9296. (iter.getListener()->*callbackFunction) ();
  9297. }
  9298. /** Calls a member function on each listener in the list, with 1 parameter. */
  9299. template <LL_TEMPLATE(1)>
  9300. void call (void (ListenerClass::*callbackFunction) (P1), LL_PARAM(1))
  9301. {
  9302. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9303. (iter.getListener()->*callbackFunction) (param1);
  9304. }
  9305. /** Calls a member function on each listener in the list, with one parameter and a bail-out-checker.
  9306. See the class description for info about writing a bail-out checker. */
  9307. template <class BailOutCheckerType, LL_TEMPLATE(1)>
  9308. void callChecked (const BailOutCheckerType& bailOutChecker,
  9309. void (ListenerClass::*callbackFunction) (P1),
  9310. LL_PARAM(1))
  9311. {
  9312. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9313. (iter.getListener()->*callbackFunction) (param1);
  9314. }
  9315. /** Calls a member function on each listener in the list, with 2 parameters. */
  9316. template <LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9317. void call (void (ListenerClass::*callbackFunction) (P1, P2),
  9318. LL_PARAM(1), LL_PARAM(2))
  9319. {
  9320. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9321. (iter.getListener()->*callbackFunction) (param1, param2);
  9322. }
  9323. /** Calls a member function on each listener in the list, with 2 parameters and a bail-out-checker.
  9324. See the class description for info about writing a bail-out checker. */
  9325. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2)>
  9326. void callChecked (const BailOutCheckerType& bailOutChecker,
  9327. void (ListenerClass::*callbackFunction) (P1, P2),
  9328. LL_PARAM(1), LL_PARAM(2))
  9329. {
  9330. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9331. (iter.getListener()->*callbackFunction) (param1, param2);
  9332. }
  9333. /** Calls a member function on each listener in the list, with 3 parameters. */
  9334. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9335. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9336. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9337. {
  9338. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9339. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9340. }
  9341. /** Calls a member function on each listener in the list, with 3 parameters and a bail-out-checker.
  9342. See the class description for info about writing a bail-out checker. */
  9343. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3)>
  9344. void callChecked (const BailOutCheckerType& bailOutChecker,
  9345. void (ListenerClass::*callbackFunction) (P1, P2, P3),
  9346. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3))
  9347. {
  9348. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9349. (iter.getListener()->*callbackFunction) (param1, param2, param3);
  9350. }
  9351. /** Calls a member function on each listener in the list, with 4 parameters. */
  9352. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9353. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9354. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9355. {
  9356. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9357. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9358. }
  9359. /** Calls a member function on each listener in the list, with 4 parameters and a bail-out-checker.
  9360. See the class description for info about writing a bail-out checker. */
  9361. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4)>
  9362. void callChecked (const BailOutCheckerType& bailOutChecker,
  9363. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4),
  9364. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4))
  9365. {
  9366. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9367. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4);
  9368. }
  9369. /** Calls a member function on each listener in the list, with 5 parameters. */
  9370. template <LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9371. void call (void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9372. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9373. {
  9374. for (Iterator<DummyBailOutChecker, ThisType> iter (*this, DummyBailOutChecker()); iter.next();)
  9375. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9376. }
  9377. /** Calls a member function on each listener in the list, with 5 parameters and a bail-out-checker.
  9378. See the class description for info about writing a bail-out checker. */
  9379. template <class BailOutCheckerType, LL_TEMPLATE(1), LL_TEMPLATE(2), LL_TEMPLATE(3), LL_TEMPLATE(4), LL_TEMPLATE(5)>
  9380. void callChecked (const BailOutCheckerType& bailOutChecker,
  9381. void (ListenerClass::*callbackFunction) (P1, P2, P3, P4, P5),
  9382. LL_PARAM(1), LL_PARAM(2), LL_PARAM(3), LL_PARAM(4), LL_PARAM(5))
  9383. {
  9384. for (Iterator<BailOutCheckerType, ThisType> iter (*this, bailOutChecker); iter.next();)
  9385. (iter.getListener()->*callbackFunction) (param1, param2, param3, param4, param5);
  9386. }
  9387. /** A dummy bail-out checker that always returns false.
  9388. See the ListenerList notes for more info about bail-out checkers.
  9389. */
  9390. class DummyBailOutChecker
  9391. {
  9392. public:
  9393. inline bool shouldBailOut() const throw() { return false; }
  9394. };
  9395. /** Iterates the listeners in a ListenerList. */
  9396. template <class BailOutCheckerType, class ListType>
  9397. class Iterator
  9398. {
  9399. public:
  9400. Iterator (const ListType& list_, const BailOutCheckerType& bailOutChecker_)
  9401. : list (list_), bailOutChecker (bailOutChecker_), index (list_.size())
  9402. {}
  9403. ~Iterator() {}
  9404. bool next()
  9405. {
  9406. if (index <= 0 || bailOutChecker.shouldBailOut())
  9407. return false;
  9408. const int listSize = list.size();
  9409. if (--index < listSize)
  9410. return true;
  9411. index = listSize - 1;
  9412. return index >= 0;
  9413. }
  9414. typename ListType::ListenerType* getListener() const throw()
  9415. {
  9416. return list.getListeners().getUnchecked (index);
  9417. }
  9418. private:
  9419. const ListType& list;
  9420. const BailOutCheckerType& bailOutChecker;
  9421. int index;
  9422. Iterator (const Iterator&);
  9423. Iterator& operator= (const Iterator&);
  9424. };
  9425. typedef ListenerList<ListenerClass, ArrayType> ThisType;
  9426. typedef ListenerClass ListenerType;
  9427. const ArrayType& getListeners() const throw() { return listeners; }
  9428. private:
  9429. ArrayType listeners;
  9430. ListenerList (const ListenerList&);
  9431. ListenerList& operator= (const ListenerList&);
  9432. #undef LL_TEMPLATE
  9433. #undef LL_PARAM
  9434. };
  9435. #endif // __JUCE_LISTENERLIST_JUCEHEADER__
  9436. /*** End of inlined file: juce_ListenerList.h ***/
  9437. /**
  9438. Represents a shared variant value.
  9439. A Value object contains a reference to a var object, and can get and set its value.
  9440. Listeners can be attached to be told when the value is changed.
  9441. The Value class is a wrapper around a shared, reference-counted underlying data
  9442. object - this means that multiple Value objects can all refer to the same piece of
  9443. data, allowing all of them to be notified when any of them changes it.
  9444. When you create a Value with its default constructor, it acts as a wrapper around a
  9445. simple var object, but by creating a Value that refers to a custom subclass of ValueSource,
  9446. you can map the Value onto any kind of underlying data.
  9447. */
  9448. class JUCE_API Value
  9449. {
  9450. public:
  9451. /** Creates an empty Value, containing a void var. */
  9452. Value();
  9453. /** Creates a Value that refers to the same value as another one.
  9454. Note that this doesn't make a copy of the other value - both this and the other
  9455. Value will share the same underlying value, so that when either one alters it, both
  9456. will see it change.
  9457. */
  9458. Value (const Value& other);
  9459. /** Creates a Value that is set to the specified value. */
  9460. explicit Value (const var& initialValue);
  9461. /** Destructor. */
  9462. ~Value();
  9463. /** Returns the current value. */
  9464. const var getValue() const;
  9465. /** Returns the current value. */
  9466. operator const var() const;
  9467. /** Returns the value as a string.
  9468. This is alternative to writing things like "myValue.getValue().toString()".
  9469. */
  9470. const String toString() const;
  9471. /** Sets the current value.
  9472. You can also use operator= to set the value.
  9473. If there are any listeners registered, they will be notified of the
  9474. change asynchronously.
  9475. */
  9476. void setValue (const var& newValue);
  9477. /** Sets the current value.
  9478. This is the same as calling setValue().
  9479. If there are any listeners registered, they will be notified of the
  9480. change asynchronously.
  9481. */
  9482. Value& operator= (const var& newValue);
  9483. /** Makes this object refer to the same underlying ValueSource as another one.
  9484. Once this object has been connected to another one, changing either one
  9485. will update the other.
  9486. Existing listeners will still be registered after you call this method, and
  9487. they'll continue to receive messages when the new value changes.
  9488. */
  9489. void referTo (const Value& valueToReferTo);
  9490. /** Returns true if this value and the other one are references to the same value.
  9491. */
  9492. bool refersToSameSourceAs (const Value& other) const;
  9493. /** Compares two values.
  9494. This is a compare-by-value comparison, so is effectively the same as
  9495. saying (this->getValue() == other.getValue()).
  9496. */
  9497. bool operator== (const Value& other) const;
  9498. /** Compares two values.
  9499. This is a compare-by-value comparison, so is effectively the same as
  9500. saying (this->getValue() != other.getValue()).
  9501. */
  9502. bool operator!= (const Value& other) const;
  9503. /** Receives callbacks when a Value object changes.
  9504. @see Value::addListener
  9505. */
  9506. class JUCE_API Listener
  9507. {
  9508. public:
  9509. Listener() {}
  9510. virtual ~Listener() {}
  9511. /** Called when a Value object is changed.
  9512. Note that the Value object passed as a parameter may not be exactly the same
  9513. object that you registered the listener with - it might be a copy that refers
  9514. to the same underlying ValueSource. To find out, you can call Value::refersToSameSourceAs().
  9515. */
  9516. virtual void valueChanged (Value& value) = 0;
  9517. };
  9518. /** Adds a listener to receive callbacks when the value changes.
  9519. The listener is added to this specific Value object, and not to the shared
  9520. object that it refers to. When this object is deleted, all the listeners will
  9521. be lost, even if other references to the same Value still exist. So when you're
  9522. adding a listener, make sure that you add it to a ValueTree instance that will last
  9523. for as long as you need the listener. In general, you'd never want to add a listener
  9524. to a local stack-based ValueTree, but more likely to one that's a member variable.
  9525. @see removeListener
  9526. */
  9527. void addListener (Listener* listener);
  9528. /** Removes a listener that was previously added with addListener(). */
  9529. void removeListener (Listener* listener);
  9530. /**
  9531. Used internally by the Value class as the base class for its shared value objects.
  9532. The Value class is essentially a reference-counted pointer to a shared instance
  9533. of a ValueSource object. If you're feeling adventurous, you can create your own custom
  9534. ValueSource classes to allow Value objects to represent your own custom data items.
  9535. */
  9536. class JUCE_API ValueSource : public ReferenceCountedObject,
  9537. public AsyncUpdater
  9538. {
  9539. public:
  9540. ValueSource();
  9541. virtual ~ValueSource();
  9542. /** Returns the current value of this object. */
  9543. virtual const var getValue() const = 0;
  9544. /** Changes the current value.
  9545. This must also trigger a change message if the value actually changes.
  9546. */
  9547. virtual void setValue (const var& newValue) = 0;
  9548. /** Delivers a change message to all the listeners that are registered with
  9549. this value.
  9550. If dispatchSynchronously is true, the method will call all the listeners
  9551. before returning; otherwise it'll dispatch a message and make the call later.
  9552. */
  9553. void sendChangeMessage (bool dispatchSynchronously);
  9554. juce_UseDebuggingNewOperator
  9555. protected:
  9556. friend class Value;
  9557. SortedSet <Value*> valuesWithListeners;
  9558. void handleAsyncUpdate();
  9559. ValueSource (const ValueSource&);
  9560. ValueSource& operator= (const ValueSource&);
  9561. };
  9562. /** Creates a Value object that uses this valueSource object as its underlying data. */
  9563. explicit Value (ValueSource* valueSource);
  9564. /** Returns the ValueSource that this value is referring to. */
  9565. ValueSource& getValueSource() throw() { return *value; }
  9566. juce_UseDebuggingNewOperator
  9567. private:
  9568. friend class ValueSource;
  9569. ReferenceCountedObjectPtr <ValueSource> value;
  9570. ListenerList <Listener> listeners;
  9571. void callListeners();
  9572. // This is disallowed to avoid confusion about whether it should
  9573. // do a by-value or by-reference copy.
  9574. Value& operator= (const Value& other);
  9575. };
  9576. /** Writes a Value to an OutputStream as a UTF8 string. */
  9577. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value);
  9578. #endif // __JUCE_VALUE_JUCEHEADER__
  9579. /*** End of inlined file: juce_Value.h ***/
  9580. #endif
  9581. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9582. /*** Start of inlined file: juce_ValueTree.h ***/
  9583. #ifndef __JUCE_VALUETREE_JUCEHEADER__
  9584. #define __JUCE_VALUETREE_JUCEHEADER__
  9585. /*** Start of inlined file: juce_UndoManager.h ***/
  9586. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  9587. #define __JUCE_UNDOMANAGER_JUCEHEADER__
  9588. /*** Start of inlined file: juce_ChangeBroadcaster.h ***/
  9589. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9590. #define __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9591. /*** Start of inlined file: juce_ChangeListenerList.h ***/
  9592. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9593. #define __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9594. /*** Start of inlined file: juce_ChangeListener.h ***/
  9595. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  9596. #define __JUCE_CHANGELISTENER_JUCEHEADER__
  9597. /**
  9598. Receives callbacks about changes to some kind of object.
  9599. Many objects use a ChangeListenerList to keep a set of listeners which they
  9600. will inform when something changes. A subclass of ChangeListener
  9601. is used to receive these callbacks.
  9602. Note that the major difference between an ActionListener and a ChangeListener
  9603. is that for a ChangeListener, multiple changes will be coalesced into fewer
  9604. callbacks, but ActionListeners perform one callback for every event posted.
  9605. @see ChangeListenerList, ChangeBroadcaster, ActionListener
  9606. */
  9607. class JUCE_API ChangeListener
  9608. {
  9609. public:
  9610. /** Destructor. */
  9611. virtual ~ChangeListener() {}
  9612. /** Overridden by your subclass to receive the callback.
  9613. @param objectThatHasChanged the value that was passed to the
  9614. ChangeListenerList::sendChangeMessage() method
  9615. */
  9616. virtual void changeListenerCallback (void* objectThatHasChanged) = 0;
  9617. };
  9618. #endif // __JUCE_CHANGELISTENER_JUCEHEADER__
  9619. /*** End of inlined file: juce_ChangeListener.h ***/
  9620. /*** Start of inlined file: juce_ScopedLock.h ***/
  9621. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  9622. #define __JUCE_SCOPEDLOCK_JUCEHEADER__
  9623. /**
  9624. Automatically locks and unlocks a CriticalSection object.
  9625. Use one of these as a local variable to control access to a CriticalSection.
  9626. e.g. @code
  9627. CriticalSection myCriticalSection;
  9628. for (;;)
  9629. {
  9630. const ScopedLock myScopedLock (myCriticalSection);
  9631. // myCriticalSection is now locked
  9632. ...do some stuff...
  9633. // myCriticalSection gets unlocked here.
  9634. }
  9635. @endcode
  9636. @see CriticalSection, ScopedUnlock
  9637. */
  9638. class JUCE_API ScopedLock
  9639. {
  9640. public:
  9641. /** Creates a ScopedLock.
  9642. As soon as it is created, this will lock the CriticalSection, and
  9643. when the ScopedLock object is deleted, the CriticalSection will
  9644. be unlocked.
  9645. Make sure this object is created and deleted by the same thread,
  9646. otherwise there are no guarantees what will happen! Best just to use it
  9647. as a local stack object, rather than creating one with the new() operator.
  9648. */
  9649. inline explicit ScopedLock (const CriticalSection& lock) throw() : lock_ (lock) { lock.enter(); }
  9650. /** Destructor.
  9651. The CriticalSection will be unlocked when the destructor is called.
  9652. Make sure this object is created and deleted by the same thread,
  9653. otherwise there are no guarantees what will happen!
  9654. */
  9655. inline ~ScopedLock() throw() { lock_.exit(); }
  9656. private:
  9657. const CriticalSection& lock_;
  9658. ScopedLock (const ScopedLock&);
  9659. ScopedLock& operator= (const ScopedLock&);
  9660. };
  9661. /**
  9662. Automatically unlocks and re-locks a CriticalSection object.
  9663. This is the reverse of a ScopedLock object - instead of locking the critical
  9664. section for the lifetime of this object, it unlocks it.
  9665. Make sure you don't try to unlock critical sections that aren't actually locked!
  9666. e.g. @code
  9667. CriticalSection myCriticalSection;
  9668. for (;;)
  9669. {
  9670. const ScopedLock myScopedLock (myCriticalSection);
  9671. // myCriticalSection is now locked
  9672. ... do some stuff with it locked ..
  9673. while (xyz)
  9674. {
  9675. ... do some stuff with it locked ..
  9676. const ScopedUnlock unlocker (myCriticalSection);
  9677. // myCriticalSection is now unlocked for the remainder of this block,
  9678. // and re-locked at the end.
  9679. ...do some stuff with it unlocked ...
  9680. }
  9681. // myCriticalSection gets unlocked here.
  9682. }
  9683. @endcode
  9684. @see CriticalSection, ScopedLock
  9685. */
  9686. class ScopedUnlock
  9687. {
  9688. public:
  9689. /** Creates a ScopedUnlock.
  9690. As soon as it is created, this will unlock the CriticalSection, and
  9691. when the ScopedLock object is deleted, the CriticalSection will
  9692. be re-locked.
  9693. Make sure this object is created and deleted by the same thread,
  9694. otherwise there are no guarantees what will happen! Best just to use it
  9695. as a local stack object, rather than creating one with the new() operator.
  9696. */
  9697. inline explicit ScopedUnlock (const CriticalSection& lock) throw() : lock_ (lock) { lock.exit(); }
  9698. /** Destructor.
  9699. The CriticalSection will be unlocked when the destructor is called.
  9700. Make sure this object is created and deleted by the same thread,
  9701. otherwise there are no guarantees what will happen!
  9702. */
  9703. inline ~ScopedUnlock() throw() { lock_.enter(); }
  9704. private:
  9705. const CriticalSection& lock_;
  9706. ScopedUnlock (const ScopedLock&);
  9707. ScopedUnlock& operator= (const ScopedUnlock&);
  9708. };
  9709. #endif // __JUCE_SCOPEDLOCK_JUCEHEADER__
  9710. /*** End of inlined file: juce_ScopedLock.h ***/
  9711. /**
  9712. A set of ChangeListeners.
  9713. Listeners can be added and removed from the list, and change messages can be
  9714. broadcast to all the listeners.
  9715. @see ChangeListener, ChangeBroadcaster
  9716. */
  9717. class JUCE_API ChangeListenerList : public MessageListener
  9718. {
  9719. public:
  9720. /** Creates an empty list. */
  9721. ChangeListenerList() throw();
  9722. /** Destructor. */
  9723. ~ChangeListenerList() throw();
  9724. /** Adds a listener to the list.
  9725. (Trying to add a listener that's already on the list will have no effect).
  9726. */
  9727. void addChangeListener (ChangeListener* listener) throw();
  9728. /** Removes a listener from the list.
  9729. If the listener isn't on the list, this won't have any effect.
  9730. */
  9731. void removeChangeListener (ChangeListener* listener) throw();
  9732. /** Removes all listeners from the list. */
  9733. void removeAllChangeListeners() throw();
  9734. /** Posts an asynchronous change message to all the listeners.
  9735. If a message has already been sent and hasn't yet been delivered, this
  9736. method won't send another - in this way it coalesces multiple frequent
  9737. changes into fewer actual callbacks to the ChangeListeners. Contrast this
  9738. with the ActionListener, which posts a new event for every call to its
  9739. sendActionMessage() method.
  9740. Only listeners which are on the list when the change event is delivered
  9741. will receive the event - and this may include listeners that weren't on
  9742. the list when the change message was sent.
  9743. @param objectThatHasChanged this pointer is passed to the
  9744. ChangeListener::changeListenerCallback() method,
  9745. and can be any value the application needs
  9746. @see sendSynchronousChangeMessage
  9747. */
  9748. void sendChangeMessage (void* objectThatHasChanged) throw();
  9749. /** This will synchronously callback all the ChangeListeners.
  9750. Use this if you need to synchronously force a call to all the
  9751. listeners' ChangeListener::changeListenerCallback() methods.
  9752. */
  9753. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9754. /** If a change message has been sent but not yet dispatched, this will
  9755. use sendSynchronousChangeMessage() to make the callback immediately.
  9756. */
  9757. void dispatchPendingMessages();
  9758. /** @internal */
  9759. void handleMessage (const Message&);
  9760. juce_UseDebuggingNewOperator
  9761. private:
  9762. SortedSet <void*> listeners;
  9763. CriticalSection lock;
  9764. void* lastChangedObject;
  9765. bool messagePending;
  9766. ChangeListenerList (const ChangeListenerList&);
  9767. ChangeListenerList& operator= (const ChangeListenerList&);
  9768. };
  9769. #endif // __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  9770. /*** End of inlined file: juce_ChangeListenerList.h ***/
  9771. /** Manages a list of ChangeListeners, and can send them messages.
  9772. To quickly add methods to your class that can add/remove change
  9773. listeners and broadcast to them, you can derive from this.
  9774. @see ChangeListenerList, ChangeListener
  9775. */
  9776. class JUCE_API ChangeBroadcaster
  9777. {
  9778. public:
  9779. /** Creates an ChangeBroadcaster. */
  9780. ChangeBroadcaster() throw();
  9781. /** Destructor. */
  9782. virtual ~ChangeBroadcaster();
  9783. /** Adds a listener to the list.
  9784. (Trying to add a listener that's already on the list will have no effect).
  9785. */
  9786. void addChangeListener (ChangeListener* listener) throw();
  9787. /** Removes a listener from the list.
  9788. If the listener isn't on the list, this won't have any effect.
  9789. */
  9790. void removeChangeListener (ChangeListener* listener) throw();
  9791. /** Removes all listeners from the list. */
  9792. void removeAllChangeListeners() throw();
  9793. /** Broadcasts a change message to all the registered listeners.
  9794. The message will be delivered asynchronously by the event thread, so this
  9795. method will not directly call any of the listeners. For a synchronous
  9796. message, use sendSynchronousChangeMessage().
  9797. @see ChangeListenerList::sendActionMessage
  9798. */
  9799. void sendChangeMessage (void* objectThatHasChanged) throw();
  9800. /** Sends a synchronous change message to all the registered listeners.
  9801. @see ChangeListenerList::sendSynchronousChangeMessage
  9802. */
  9803. void sendSynchronousChangeMessage (void* objectThatHasChanged);
  9804. /** If a change message has been sent but not yet dispatched, this will
  9805. use sendSynchronousChangeMessage() to make the callback immediately.
  9806. */
  9807. void dispatchPendingMessages();
  9808. private:
  9809. ChangeListenerList changeListenerList;
  9810. ChangeBroadcaster (const ChangeBroadcaster&);
  9811. ChangeBroadcaster& operator= (const ChangeBroadcaster&);
  9812. };
  9813. #endif // __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  9814. /*** End of inlined file: juce_ChangeBroadcaster.h ***/
  9815. /*** Start of inlined file: juce_UndoableAction.h ***/
  9816. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  9817. #define __JUCE_UNDOABLEACTION_JUCEHEADER__
  9818. /**
  9819. Used by the UndoManager class to store an action which can be done
  9820. and undone.
  9821. @see UndoManager
  9822. */
  9823. class JUCE_API UndoableAction
  9824. {
  9825. protected:
  9826. /** Creates an action. */
  9827. UndoableAction() throw() {}
  9828. public:
  9829. /** Destructor. */
  9830. virtual ~UndoableAction() {}
  9831. /** Overridden by a subclass to perform the action.
  9832. This method is called by the UndoManager, and shouldn't be used directly by
  9833. applications.
  9834. Be careful not to make any calls in a perform() method that could call
  9835. recursively back into the UndoManager::perform() method
  9836. @returns true if the action could be performed.
  9837. @see UndoManager::perform
  9838. */
  9839. virtual bool perform() = 0;
  9840. /** Overridden by a subclass to undo the action.
  9841. This method is called by the UndoManager, and shouldn't be used directly by
  9842. applications.
  9843. Be careful not to make any calls in an undo() method that could call
  9844. recursively back into the UndoManager::perform() method
  9845. @returns true if the action could be undone without any errors.
  9846. @see UndoManager::perform
  9847. */
  9848. virtual bool undo() = 0;
  9849. /** Returns a value to indicate how much memory this object takes up.
  9850. Because the UndoManager keeps a list of UndoableActions, this is used
  9851. to work out how much space each one will take up, so that the UndoManager
  9852. can work out how many to keep.
  9853. The default value returned here is 10 - units are arbitrary and
  9854. don't have to be accurate.
  9855. @see UndoManager::getNumberOfUnitsTakenUpByStoredCommands,
  9856. UndoManager::setMaxNumberOfStoredUnits
  9857. */
  9858. virtual int getSizeInUnits() { return 10; }
  9859. /** Allows multiple actions to be coalesced into a single action object, to reduce storage space.
  9860. If possible, this method should create and return a single action that does the same job as
  9861. this one followed by the supplied action.
  9862. If it's not possible to merge the two actions, the method should return zero.
  9863. */
  9864. virtual UndoableAction* createCoalescedAction (UndoableAction* nextAction) { (void) nextAction; return 0; }
  9865. };
  9866. #endif // __JUCE_UNDOABLEACTION_JUCEHEADER__
  9867. /*** End of inlined file: juce_UndoableAction.h ***/
  9868. /**
  9869. Manages a list of undo/redo commands.
  9870. An UndoManager object keeps a list of past actions and can use these actions
  9871. to move backwards and forwards through an undo history.
  9872. To use it, create subclasses of UndoableAction which perform all the
  9873. actions you need, then when you need to actually perform an action, create one
  9874. and pass it to the UndoManager's perform() method.
  9875. The manager also uses the concept of 'transactions' to group the actions
  9876. together - all actions performed between calls to beginNewTransaction() are
  9877. grouped together and are all undone/redone as a group.
  9878. The UndoManager is a ChangeBroadcaster, so listeners can register to be told
  9879. when actions are performed or undone.
  9880. @see UndoableAction
  9881. */
  9882. class JUCE_API UndoManager : public ChangeBroadcaster
  9883. {
  9884. public:
  9885. /** Creates an UndoManager.
  9886. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9887. to indicate how much storage it takes up
  9888. (UndoableAction::getSizeInUnits()), so this
  9889. lets you specify the maximum total number of
  9890. units that the undomanager is allowed to
  9891. keep in memory before letting the older actions
  9892. drop off the end of the list.
  9893. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9894. that will be kept, even if this involves exceeding
  9895. the amount of space specified in maxNumberOfUnitsToKeep
  9896. */
  9897. UndoManager (int maxNumberOfUnitsToKeep = 30000,
  9898. int minimumTransactionsToKeep = 30);
  9899. /** Destructor. */
  9900. ~UndoManager();
  9901. /** Deletes all stored actions in the list. */
  9902. void clearUndoHistory();
  9903. /** Returns the current amount of space to use for storing UndoableAction objects.
  9904. @see setMaxNumberOfStoredUnits
  9905. */
  9906. int getNumberOfUnitsTakenUpByStoredCommands() const;
  9907. /** Sets the amount of space that can be used for storing UndoableAction objects.
  9908. @param maxNumberOfUnitsToKeep each UndoableAction object returns a value
  9909. to indicate how much storage it takes up
  9910. (UndoableAction::getSizeInUnits()), so this
  9911. lets you specify the maximum total number of
  9912. units that the undomanager is allowed to
  9913. keep in memory before letting the older actions
  9914. drop off the end of the list.
  9915. @param minimumTransactionsToKeep this specifies the minimum number of transactions
  9916. that will be kept, even if this involves exceeding
  9917. the amount of space specified in maxNumberOfUnitsToKeep
  9918. @see getNumberOfUnitsTakenUpByStoredCommands
  9919. */
  9920. void setMaxNumberOfStoredUnits (int maxNumberOfUnitsToKeep,
  9921. int minimumTransactionsToKeep);
  9922. /** Performs an action and adds it to the undo history list.
  9923. @param action the action to perform - this will be deleted by the UndoManager
  9924. when no longer needed
  9925. @param actionName if this string is non-empty, the current transaction will be
  9926. given this name; if it's empty, the current transaction name will
  9927. be left unchanged. See setCurrentTransactionName()
  9928. @returns true if the command succeeds - see UndoableAction::perform
  9929. @see beginNewTransaction
  9930. */
  9931. bool perform (UndoableAction* action,
  9932. const String& actionName = String::empty);
  9933. /** Starts a new group of actions that together will be treated as a single transaction.
  9934. All actions that are passed to the perform() method between calls to this
  9935. method are grouped together and undone/redone together by a single call to
  9936. undo() or redo().
  9937. @param actionName a description of the transaction that is about to be
  9938. performed
  9939. */
  9940. void beginNewTransaction (const String& actionName = String::empty);
  9941. /** Changes the name stored for the current transaction.
  9942. Each transaction is given a name when the beginNewTransaction() method is
  9943. called, but this can be used to change that name without starting a new
  9944. transaction.
  9945. */
  9946. void setCurrentTransactionName (const String& newName);
  9947. /** Returns true if there's at least one action in the list to undo.
  9948. @see getUndoDescription, undo, canRedo
  9949. */
  9950. bool canUndo() const;
  9951. /** Returns the description of the transaction that would be next to get undone.
  9952. The description returned is the one that was passed into beginNewTransaction
  9953. before the set of actions was performed.
  9954. @see undo
  9955. */
  9956. const String getUndoDescription() const;
  9957. /** Tries to roll-back the last transaction.
  9958. @returns true if the transaction can be undone, and false if it fails, or
  9959. if there aren't any transactions to undo
  9960. */
  9961. bool undo();
  9962. /** Tries to roll-back any actions that were added to the current transaction.
  9963. This will perform an undo() only if there are some actions in the undo list
  9964. that were added after the last call to beginNewTransaction().
  9965. This is useful because it lets you call beginNewTransaction(), then
  9966. perform an operation which may or may not actually perform some actions, and
  9967. then call this method to get rid of any actions that might have been done
  9968. without it rolling back the previous transaction if nothing was actually
  9969. done.
  9970. @returns true if any actions were undone.
  9971. */
  9972. bool undoCurrentTransactionOnly();
  9973. /** Returns a list of the UndoableAction objects that have been performed during the
  9974. transaction that is currently open.
  9975. Effectively, this is the list of actions that would be undone if undoCurrentTransactionOnly()
  9976. were to be called now.
  9977. The first item in the list is the earliest action performed.
  9978. */
  9979. void getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const;
  9980. /** Returns the number of UndoableAction objects that have been performed during the
  9981. transaction that is currently open.
  9982. @see getActionsInCurrentTransaction
  9983. */
  9984. int getNumActionsInCurrentTransaction() const;
  9985. /** Returns true if there's at least one action in the list to redo.
  9986. @see getRedoDescription, redo, canUndo
  9987. */
  9988. bool canRedo() const;
  9989. /** Returns the description of the transaction that would be next to get redone.
  9990. The description returned is the one that was passed into beginNewTransaction
  9991. before the set of actions was performed.
  9992. @see redo
  9993. */
  9994. const String getRedoDescription() const;
  9995. /** Tries to redo the last transaction that was undone.
  9996. @returns true if the transaction can be redone, and false if it fails, or
  9997. if there aren't any transactions to redo
  9998. */
  9999. bool redo();
  10000. juce_UseDebuggingNewOperator
  10001. private:
  10002. OwnedArray <OwnedArray <UndoableAction> > transactions;
  10003. StringArray transactionNames;
  10004. String currentTransactionName;
  10005. int totalUnitsStored, maxNumUnitsToKeep, minimumTransactionsToKeep, nextIndex;
  10006. bool newTransaction, reentrancyCheck;
  10007. // disallow copy constructor
  10008. UndoManager (const UndoManager&);
  10009. UndoManager& operator= (const UndoManager&);
  10010. };
  10011. #endif // __JUCE_UNDOMANAGER_JUCEHEADER__
  10012. /*** End of inlined file: juce_UndoManager.h ***/
  10013. /**
  10014. A powerful tree structure that can be used to hold free-form data, and which can
  10015. handle its own undo and redo behaviour.
  10016. A ValueTree contains a list of named properties as var objects, and also holds
  10017. any number of sub-trees.
  10018. Create ValueTree objects on the stack, and don't be afraid to copy them around, as
  10019. they're simply a lightweight reference to a shared data container. Creating a copy
  10020. of another ValueTree simply creates a new reference to the same underlying object - to
  10021. make a separate, deep copy of a tree you should explicitly call createCopy().
  10022. Each ValueTree has a type name, in much the same way as an XmlElement has a tag name,
  10023. and much of the structure of a ValueTree is similar to an XmlElement tree.
  10024. You can convert a ValueTree to and from an XmlElement, and as long as the XML doesn't
  10025. contain text elements, the conversion works well and makes a good serialisation
  10026. format. They can also be serialised to a binary format, which is very fast and compact.
  10027. All the methods that change data take an optional UndoManager, which will be used
  10028. to track any changes to the object. For this to work, you have to be careful to
  10029. consistently always use the same UndoManager for all operations to any node inside
  10030. the tree.
  10031. A ValueTree can only be a child of one parent at a time, so if you're moving one from
  10032. one tree to another, be careful to always remove it first, before adding it. This
  10033. could also mess up your undo/redo chain, so be wary! In a debug build you should hit
  10034. assertions if you try to do anything dangerous, but there are still plenty of ways it
  10035. could go wrong.
  10036. Listeners can be added to a ValueTree to be told when properies change and when
  10037. nodes are added or removed.
  10038. @see var, XmlElement
  10039. */
  10040. class JUCE_API ValueTree
  10041. {
  10042. public:
  10043. /** Creates an empty, invalid ValueTree.
  10044. A ValueTree that is created with this constructor can't actually be used for anything,
  10045. it's just a default 'null' ValueTree that can be returned to indicate some sort of failure.
  10046. To create a real one, use the constructor that takes a string.
  10047. @see ValueTree::invalid
  10048. */
  10049. ValueTree() throw();
  10050. /** Creates an empty ValueTree with the given type name.
  10051. Like an XmlElement, each ValueTree node has a type, which you can access with
  10052. getType() and hasType().
  10053. */
  10054. explicit ValueTree (const Identifier& type);
  10055. /** Creates a reference to another ValueTree. */
  10056. ValueTree (const ValueTree& other);
  10057. /** Makes this object reference another node. */
  10058. ValueTree& operator= (const ValueTree& other);
  10059. /** Destructor. */
  10060. ~ValueTree();
  10061. /** Returns true if both this and the other tree node refer to the same underlying structure.
  10062. Note that this isn't a value comparison - two independently-created trees which
  10063. contain identical data are not considered equal.
  10064. */
  10065. bool operator== (const ValueTree& other) const throw();
  10066. /** Returns true if this and the other node refer to different underlying structures.
  10067. Note that this isn't a value comparison - two independently-created trees which
  10068. contain identical data are not considered equal.
  10069. */
  10070. bool operator!= (const ValueTree& other) const throw();
  10071. /** Performs a deep comparison between the properties and children of two trees.
  10072. If all the properties and children of the two trees are the same (recursively), this
  10073. returns true.
  10074. The normal operator==() only checks whether two trees refer to the same shared data
  10075. structure, so use this method if you need to do a proper value comparison.
  10076. */
  10077. bool isEquivalentTo (const ValueTree& other) const;
  10078. /** Returns true if this node refers to some valid data.
  10079. It's hard to create an invalid node, but you might get one returned, e.g. by an out-of-range
  10080. call to getChild().
  10081. */
  10082. bool isValid() const { return object != 0; }
  10083. /** Returns a deep copy of this tree and all its sub-nodes. */
  10084. ValueTree createCopy() const;
  10085. /** Returns the type of this node.
  10086. The type is specified when the ValueTree is created.
  10087. @see hasType
  10088. */
  10089. const Identifier getType() const;
  10090. /** Returns true if the node has this type.
  10091. The comparison is case-sensitive.
  10092. */
  10093. bool hasType (const Identifier& typeName) const;
  10094. /** Returns the value of a named property.
  10095. If no such property has been set, this will return a void variant.
  10096. You can also use operator[] to get a property.
  10097. @see var, setProperty, hasProperty
  10098. */
  10099. const var& getProperty (const Identifier& name) const;
  10100. /** Returns the value of a named property, or a user-specified default if the property doesn't exist.
  10101. If no such property has been set, this will return the value of defaultReturnValue.
  10102. You can also use operator[] and getProperty to get a property.
  10103. @see var, getProperty, setProperty, hasProperty
  10104. */
  10105. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10106. /** Returns the value of a named property.
  10107. If no such property has been set, this will return a void variant. This is the same as
  10108. calling getProperty().
  10109. @see getProperty
  10110. */
  10111. const var& operator[] (const Identifier& name) const;
  10112. /** Changes a named property of the node.
  10113. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10114. so that this change can be undone.
  10115. @see var, getProperty, removeProperty
  10116. */
  10117. void setProperty (const Identifier& name, const var& newValue, UndoManager* undoManager);
  10118. /** Returns true if the node contains a named property. */
  10119. bool hasProperty (const Identifier& name) const;
  10120. /** Removes a property from the node.
  10121. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10122. so that this change can be undone.
  10123. */
  10124. void removeProperty (const Identifier& name, UndoManager* undoManager);
  10125. /** Removes all properties from the node.
  10126. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10127. so that this change can be undone.
  10128. */
  10129. void removeAllProperties (UndoManager* undoManager);
  10130. /** Returns the total number of properties that the node contains.
  10131. @see getProperty.
  10132. */
  10133. int getNumProperties() const;
  10134. /** Returns the identifier of the property with a given index.
  10135. @see getNumProperties
  10136. */
  10137. const Identifier getPropertyName (int index) const;
  10138. /** Returns a Value object that can be used to control and respond to one of the tree's properties.
  10139. The Value object will maintain a reference to this tree, and will use the undo manager when
  10140. it needs to change the value. Attaching a Value::Listener to the value object will provide
  10141. callbacks whenever the property changes.
  10142. */
  10143. Value getPropertyAsValue (const Identifier& name, UndoManager* undoManager) const;
  10144. /** Returns the number of child nodes belonging to this one.
  10145. @see getChild
  10146. */
  10147. int getNumChildren() const;
  10148. /** Returns one of this node's child nodes.
  10149. If the index is out of range, it'll return an invalid node. (See isValid() to find out
  10150. whether a node is valid).
  10151. */
  10152. ValueTree getChild (int index) const;
  10153. /** Returns the first child node with the speficied type name.
  10154. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10155. whether a node is valid).
  10156. @see getOrCreateChildWithName
  10157. */
  10158. ValueTree getChildWithName (const Identifier& type) const;
  10159. /** Returns the first child node with the speficied type name, creating and adding
  10160. a child with this name if there wasn't already one there.
  10161. The only time this will return an invalid object is when the object that you're calling
  10162. the method on is itself invalid.
  10163. @see getChildWithName
  10164. */
  10165. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10166. /** Looks for the first child node that has the speficied property value.
  10167. This will scan the child nodes in order, until it finds one that has property that matches
  10168. the specified value.
  10169. If no such node is found, it'll return an invalid node. (See isValid() to find out
  10170. whether a node is valid).
  10171. */
  10172. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10173. /** Adds a child to this node.
  10174. Make sure that the child is removed from any former parent node before calling this, or
  10175. you'll hit an assertion.
  10176. If the index is < 0 or greater than the current number of child nodes, the new node will
  10177. be added at the end of the list.
  10178. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10179. so that this change can be undone.
  10180. */
  10181. void addChild (const ValueTree& child, int index, UndoManager* undoManager);
  10182. /** Removes the specified child from this node's child-list.
  10183. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10184. so that this change can be undone.
  10185. */
  10186. void removeChild (const ValueTree& child, UndoManager* undoManager);
  10187. /** Removes a child from this node's child-list.
  10188. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10189. so that this change can be undone.
  10190. */
  10191. void removeChild (int childIndex, UndoManager* undoManager);
  10192. /** Removes all child-nodes from this node.
  10193. If the undoManager parameter is non-null, its UndoManager::perform() method will be used,
  10194. so that this change can be undone.
  10195. */
  10196. void removeAllChildren (UndoManager* undoManager);
  10197. /** Moves one of the children to a different index.
  10198. This will move the child to a specified index, shuffling along any intervening
  10199. items as required. So for example, if you have a list of { 0, 1, 2, 3, 4, 5 }, then
  10200. calling move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
  10201. @param currentIndex the index of the item to be moved. If this isn't a
  10202. valid index, then nothing will be done
  10203. @param newIndex the index at which you'd like this item to end up. If this
  10204. is less than zero, the value will be moved to the end
  10205. of the list
  10206. @param undoManager the optional UndoManager to use to store this transaction
  10207. */
  10208. void moveChild (int currentIndex, int newIndex, UndoManager* undoManager);
  10209. /** Returns true if this node is anywhere below the specified parent node.
  10210. This returns true if the node is a child-of-a-child, as well as a direct child.
  10211. */
  10212. bool isAChildOf (const ValueTree& possibleParent) const;
  10213. /** Returns the index of a child item in this parent.
  10214. If the child isn't found, this returns -1.
  10215. */
  10216. int indexOf (const ValueTree& child) const;
  10217. /** Returns the parent node that contains this one.
  10218. If the node has no parent, this will return an invalid node. (See isValid() to find out
  10219. whether a node is valid).
  10220. */
  10221. ValueTree getParent() const;
  10222. /** Returns one of this node's siblings in its parent's child list.
  10223. The delta specifies how far to move through the list, so a value of 1 would return the node
  10224. that follows this one, -1 would return the node before it, 0 will return this node itself, etc.
  10225. If the requested position is beyond the range of available nodes, this will return ValueTree::invalid.
  10226. */
  10227. ValueTree getSibling (int delta) const;
  10228. /** Creates an XmlElement that holds a complete image of this node and all its children.
  10229. If this node is invalid, this may return 0. Otherwise, the XML that is produced can
  10230. be used to recreate a similar node by calling fromXml()
  10231. @see fromXml
  10232. */
  10233. XmlElement* createXml() const;
  10234. /** Tries to recreate a node from its XML representation.
  10235. This isn't designed to cope with random XML data - for a sensible result, it should only
  10236. be fed XML that was created by the createXml() method.
  10237. */
  10238. static ValueTree fromXml (const XmlElement& xml);
  10239. /** Stores this tree (and all its children) in a binary format.
  10240. Once written, the data can be read back with readFromStream().
  10241. It's much faster to load/save your tree in binary form than as XML, but
  10242. obviously isn't human-readable.
  10243. */
  10244. void writeToStream (OutputStream& output);
  10245. /** Reloads a tree from a stream that was written with writeToStream(). */
  10246. static ValueTree readFromStream (InputStream& input);
  10247. /** Reloads a tree from a data block that was written with writeToStream(). */
  10248. static ValueTree readFromData (const void* data, size_t numBytes);
  10249. /** Listener class for events that happen to a ValueTree.
  10250. To get events from a ValueTree, make your class implement this interface, and use
  10251. ValueTree::addListener() and ValueTree::removeListener() to register it.
  10252. */
  10253. class JUCE_API Listener
  10254. {
  10255. public:
  10256. /** Destructor. */
  10257. virtual ~Listener() {}
  10258. /** This method is called when a property of this node (or of one of its sub-nodes) has
  10259. changed.
  10260. The tree parameter indicates which tree has had its property changed, and the property
  10261. parameter indicates the property.
  10262. Note that when you register a listener to a tree, it will receive this callback for
  10263. property changes in that tree, and also for any of its children, (recursively, at any depth).
  10264. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10265. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10266. */
  10267. virtual void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged,
  10268. const Identifier& property) = 0;
  10269. /** This method is called when a child sub-tree is added or removed.
  10270. The tree parameter indicates the tree whose child was added or removed.
  10271. Note that when you register a listener to a tree, it will receive this callback for
  10272. child changes in that tree, and also in any of its children, (recursively, at any depth).
  10273. If your tree has sub-trees but you only want to know about changes to the top level tree,
  10274. simply check the tree parameter in this callback to make sure it's the tree you're interested in.
  10275. */
  10276. virtual void valueTreeChildrenChanged (ValueTree& treeWhoseChildHasChanged) = 0;
  10277. /** This method is called when a tree has been added or removed from a parent node.
  10278. This callback happens when the tree to which the listener was registered is added or
  10279. removed from a parent. Unlike the other callbacks, it applies only to the tree to which
  10280. the listener is registered, and not to any of its children.
  10281. */
  10282. virtual void valueTreeParentChanged (ValueTree& treeWhoseParentHasChanged) = 0;
  10283. };
  10284. /** Adds a listener to receive callbacks when this node is changed.
  10285. The listener is added to this specific ValueTree object, and not to the shared
  10286. object that it refers to. When this object is deleted, all the listeners will
  10287. be lost, even if other references to the same ValueTree still exist. And if you
  10288. use the operator= to make this refer to a different ValueTree, any listeners will
  10289. begin listening to changes to the new tree instead of the old one.
  10290. When you're adding a listener, make sure that you add it to a ValueTree instance that
  10291. will last for as long as you need the listener. In general, you'd never want to add a
  10292. listener to a local stack-based ValueTree, and would usually add one to a member variable.
  10293. @see removeListener
  10294. */
  10295. void addListener (Listener* listener);
  10296. /** Removes a listener that was previously added with addListener(). */
  10297. void removeListener (Listener* listener);
  10298. /** This method uses a comparator object to sort the tree's children into order.
  10299. The object provided must have a method of the form:
  10300. @code
  10301. int compareElements (const ValueTree& first, const ValueTree& second);
  10302. @endcode
  10303. ..and this method must return:
  10304. - a value of < 0 if the first comes before the second
  10305. - a value of 0 if the two objects are equivalent
  10306. - a value of > 0 if the second comes before the first
  10307. To improve performance, the compareElements() method can be declared as static or const.
  10308. @param comparator the comparator to use for comparing elements.
  10309. @param retainOrderOfEquivalentItems if this is true, then items
  10310. which the comparator says are equivalent will be
  10311. kept in the order in which they currently appear
  10312. in the array. This is slower to perform, but may
  10313. be important in some cases. If it's false, a faster
  10314. algorithm is used, but equivalent elements may be
  10315. rearranged.
  10316. */
  10317. template <typename ElementComparator>
  10318. void sort (ElementComparator& comparator, const bool retainOrderOfEquivalentItems = false)
  10319. {
  10320. if (object != 0)
  10321. {
  10322. ComparatorAdapter <ElementComparator> adapter (comparator);
  10323. object->children.sort (adapter, retainOrderOfEquivalentItems);
  10324. object->sendChildChangeMessage();
  10325. }
  10326. }
  10327. /** An invalid ValueTree that can be used if you need to return one as an error condition, etc.
  10328. This invalid object is equivalent to ValueTree created with its default constructor.
  10329. */
  10330. static const ValueTree invalid;
  10331. juce_UseDebuggingNewOperator
  10332. private:
  10333. class SetPropertyAction;
  10334. friend class SetPropertyAction;
  10335. class AddOrRemoveChildAction;
  10336. friend class AddOrRemoveChildAction;
  10337. class MoveChildAction;
  10338. friend class MoveChildAction;
  10339. class JUCE_API SharedObject : public ReferenceCountedObject
  10340. {
  10341. public:
  10342. explicit SharedObject (const Identifier& type);
  10343. SharedObject (const SharedObject& other);
  10344. ~SharedObject();
  10345. const Identifier type;
  10346. NamedValueSet properties;
  10347. ReferenceCountedArray <SharedObject> children;
  10348. SortedSet <ValueTree*> valueTreesWithListeners;
  10349. SharedObject* parent;
  10350. void sendPropertyChangeMessage (const Identifier& property);
  10351. void sendPropertyChangeMessage (ValueTree& tree, const Identifier& property);
  10352. void sendChildChangeMessage();
  10353. void sendChildChangeMessage (ValueTree& tree);
  10354. void sendParentChangeMessage();
  10355. const var& getProperty (const Identifier& name) const;
  10356. const var getProperty (const Identifier& name, const var& defaultReturnValue) const;
  10357. void setProperty (const Identifier& name, const var& newValue, UndoManager*);
  10358. bool hasProperty (const Identifier& name) const;
  10359. void removeProperty (const Identifier& name, UndoManager*);
  10360. void removeAllProperties (UndoManager*);
  10361. bool isAChildOf (const SharedObject* possibleParent) const;
  10362. int indexOf (const ValueTree& child) const;
  10363. ValueTree getChildWithName (const Identifier& type) const;
  10364. ValueTree getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager);
  10365. ValueTree getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const;
  10366. void addChild (SharedObject* child, int index, UndoManager*);
  10367. void removeChild (int childIndex, UndoManager*);
  10368. void removeAllChildren (UndoManager*);
  10369. void moveChild (int currentIndex, int newIndex, UndoManager*);
  10370. bool isEquivalentTo (const SharedObject& other) const;
  10371. XmlElement* createXml() const;
  10372. juce_UseDebuggingNewOperator
  10373. private:
  10374. SharedObject& operator= (const SharedObject&);
  10375. };
  10376. template <typename ElementComparator>
  10377. class ComparatorAdapter
  10378. {
  10379. public:
  10380. ComparatorAdapter (ElementComparator& comparator_) throw() : comparator (comparator_) {}
  10381. int compareElements (SharedObject* const first, SharedObject* const second)
  10382. {
  10383. return comparator.compareElements (ValueTree (first), ValueTree (second));
  10384. }
  10385. private:
  10386. ElementComparator& comparator;
  10387. ComparatorAdapter (const ComparatorAdapter&);
  10388. ComparatorAdapter& operator= (const ComparatorAdapter&);
  10389. };
  10390. friend class SharedObject;
  10391. typedef ReferenceCountedObjectPtr <SharedObject> SharedObjectPtr;
  10392. SharedObjectPtr object;
  10393. ListenerList <Listener> listeners;
  10394. #if JUCE_MSVC && ! DOXYGEN
  10395. public: // (workaround for VC6)
  10396. #endif
  10397. explicit ValueTree (SharedObject*);
  10398. };
  10399. #endif // __JUCE_VALUETREE_JUCEHEADER__
  10400. /*** End of inlined file: juce_ValueTree.h ***/
  10401. #endif
  10402. #ifndef __JUCE_VARIANT_JUCEHEADER__
  10403. #endif
  10404. #ifndef __JUCE_ATOMIC_JUCEHEADER__
  10405. #endif
  10406. #ifndef __JUCE_BYTEORDER_JUCEHEADER__
  10407. #endif
  10408. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10409. /*** Start of inlined file: juce_FileLogger.h ***/
  10410. #ifndef __JUCE_FILELOGGER_JUCEHEADER__
  10411. #define __JUCE_FILELOGGER_JUCEHEADER__
  10412. /**
  10413. A simple implemenation of a Logger that writes to a file.
  10414. @see Logger
  10415. */
  10416. class JUCE_API FileLogger : public Logger
  10417. {
  10418. public:
  10419. /** Creates a FileLogger for a given file.
  10420. @param fileToWriteTo the file that to use - new messages will be appended
  10421. to the file. If the file doesn't exist, it will be created,
  10422. along with any parent directories that are needed.
  10423. @param welcomeMessage when opened, the logger will write a header to the log, along
  10424. with the current date and time, and this welcome message
  10425. @param maxInitialFileSizeBytes if this is zero or greater, then if the file already exists
  10426. but is larger than this number of bytes, then the start of the
  10427. file will be truncated to keep the size down. This prevents a log
  10428. file getting ridiculously large over time. The file will be truncated
  10429. at a new-line boundary. If this value is less than zero, no size limit
  10430. will be imposed; if it's zero, the file will always be deleted. Note that
  10431. the size is only checked once when this object is created - any logging
  10432. that is done later will be appended without any checking
  10433. */
  10434. FileLogger (const File& fileToWriteTo,
  10435. const String& welcomeMessage,
  10436. const int maxInitialFileSizeBytes = 128 * 1024);
  10437. /** Destructor. */
  10438. ~FileLogger();
  10439. void logMessage (const String& message);
  10440. const File getLogFile() const { return logFile; }
  10441. /** Helper function to create a log file in the correct place for this platform.
  10442. On Windows this will return a logger with a path such as:
  10443. c:\\Documents and Settings\\username\\Application Data\\[logFileSubDirectoryName]\\[logFileName]
  10444. On the Mac it'll create something like:
  10445. ~/Library/Logs/[logFileName]
  10446. The method might return 0 if the file can't be created for some reason.
  10447. @param logFileSubDirectoryName if a subdirectory is needed, this is what it will be called -
  10448. it's best to use the something like the name of your application here.
  10449. @param logFileName the name of the file to create, e.g. "MyAppLog.txt". Don't just
  10450. call it "log.txt" because if it goes in a directory with logs
  10451. from other applications (as it will do on the Mac) then no-one
  10452. will know which one is yours!
  10453. @param welcomeMessage a message that will be written to the log when it's opened.
  10454. @param maxInitialFileSizeBytes (see the FileLogger constructor for more info on this)
  10455. */
  10456. static FileLogger* createDefaultAppLogger (const String& logFileSubDirectoryName,
  10457. const String& logFileName,
  10458. const String& welcomeMessage,
  10459. const int maxInitialFileSizeBytes = 128 * 1024);
  10460. juce_UseDebuggingNewOperator
  10461. private:
  10462. File logFile;
  10463. CriticalSection logLock;
  10464. ScopedPointer <FileOutputStream> logStream;
  10465. void trimFileSize (int maxFileSizeBytes) const;
  10466. FileLogger (const FileLogger&);
  10467. FileLogger& operator= (const FileLogger&);
  10468. };
  10469. #endif // __JUCE_FILELOGGER_JUCEHEADER__
  10470. /*** End of inlined file: juce_FileLogger.h ***/
  10471. #endif
  10472. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10473. /*** Start of inlined file: juce_Initialisation.h ***/
  10474. #ifndef __JUCE_INITIALISATION_JUCEHEADER__
  10475. #define __JUCE_INITIALISATION_JUCEHEADER__
  10476. /** Initialises Juce's GUI classes.
  10477. If you're embedding Juce into an application that uses its own event-loop rather
  10478. than using the START_JUCE_APPLICATION macro, call this function before making any
  10479. Juce calls, to make sure things are initialised correctly.
  10480. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10481. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10482. @see shutdownJuce_GUI(), initialiseJuce_NonGUI()
  10483. */
  10484. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI();
  10485. /** Clears up any static data being used by Juce's GUI classes.
  10486. If you're embedding Juce into an application that uses its own event-loop rather
  10487. than using the START_JUCE_APPLICATION macro, call this function in your shutdown
  10488. code to clean up any juce objects that might be lying around.
  10489. @see initialiseJuce_GUI(), initialiseJuce_NonGUI()
  10490. */
  10491. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  10492. /** Initialises the core parts of Juce.
  10493. If you're embedding Juce into either a command-line program, call this function
  10494. at the start of your main() function to make sure that Juce is initialised correctly.
  10495. Note that if you're creating a Juce DLL for Windows, you may also need to call the
  10496. PlatformUtilities::setCurrentModuleInstanceHandle() method.
  10497. @see shutdownJuce_NonGUI, initialiseJuce_GUI
  10498. */
  10499. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI();
  10500. /** Clears up any static data being used by Juce's non-gui core classes.
  10501. If you're embedding Juce into either a command-line program, call this function
  10502. at the end of your main() function if you want to make sure any Juce objects are
  10503. cleaned up correctly.
  10504. @see initialiseJuce_NonGUI, initialiseJuce_GUI
  10505. */
  10506. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI();
  10507. /** A utility object that helps you initialise and shutdown Juce correctly
  10508. using an RAII pattern.
  10509. When an instance of this class is created, it calls initialiseJuce_NonGUI(),
  10510. and when it's deleted, it calls shutdownJuce_NonGUI(), which lets you easily
  10511. make sure that these functions are matched correctly.
  10512. This class is particularly handy to use at the beginning of a console app's
  10513. main() function, because it'll take care of shutting down whenever you return
  10514. from the main() call.
  10515. @see ScopedJuceInitialiser_GUI
  10516. */
  10517. class ScopedJuceInitialiser_NonGUI
  10518. {
  10519. public:
  10520. /** The constructor simply calls initialiseJuce_NonGUI(). */
  10521. ScopedJuceInitialiser_NonGUI() { initialiseJuce_NonGUI(); }
  10522. /** The destructor simply calls shutdownJuce_NonGUI(). */
  10523. ~ScopedJuceInitialiser_NonGUI() { shutdownJuce_NonGUI(); }
  10524. };
  10525. /** A utility object that helps you initialise and shutdown Juce correctly
  10526. using an RAII pattern.
  10527. When an instance of this class is created, it calls initialiseJuce_GUI(),
  10528. and when it's deleted, it calls shutdownJuce_GUI(), which lets you easily
  10529. make sure that these functions are matched correctly.
  10530. This class is particularly handy to use at the beginning of a console app's
  10531. main() function, because it'll take care of shutting down whenever you return
  10532. from the main() call.
  10533. @see ScopedJuceInitialiser_NonGUI
  10534. */
  10535. class ScopedJuceInitialiser_GUI
  10536. {
  10537. public:
  10538. /** The constructor simply calls initialiseJuce_GUI(). */
  10539. ScopedJuceInitialiser_GUI() { initialiseJuce_GUI(); }
  10540. /** The destructor simply calls shutdownJuce_GUI(). */
  10541. ~ScopedJuceInitialiser_GUI() { shutdownJuce_GUI(); }
  10542. };
  10543. #endif // __JUCE_INITIALISATION_JUCEHEADER__
  10544. /*** End of inlined file: juce_Initialisation.h ***/
  10545. #endif
  10546. #ifndef __JUCE_LOGGER_JUCEHEADER__
  10547. #endif
  10548. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  10549. #endif
  10550. #ifndef __JUCE_MEMORY_JUCEHEADER__
  10551. #endif
  10552. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10553. /*** Start of inlined file: juce_PerformanceCounter.h ***/
  10554. #ifndef __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10555. #define __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10556. /** A timer for measuring performance of code and dumping the results to a file.
  10557. e.g. @code
  10558. PerformanceCounter pc ("fish", 50, "/temp/myfishlog.txt");
  10559. for (;;)
  10560. {
  10561. pc.start();
  10562. doSomethingFishy();
  10563. pc.stop();
  10564. }
  10565. @endcode
  10566. In this example, the time of each period between calling start/stop will be
  10567. measured and averaged over 50 runs, and the results printed to a file
  10568. every 50 times round the loop.
  10569. */
  10570. class JUCE_API PerformanceCounter
  10571. {
  10572. public:
  10573. /** Creates a PerformanceCounter object.
  10574. @param counterName the name used when printing out the statistics
  10575. @param runsPerPrintout the number of start/stop iterations before calling
  10576. printStatistics()
  10577. @param loggingFile a file to dump the results to - if this is File::nonexistent,
  10578. the results are just written to the debugger output
  10579. */
  10580. PerformanceCounter (const String& counterName,
  10581. int runsPerPrintout = 100,
  10582. const File& loggingFile = File::nonexistent);
  10583. /** Destructor. */
  10584. ~PerformanceCounter();
  10585. /** Starts timing.
  10586. @see stop
  10587. */
  10588. void start();
  10589. /** Stops timing and prints out the results.
  10590. The number of iterations before doing a printout of the
  10591. results is set in the constructor.
  10592. @see start
  10593. */
  10594. void stop();
  10595. /** Dumps the current metrics to the debugger output and to a file.
  10596. As well as using Logger::outputDebugString to print the results,
  10597. this will write then to the file specified in the constructor (if
  10598. this was valid).
  10599. */
  10600. void printStatistics();
  10601. juce_UseDebuggingNewOperator
  10602. private:
  10603. String name;
  10604. int numRuns, runsPerPrint;
  10605. double totalTime;
  10606. int64 started;
  10607. File outputFile;
  10608. };
  10609. #endif // __JUCE_PERFORMANCECOUNTER_JUCEHEADER__
  10610. /*** End of inlined file: juce_PerformanceCounter.h ***/
  10611. #endif
  10612. #ifndef __JUCE_PLATFORMDEFS_JUCEHEADER__
  10613. #endif
  10614. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10615. /*** Start of inlined file: juce_PlatformUtilities.h ***/
  10616. #ifndef __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10617. #define __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10618. /**
  10619. A collection of miscellaneous platform-specific utilities.
  10620. */
  10621. class JUCE_API PlatformUtilities
  10622. {
  10623. public:
  10624. /** Plays the operating system's default alert 'beep' sound. */
  10625. static void beep();
  10626. /** Tries to launch the system's default reader for a given file or URL. */
  10627. static bool openDocument (const String& documentURL, const String& parameters);
  10628. /** Tries to launch the system's default email app to let the user create an email.
  10629. */
  10630. static bool launchEmailWithAttachments (const String& targetEmailAddress,
  10631. const String& emailSubject,
  10632. const String& bodyText,
  10633. const StringArray& filesToAttach);
  10634. #if JUCE_MAC || JUCE_IPHONE || DOXYGEN
  10635. /** MAC ONLY - Turns a Core CF String into a juce one. */
  10636. static const String cfStringToJuceString (CFStringRef cfString);
  10637. /** MAC ONLY - Turns a juce string into a Core CF one. */
  10638. static CFStringRef juceStringToCFString (const String& s);
  10639. /** MAC ONLY - Turns a file path into an FSRef, returning true if it succeeds. */
  10640. static bool makeFSRefFromPath (FSRef* destFSRef, const String& path);
  10641. /** MAC ONLY - Turns an FSRef into a juce string path. */
  10642. static const String makePathFromFSRef (FSRef* file);
  10643. /** MAC ONLY - Converts any decomposed unicode characters in a string into
  10644. their precomposed equivalents.
  10645. */
  10646. static const String convertToPrecomposedUnicode (const String& s);
  10647. /** MAC ONLY - Gets the type of a file from the file's resources. */
  10648. static OSType getTypeOfFile (const String& filename);
  10649. /** MAC ONLY - Returns true if this file is actually a bundle. */
  10650. static bool isBundle (const String& filename);
  10651. /** MAC ONLY - Adds an item to the dock */
  10652. static void addItemToDock (const File& file);
  10653. /** MAC ONLY - Returns the current OS version number.
  10654. E.g. if it's running on 10.4, this will be 4, 10.5 will return 5, etc.
  10655. */
  10656. static int getOSXMinorVersionNumber();
  10657. #endif
  10658. #if JUCE_WINDOWS || DOXYGEN
  10659. // Some registry helper functions:
  10660. /** WIN32 ONLY - Returns a string from the registry.
  10661. The path is a string for the entire path of a value in the registry,
  10662. e.g. "HKEY_CURRENT_USER\Software\foo\bar"
  10663. */
  10664. static const String getRegistryValue (const String& regValuePath,
  10665. const String& defaultValue = String::empty);
  10666. /** WIN32 ONLY - Sets a registry value as a string.
  10667. This will take care of creating any groups needed to get to the given
  10668. registry value.
  10669. */
  10670. static void setRegistryValue (const String& regValuePath,
  10671. const String& value);
  10672. /** WIN32 ONLY - Returns true if the given value exists in the registry. */
  10673. static bool registryValueExists (const String& regValuePath);
  10674. /** WIN32 ONLY - Deletes a registry value. */
  10675. static void deleteRegistryValue (const String& regValuePath);
  10676. /** WIN32 ONLY - Deletes a registry key (which is registry-talk for 'folder'). */
  10677. static void deleteRegistryKey (const String& regKeyPath);
  10678. /** WIN32 ONLY - Creates a file association in the registry.
  10679. This lets you set the exe that should be launched by a given file extension.
  10680. @param fileExtension the file extension to associate, including the
  10681. initial dot, e.g. ".txt"
  10682. @param symbolicDescription a space-free short token to identify the file type
  10683. @param fullDescription a human-readable description of the file type
  10684. @param targetExecutable the executable that should be launched
  10685. @param iconResourceNumber the icon that gets displayed for the file type will be
  10686. found by looking up this resource number in the
  10687. executable. Pass 0 here to not use an icon
  10688. */
  10689. static void registerFileAssociation (const String& fileExtension,
  10690. const String& symbolicDescription,
  10691. const String& fullDescription,
  10692. const File& targetExecutable,
  10693. int iconResourceNumber);
  10694. /** WIN32 ONLY - This returns the HINSTANCE of the current module.
  10695. In a normal Juce application this will be set to the module handle
  10696. of the application executable.
  10697. If you're writing a DLL using Juce and plan to use any Juce messaging or
  10698. windows, you'll need to make sure you use the setCurrentModuleInstanceHandle()
  10699. to set the correct module handle in your DllMain() function, because
  10700. the win32 system relies on the correct instance handle when opening windows.
  10701. */
  10702. static void* JUCE_CALLTYPE getCurrentModuleInstanceHandle() throw();
  10703. /** WIN32 ONLY - Sets a new module handle to be used by the library.
  10704. @see getCurrentModuleInstanceHandle()
  10705. */
  10706. static void JUCE_CALLTYPE setCurrentModuleInstanceHandle (void* newHandle) throw();
  10707. /** WIN32 ONLY - Gets the command-line params as a string.
  10708. This is needed to avoid unicode problems with the argc type params.
  10709. */
  10710. static const String JUCE_CALLTYPE getCurrentCommandLineParams();
  10711. #endif
  10712. /** Clears the floating point unit's flags.
  10713. Only has an effect under win32, currently.
  10714. */
  10715. static void fpuReset();
  10716. #if JUCE_LINUX || JUCE_WINDOWS
  10717. /** Loads a dynamically-linked library into the process's address space.
  10718. @param pathOrFilename the platform-dependent name and search path
  10719. @returns a handle which can be used by getProcedureEntryPoint(), or
  10720. zero if it fails.
  10721. @see freeDynamicLibrary, getProcedureEntryPoint
  10722. */
  10723. static void* loadDynamicLibrary (const String& pathOrFilename);
  10724. /** Frees a dynamically-linked library.
  10725. @param libraryHandle a handle created by loadDynamicLibrary
  10726. @see loadDynamicLibrary, getProcedureEntryPoint
  10727. */
  10728. static void freeDynamicLibrary (void* libraryHandle);
  10729. /** Finds a procedure call in a dynamically-linked library.
  10730. @param libraryHandle a library handle returned by loadDynamicLibrary
  10731. @param procedureName the name of the procedure call to try to load
  10732. @returns a pointer to the function if found, or 0 if it fails
  10733. @see loadDynamicLibrary
  10734. */
  10735. static void* getProcedureEntryPoint (void* libraryHandle,
  10736. const String& procedureName);
  10737. #endif
  10738. #if JUCE_LINUX || DOXYGEN
  10739. #endif
  10740. private:
  10741. PlatformUtilities();
  10742. PlatformUtilities (const PlatformUtilities&);
  10743. PlatformUtilities& operator= (const PlatformUtilities&);
  10744. };
  10745. #if JUCE_MAC || JUCE_IPHONE
  10746. /** A handy C++ wrapper that creates and deletes an NSAutoreleasePool object
  10747. using RAII.
  10748. */
  10749. class ScopedAutoReleasePool
  10750. {
  10751. public:
  10752. ScopedAutoReleasePool();
  10753. ~ScopedAutoReleasePool();
  10754. private:
  10755. void* pool;
  10756. ScopedAutoReleasePool (const ScopedAutoReleasePool&);
  10757. ScopedAutoReleasePool& operator= (const ScopedAutoReleasePool&);
  10758. };
  10759. #endif
  10760. #if JUCE_LINUX
  10761. /** A handy class that uses XLockDisplay and XUnlockDisplay to lock the X server
  10762. using an RAII approach.
  10763. */
  10764. class ScopedXLock
  10765. {
  10766. public:
  10767. /** Creating a ScopedXLock object locks the X display.
  10768. This uses XLockDisplay() to grab the display that Juce is using.
  10769. */
  10770. ScopedXLock();
  10771. /** Deleting a ScopedXLock object unlocks the X display.
  10772. This calls XUnlockDisplay() to release the lock.
  10773. */
  10774. ~ScopedXLock();
  10775. };
  10776. #endif
  10777. #if JUCE_MAC
  10778. /**
  10779. A wrapper class for picking up events from an Apple IR remote control device.
  10780. To use it, just create a subclass of this class, implementing the buttonPressed()
  10781. callback, then call start() and stop() to start or stop receiving events.
  10782. */
  10783. class JUCE_API AppleRemoteDevice
  10784. {
  10785. public:
  10786. AppleRemoteDevice();
  10787. virtual ~AppleRemoteDevice();
  10788. /** The set of buttons that may be pressed.
  10789. @see buttonPressed
  10790. */
  10791. enum ButtonType
  10792. {
  10793. menuButton = 0, /**< The menu button (if it's held for a short time). */
  10794. playButton, /**< The play button. */
  10795. plusButton, /**< The plus or volume-up button. */
  10796. minusButton, /**< The minus or volume-down button. */
  10797. rightButton, /**< The right button (if it's held for a short time). */
  10798. leftButton, /**< The left button (if it's held for a short time). */
  10799. rightButton_Long, /**< The right button (if it's held for a long time). */
  10800. leftButton_Long, /**< The menu button (if it's held for a long time). */
  10801. menuButton_Long, /**< The menu button (if it's held for a long time). */
  10802. playButtonSleepMode,
  10803. switched
  10804. };
  10805. /** Override this method to receive the callback about a button press.
  10806. The callback will happen on the application's message thread.
  10807. Some buttons trigger matching up and down events, in which the isDown parameter
  10808. will be true and then false. Others only send a single event when the
  10809. button is pressed.
  10810. */
  10811. virtual void buttonPressed (const ButtonType buttonId, const bool isDown) = 0;
  10812. /** Starts the device running and responding to events.
  10813. Returns true if it managed to open the device.
  10814. @param inExclusiveMode if true, the remote will be grabbed exclusively for this app,
  10815. and will not be available to any other part of the system. If
  10816. false, it will be shared with other apps.
  10817. @see stop
  10818. */
  10819. bool start (const bool inExclusiveMode);
  10820. /** Stops the device running.
  10821. @see start
  10822. */
  10823. void stop();
  10824. /** Returns true if the device has been started successfully.
  10825. */
  10826. bool isActive() const;
  10827. /** Returns the ID number of the remote, if it has sent one.
  10828. */
  10829. int getRemoteId() const { return remoteId; }
  10830. juce_UseDebuggingNewOperator
  10831. /** @internal */
  10832. void handleCallbackInternal();
  10833. private:
  10834. void* device;
  10835. void* queue;
  10836. int remoteId;
  10837. bool open (const bool openInExclusiveMode);
  10838. AppleRemoteDevice (const AppleRemoteDevice&);
  10839. AppleRemoteDevice& operator= (const AppleRemoteDevice&);
  10840. };
  10841. #endif
  10842. #endif // __JUCE_PLATFORMUTILITIES_JUCEHEADER__
  10843. /*** End of inlined file: juce_PlatformUtilities.h ***/
  10844. #endif
  10845. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10846. /*** Start of inlined file: juce_Random.h ***/
  10847. #ifndef __JUCE_RANDOM_JUCEHEADER__
  10848. #define __JUCE_RANDOM_JUCEHEADER__
  10849. /**
  10850. A simple pseudo-random number generator.
  10851. */
  10852. class JUCE_API Random
  10853. {
  10854. public:
  10855. /** Creates a Random object based on a seed value.
  10856. For a given seed value, the subsequent numbers generated by this object
  10857. will be predictable, so a good idea is to set this value based
  10858. on the time, e.g.
  10859. new Random (Time::currentTimeMillis())
  10860. */
  10861. explicit Random (int64 seedValue) throw();
  10862. /** Destructor. */
  10863. ~Random() throw();
  10864. /** Returns the next random 32 bit integer.
  10865. @returns a random integer from the full range 0x80000000 to 0x7fffffff
  10866. */
  10867. int nextInt() throw();
  10868. /** Returns the next random number, limited to a given range.
  10869. @returns a random integer between 0 (inclusive) and maxValue (exclusive).
  10870. */
  10871. int nextInt (int maxValue) throw();
  10872. /** Returns the next 64-bit random number.
  10873. @returns a random integer from the full range 0x8000000000000000 to 0x7fffffffffffffff
  10874. */
  10875. int64 nextInt64() throw();
  10876. /** Returns the next random floating-point number.
  10877. @returns a random value in the range 0 to 1.0
  10878. */
  10879. float nextFloat() throw();
  10880. /** Returns the next random floating-point number.
  10881. @returns a random value in the range 0 to 1.0
  10882. */
  10883. double nextDouble() throw();
  10884. /** Returns the next random boolean value.
  10885. */
  10886. bool nextBool() throw();
  10887. /** Returns a BigInteger containing a random number.
  10888. @returns a random value in the range 0 to (maximumValue - 1).
  10889. */
  10890. const BigInteger nextLargeNumber (const BigInteger& maximumValue);
  10891. /** Sets a range of bits in a BigInteger to random values. */
  10892. void fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits);
  10893. /** To avoid the overhead of having to create a new Random object whenever
  10894. you need a number, this is a shared application-wide object that
  10895. can be used.
  10896. It's not thread-safe though, so threads should use their own Random object.
  10897. */
  10898. static Random& getSystemRandom() throw();
  10899. /** Resets this Random object to a given seed value. */
  10900. void setSeed (int64 newSeed) throw();
  10901. /** Merges this object's seed with another value.
  10902. This sets the seed to be a value created by combining the current seed and this
  10903. new value.
  10904. */
  10905. void combineSeed (int64 seedValue) throw();
  10906. /** Reseeds this generator using a value generated from various semi-random system
  10907. properties like the current time, etc.
  10908. Because this function convolves the time with the last seed value, calling
  10909. it repeatedly will increase the randomness of the final result.
  10910. */
  10911. void setSeedRandomly();
  10912. juce_UseDebuggingNewOperator
  10913. private:
  10914. int64 seed;
  10915. };
  10916. #endif // __JUCE_RANDOM_JUCEHEADER__
  10917. /*** End of inlined file: juce_Random.h ***/
  10918. #endif
  10919. #ifndef __JUCE_RELATIVETIME_JUCEHEADER__
  10920. #endif
  10921. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10922. /*** Start of inlined file: juce_Singleton.h ***/
  10923. #ifndef __JUCE_SINGLETON_JUCEHEADER__
  10924. #define __JUCE_SINGLETON_JUCEHEADER__
  10925. /**
  10926. Macro to declare member variables and methods for a singleton class.
  10927. To use this, add the line juce_DeclareSingleton (MyClass, doNotRecreateAfterDeletion)
  10928. to the class's definition.
  10929. Then put a macro juce_ImplementSingleton (MyClass) along with the class's
  10930. implementation code.
  10931. It's also a very good idea to also add the call clearSingletonInstance() in your class's
  10932. destructor, in case it is deleted by other means than deleteInstance()
  10933. Clients can then call the static method MyClass::getInstance() to get a pointer
  10934. to the singleton, or MyClass::getInstanceWithoutCreating() which will return 0 if
  10935. no instance currently exists.
  10936. e.g. @code
  10937. class MySingleton
  10938. {
  10939. public:
  10940. MySingleton()
  10941. {
  10942. }
  10943. ~MySingleton()
  10944. {
  10945. // this ensures that no dangling pointers are left when the
  10946. // singleton is deleted.
  10947. clearSingletonInstance();
  10948. }
  10949. juce_DeclareSingleton (MySingleton, false)
  10950. };
  10951. juce_ImplementSingleton (MySingleton)
  10952. // example of usage:
  10953. MySingleton* m = MySingleton::getInstance(); // creates the singleton if there isn't already one.
  10954. ...
  10955. MySingleton::deleteInstance(); // safely deletes the singleton (if it's been created).
  10956. @endcode
  10957. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  10958. than once during the process's lifetime - i.e. after you've created and deleted the
  10959. object, getInstance() will refuse to create another one. This can be useful to stop
  10960. objects being accidentally re-created during your app's shutdown code.
  10961. If you know that your object will only be created and deleted by a single thread, you
  10962. can use the slightly more efficient juce_DeclareSingleton_SingleThreaded() macro instead
  10963. of this one.
  10964. @see juce_ImplementSingleton, juce_DeclareSingleton_SingleThreaded
  10965. */
  10966. #define juce_DeclareSingleton(classname, doNotRecreateAfterDeletion) \
  10967. \
  10968. static classname* _singletonInstance; \
  10969. static JUCE_NAMESPACE::CriticalSection _singletonLock; \
  10970. \
  10971. static classname* JUCE_CALLTYPE getInstance() \
  10972. { \
  10973. if (_singletonInstance == 0) \
  10974. {\
  10975. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  10976. \
  10977. if (_singletonInstance == 0) \
  10978. { \
  10979. static bool alreadyInside = false; \
  10980. static bool createdOnceAlready = false; \
  10981. \
  10982. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  10983. jassert (! problem); \
  10984. if (! problem) \
  10985. { \
  10986. createdOnceAlready = true; \
  10987. alreadyInside = true; \
  10988. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  10989. alreadyInside = false; \
  10990. \
  10991. _singletonInstance = newObject; \
  10992. } \
  10993. } \
  10994. } \
  10995. \
  10996. return _singletonInstance; \
  10997. } \
  10998. \
  10999. static inline classname* JUCE_CALLTYPE getInstanceWithoutCreating() throw() \
  11000. { \
  11001. return _singletonInstance; \
  11002. } \
  11003. \
  11004. static void JUCE_CALLTYPE deleteInstance() \
  11005. { \
  11006. const JUCE_NAMESPACE::ScopedLock sl (_singletonLock); \
  11007. if (_singletonInstance != 0) \
  11008. { \
  11009. classname* const old = _singletonInstance; \
  11010. _singletonInstance = 0; \
  11011. delete old; \
  11012. } \
  11013. } \
  11014. \
  11015. void clearSingletonInstance() throw() \
  11016. { \
  11017. if (_singletonInstance == this) \
  11018. _singletonInstance = 0; \
  11019. }
  11020. /** This is a counterpart to the juce_DeclareSingleton macro.
  11021. After adding the juce_DeclareSingleton to the class definition, this macro has
  11022. to be used in the cpp file.
  11023. */
  11024. #define juce_ImplementSingleton(classname) \
  11025. \
  11026. classname* classname::_singletonInstance = 0; \
  11027. JUCE_NAMESPACE::CriticalSection classname::_singletonLock;
  11028. /**
  11029. Macro to declare member variables and methods for a singleton class.
  11030. This is exactly the same as juce_DeclareSingleton, but doesn't use a critical
  11031. section to make access to it thread-safe. If you know that your object will
  11032. only ever be created or deleted by a single thread, then this is a
  11033. more efficient version to use.
  11034. If doNotRecreateAfterDeletion = true, it won't allow the object to be created more
  11035. than once during the process's lifetime - i.e. after you've created and deleted the
  11036. object, getInstance() will refuse to create another one. This can be useful to stop
  11037. objects being accidentally re-created during your app's shutdown code.
  11038. See the documentation for juce_DeclareSingleton for more information about
  11039. how to use it, the only difference being that you have to use
  11040. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11041. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton, juce_DeclareSingleton_SingleThreaded_Minimal
  11042. */
  11043. #define juce_DeclareSingleton_SingleThreaded(classname, doNotRecreateAfterDeletion) \
  11044. \
  11045. static classname* _singletonInstance; \
  11046. \
  11047. static classname* getInstance() \
  11048. { \
  11049. if (_singletonInstance == 0) \
  11050. { \
  11051. static bool alreadyInside = false; \
  11052. static bool createdOnceAlready = false; \
  11053. \
  11054. const bool problem = alreadyInside || ((doNotRecreateAfterDeletion) && createdOnceAlready); \
  11055. jassert (! problem); \
  11056. if (! problem) \
  11057. { \
  11058. createdOnceAlready = true; \
  11059. alreadyInside = true; \
  11060. classname* newObject = new classname(); /* (use a stack variable to avoid setting the newObject value before the class has finished its constructor) */ \
  11061. alreadyInside = false; \
  11062. \
  11063. _singletonInstance = newObject; \
  11064. } \
  11065. } \
  11066. \
  11067. return _singletonInstance; \
  11068. } \
  11069. \
  11070. static inline classname* getInstanceWithoutCreating() throw() \
  11071. { \
  11072. return _singletonInstance; \
  11073. } \
  11074. \
  11075. static void deleteInstance() \
  11076. { \
  11077. if (_singletonInstance != 0) \
  11078. { \
  11079. classname* const old = _singletonInstance; \
  11080. _singletonInstance = 0; \
  11081. delete old; \
  11082. } \
  11083. } \
  11084. \
  11085. void clearSingletonInstance() throw() \
  11086. { \
  11087. if (_singletonInstance == this) \
  11088. _singletonInstance = 0; \
  11089. }
  11090. /**
  11091. Macro to declare member variables and methods for a singleton class.
  11092. This is like juce_DeclareSingleton_SingleThreaded, but doesn't do any checking
  11093. for recursion or repeated instantiation. It's intended for use as a lightweight
  11094. version of a singleton, where you're using it in very straightforward
  11095. circumstances and don't need the extra checking.
  11096. Juce use the normal juce_ImplementSingleton_SingleThreaded as the counterpart
  11097. to this declaration, as you would with juce_DeclareSingleton_SingleThreaded.
  11098. See the documentation for juce_DeclareSingleton for more information about
  11099. how to use it, the only difference being that you have to use
  11100. juce_ImplementSingleton_SingleThreaded instead of juce_ImplementSingleton.
  11101. @see juce_ImplementSingleton_SingleThreaded, juce_DeclareSingleton
  11102. */
  11103. #define juce_DeclareSingleton_SingleThreaded_Minimal(classname) \
  11104. \
  11105. static classname* _singletonInstance; \
  11106. \
  11107. static classname* getInstance() \
  11108. { \
  11109. if (_singletonInstance == 0) \
  11110. _singletonInstance = new classname(); \
  11111. \
  11112. return _singletonInstance; \
  11113. } \
  11114. \
  11115. static inline classname* getInstanceWithoutCreating() throw() \
  11116. { \
  11117. return _singletonInstance; \
  11118. } \
  11119. \
  11120. static void deleteInstance() \
  11121. { \
  11122. if (_singletonInstance != 0) \
  11123. { \
  11124. classname* const old = _singletonInstance; \
  11125. _singletonInstance = 0; \
  11126. delete old; \
  11127. } \
  11128. } \
  11129. \
  11130. void clearSingletonInstance() throw() \
  11131. { \
  11132. if (_singletonInstance == this) \
  11133. _singletonInstance = 0; \
  11134. }
  11135. /** This is a counterpart to the juce_DeclareSingleton_SingleThreaded macro.
  11136. After adding juce_DeclareSingleton_SingleThreaded or juce_DeclareSingleton_SingleThreaded_Minimal
  11137. to the class definition, this macro has to be used somewhere in the cpp file.
  11138. */
  11139. #define juce_ImplementSingleton_SingleThreaded(classname) \
  11140. \
  11141. classname* classname::_singletonInstance = 0;
  11142. #endif // __JUCE_SINGLETON_JUCEHEADER__
  11143. /*** End of inlined file: juce_Singleton.h ***/
  11144. #endif
  11145. #ifndef __JUCE_STANDARDHEADER_JUCEHEADER__
  11146. #endif
  11147. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11148. /*** Start of inlined file: juce_SystemStats.h ***/
  11149. #ifndef __JUCE_SYSTEMSTATS_JUCEHEADER__
  11150. #define __JUCE_SYSTEMSTATS_JUCEHEADER__
  11151. /**
  11152. Contains methods for finding out about the current hardware and OS configuration.
  11153. */
  11154. class JUCE_API SystemStats
  11155. {
  11156. public:
  11157. /** Returns the current version of JUCE,
  11158. (just in case you didn't already know at compile-time.)
  11159. See also the JUCE_VERSION, JUCE_MAJOR_VERSION and JUCE_MINOR_VERSION macros.
  11160. */
  11161. static const String getJUCEVersion();
  11162. /** The set of possible results of the getOperatingSystemType() method.
  11163. */
  11164. enum OperatingSystemType
  11165. {
  11166. UnknownOS = 0,
  11167. MacOSX = 0x1000,
  11168. Linux = 0x2000,
  11169. Win95 = 0x4001,
  11170. Win98 = 0x4002,
  11171. WinNT351 = 0x4103,
  11172. WinNT40 = 0x4104,
  11173. Win2000 = 0x4105,
  11174. WinXP = 0x4106,
  11175. WinVista = 0x4107,
  11176. Windows7 = 0x4108,
  11177. Windows = 0x4000, /**< To test whether any version of Windows is running,
  11178. you can use the expression ((getOperatingSystemType() & Windows) != 0). */
  11179. WindowsNT = 0x0100, /**< To test whether the platform is Windows NT or later (i.e. not Win95 or 98),
  11180. you can use the expression ((getOperatingSystemType() & WindowsNT) != 0). */
  11181. };
  11182. /** Returns the type of operating system we're running on.
  11183. @returns one of the values from the OperatingSystemType enum.
  11184. @see getOperatingSystemName
  11185. */
  11186. static OperatingSystemType getOperatingSystemType();
  11187. /** Returns the name of the type of operating system we're running on.
  11188. @returns a string describing the OS type.
  11189. @see getOperatingSystemType
  11190. */
  11191. static const String getOperatingSystemName();
  11192. /** Returns true if the OS is 64-bit, or false for a 32-bit OS.
  11193. */
  11194. static bool isOperatingSystem64Bit();
  11195. /** Returns the current user's name, if available.
  11196. @see getFullUserName()
  11197. */
  11198. static const String getLogonName();
  11199. /** Returns the current user's full name, if available.
  11200. On some OSes, this may just return the same value as getLogonName().
  11201. @see getLogonName()
  11202. */
  11203. static const String getFullUserName();
  11204. // CPU and memory information..
  11205. /** Returns the approximate CPU speed.
  11206. @returns the speed in megahertz, e.g. 1500, 2500, 32000 (depending on
  11207. what year you're reading this...)
  11208. */
  11209. static int getCpuSpeedInMegaherz();
  11210. /** Returns a string to indicate the CPU vendor.
  11211. Might not be known on some systems.
  11212. */
  11213. static const String getCpuVendor();
  11214. /** Checks whether Intel MMX instructions are available. */
  11215. static bool hasMMX() throw() { return cpuFlags.hasMMX; }
  11216. /** Checks whether Intel SSE instructions are available. */
  11217. static bool hasSSE() throw() { return cpuFlags.hasSSE; }
  11218. /** Checks whether Intel SSE2 instructions are available. */
  11219. static bool hasSSE2() throw() { return cpuFlags.hasSSE2; }
  11220. /** Checks whether AMD 3DNOW instructions are available. */
  11221. static bool has3DNow() throw() { return cpuFlags.has3DNow; }
  11222. /** Returns the number of CPUs.
  11223. */
  11224. static int getNumCpus() throw() { return cpuFlags.numCpus; }
  11225. /** Finds out how much RAM is in the machine.
  11226. @returns the approximate number of megabytes of memory, or zero if
  11227. something goes wrong when finding out.
  11228. */
  11229. static int getMemorySizeInMegabytes();
  11230. /** Returns the system page-size.
  11231. This is only used by programmers with beards.
  11232. */
  11233. static int getPageSize();
  11234. /** Returns a list of MAC addresses found on this machine.
  11235. @param addresses an array into which the MAC addresses should be copied
  11236. @param maxNum the number of elements in this array
  11237. @param littleEndian the endianness of the numbers to return. If this is true,
  11238. the least-significant byte of each number is the first byte
  11239. of the mac address. If false, the least significant byte is
  11240. the last number. Note that the default values of this parameter
  11241. are different on Mac/PC to avoid breaking old software that was
  11242. written before this parameter was added (when the two systems
  11243. defaulted to using different endiannesses). In newer
  11244. software you probably want to specify an explicit value
  11245. for this.
  11246. @returns the number of MAC addresses that were found
  11247. */
  11248. static int getMACAddresses (int64* addresses, int maxNum,
  11249. #if JUCE_MAC
  11250. bool littleEndian = true);
  11251. #else
  11252. bool littleEndian = false);
  11253. #endif
  11254. /** Returns a list of MAC addresses found on this machine.
  11255. @returns an array of strings containing the MAC addresses that were found
  11256. */
  11257. static const StringArray getMACAddressStrings();
  11258. // not-for-public-use platform-specific method gets called at startup to initialise things.
  11259. static void initialiseStats();
  11260. private:
  11261. struct CPUFlags
  11262. {
  11263. int numCpus;
  11264. bool hasMMX : 1;
  11265. bool hasSSE : 1;
  11266. bool hasSSE2 : 1;
  11267. bool has3DNow : 1;
  11268. };
  11269. static CPUFlags cpuFlags;
  11270. SystemStats();
  11271. SystemStats (const SystemStats&);
  11272. SystemStats& operator= (const SystemStats&);
  11273. };
  11274. #endif // __JUCE_SYSTEMSTATS_JUCEHEADER__
  11275. /*** End of inlined file: juce_SystemStats.h ***/
  11276. #endif
  11277. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  11278. #endif
  11279. #ifndef __JUCE_TIME_JUCEHEADER__
  11280. #endif
  11281. #ifndef __JUCE_UUID_JUCEHEADER__
  11282. /*** Start of inlined file: juce_Uuid.h ***/
  11283. #ifndef __JUCE_UUID_JUCEHEADER__
  11284. #define __JUCE_UUID_JUCEHEADER__
  11285. /**
  11286. A universally unique 128-bit identifier.
  11287. This class generates very random unique numbers based on the system time
  11288. and MAC addresses if any are available. It's extremely unlikely that two identical
  11289. UUIDs would ever be created by chance.
  11290. The class includes methods for saving the ID as a string or as raw binary data.
  11291. */
  11292. class JUCE_API Uuid
  11293. {
  11294. public:
  11295. /** Creates a new unique ID. */
  11296. Uuid();
  11297. /** Destructor. */
  11298. ~Uuid() throw();
  11299. /** Creates a copy of another UUID. */
  11300. Uuid (const Uuid& other);
  11301. /** Copies another UUID. */
  11302. Uuid& operator= (const Uuid& other);
  11303. /** Returns true if the ID is zero. */
  11304. bool isNull() const throw();
  11305. /** Compares two UUIDs. */
  11306. bool operator== (const Uuid& other) const;
  11307. /** Compares two UUIDs. */
  11308. bool operator!= (const Uuid& other) const;
  11309. /** Returns a stringified version of this UUID.
  11310. A Uuid object can later be reconstructed from this string using operator= or
  11311. the constructor that takes a string parameter.
  11312. @returns a 32 character hex string.
  11313. */
  11314. const String toString() const;
  11315. /** Creates an ID from an encoded string version.
  11316. @see toString
  11317. */
  11318. Uuid (const String& uuidString);
  11319. /** Copies from a stringified UUID.
  11320. The string passed in should be one that was created with the toString() method.
  11321. */
  11322. Uuid& operator= (const String& uuidString);
  11323. /** Returns a pointer to the internal binary representation of the ID.
  11324. This is an array of 16 bytes. To reconstruct a Uuid from its data, use
  11325. the constructor or operator= method that takes an array of uint8s.
  11326. */
  11327. const uint8* getRawData() const throw() { return value.asBytes; }
  11328. /** Creates a UUID from a 16-byte array.
  11329. @see getRawData
  11330. */
  11331. Uuid (const uint8* const rawData);
  11332. /** Sets this UUID from 16-bytes of raw data. */
  11333. Uuid& operator= (const uint8* const rawData);
  11334. juce_UseDebuggingNewOperator
  11335. private:
  11336. union
  11337. {
  11338. uint8 asBytes [16];
  11339. int asInt[4];
  11340. int64 asInt64[2];
  11341. } value;
  11342. };
  11343. #endif // __JUCE_UUID_JUCEHEADER__
  11344. /*** End of inlined file: juce_Uuid.h ***/
  11345. #endif
  11346. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11347. /*** Start of inlined file: juce_BlowFish.h ***/
  11348. #ifndef __JUCE_BLOWFISH_JUCEHEADER__
  11349. #define __JUCE_BLOWFISH_JUCEHEADER__
  11350. /**
  11351. BlowFish encryption class.
  11352. */
  11353. class JUCE_API BlowFish
  11354. {
  11355. public:
  11356. /** Creates an object that can encode/decode based on the specified key.
  11357. The key data can be up to 72 bytes long.
  11358. */
  11359. BlowFish (const void* keyData, int keyBytes);
  11360. /** Creates a copy of another blowfish object. */
  11361. BlowFish (const BlowFish& other);
  11362. /** Copies another blowfish object. */
  11363. BlowFish& operator= (const BlowFish& other);
  11364. /** Destructor. */
  11365. ~BlowFish();
  11366. /** Encrypts a pair of 32-bit integers. */
  11367. void encrypt (uint32& data1, uint32& data2) const throw();
  11368. /** Decrypts a pair of 32-bit integers. */
  11369. void decrypt (uint32& data1, uint32& data2) const throw();
  11370. juce_UseDebuggingNewOperator
  11371. private:
  11372. uint32 p[18];
  11373. HeapBlock <uint32> s[4];
  11374. uint32 F (uint32 x) const throw();
  11375. };
  11376. #endif // __JUCE_BLOWFISH_JUCEHEADER__
  11377. /*** End of inlined file: juce_BlowFish.h ***/
  11378. #endif
  11379. #ifndef __JUCE_MD5_JUCEHEADER__
  11380. /*** Start of inlined file: juce_MD5.h ***/
  11381. #ifndef __JUCE_MD5_JUCEHEADER__
  11382. #define __JUCE_MD5_JUCEHEADER__
  11383. /**
  11384. MD5 checksum class.
  11385. Create one of these with a block of source data or a string, and it calculates the
  11386. MD5 checksum of that data.
  11387. You can then retrieve this checksum as a 16-byte block, or as a hex string.
  11388. */
  11389. class JUCE_API MD5
  11390. {
  11391. public:
  11392. /** Creates a null MD5 object. */
  11393. MD5();
  11394. /** Creates a copy of another MD5. */
  11395. MD5 (const MD5& other);
  11396. /** Copies another MD5. */
  11397. MD5& operator= (const MD5& other);
  11398. /** Creates a checksum for a block of binary data. */
  11399. explicit MD5 (const MemoryBlock& data);
  11400. /** Creates a checksum for a block of binary data. */
  11401. MD5 (const void* data, const size_t numBytes);
  11402. /** Creates a checksum for a string.
  11403. Note that this operates on the string as a block of unicode characters, so the
  11404. result you get will differ from the value you'd get if the string was treated
  11405. as a block of utf8 or ascii. Bear this in mind if you're comparing the result
  11406. of this method with a checksum created by a different framework, which may have
  11407. used a different encoding.
  11408. */
  11409. explicit MD5 (const String& text);
  11410. /** Creates a checksum for the input from a stream.
  11411. This will read up to the given number of bytes from the stream, and produce the
  11412. checksum of that. If the number of bytes to read is negative, it'll read
  11413. until the stream is exhausted.
  11414. */
  11415. MD5 (InputStream& input, int64 numBytesToRead = -1);
  11416. /** Creates a checksum for a file. */
  11417. explicit MD5 (const File& file);
  11418. /** Destructor. */
  11419. ~MD5();
  11420. /** Returns the checksum as a 16-byte block of data. */
  11421. const MemoryBlock getRawChecksumData() const;
  11422. /** Returns the checksum as a 32-digit hex string. */
  11423. const String toHexString() const;
  11424. /** Compares this to another MD5. */
  11425. bool operator== (const MD5& other) const;
  11426. /** Compares this to another MD5. */
  11427. bool operator!= (const MD5& other) const;
  11428. juce_UseDebuggingNewOperator
  11429. private:
  11430. uint8 result [16];
  11431. struct ProcessContext
  11432. {
  11433. uint8 buffer [64];
  11434. uint32 state [4];
  11435. uint32 count [2];
  11436. ProcessContext();
  11437. void processBlock (const void* data, size_t dataSize);
  11438. void transform (const void* buffer);
  11439. void finish (void* const result);
  11440. };
  11441. void processStream (InputStream& input, int64 numBytesToRead);
  11442. };
  11443. #endif // __JUCE_MD5_JUCEHEADER__
  11444. /*** End of inlined file: juce_MD5.h ***/
  11445. #endif
  11446. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11447. /*** Start of inlined file: juce_Primes.h ***/
  11448. #ifndef __JUCE_PRIMES_JUCEHEADER__
  11449. #define __JUCE_PRIMES_JUCEHEADER__
  11450. /**
  11451. Prime number creation class.
  11452. This class contains static methods for generating and testing prime numbers.
  11453. @see BigInteger
  11454. */
  11455. class JUCE_API Primes
  11456. {
  11457. public:
  11458. /** Creates a random prime number with a given bit-length.
  11459. The certainty parameter specifies how many iterations to use when testing
  11460. for primality. A safe value might be anything over about 20-30.
  11461. The randomSeeds parameter lets you optionally pass it a set of values with
  11462. which to seed the random number generation, improving the security of the
  11463. keys generated.
  11464. */
  11465. static const BigInteger createProbablePrime (int bitLength,
  11466. int certainty,
  11467. const int* randomSeeds = 0,
  11468. int numRandomSeeds = 0);
  11469. /** Tests a number to see if it's prime.
  11470. This isn't a bulletproof test, it uses a Miller-Rabin test to determine
  11471. whether the number is prime.
  11472. The certainty parameter specifies how many iterations to use when testing - a
  11473. safe value might be anything over about 20-30.
  11474. */
  11475. static bool isProbablyPrime (const BigInteger& number, int certainty);
  11476. private:
  11477. Primes();
  11478. Primes (const Primes&);
  11479. Primes& operator= (const Primes&);
  11480. };
  11481. #endif // __JUCE_PRIMES_JUCEHEADER__
  11482. /*** End of inlined file: juce_Primes.h ***/
  11483. #endif
  11484. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11485. /*** Start of inlined file: juce_RSAKey.h ***/
  11486. #ifndef __JUCE_RSAKEY_JUCEHEADER__
  11487. #define __JUCE_RSAKEY_JUCEHEADER__
  11488. /**
  11489. RSA public/private key-pair encryption class.
  11490. An object of this type makes up one half of a public/private RSA key pair. Use the
  11491. createKeyPair() method to create a matching pair for encoding/decoding.
  11492. */
  11493. class JUCE_API RSAKey
  11494. {
  11495. public:
  11496. /** Creates a null key object.
  11497. Initialise a pair of objects for use with the createKeyPair() method.
  11498. */
  11499. RSAKey();
  11500. /** Loads a key from an encoded string representation.
  11501. This reloads a key from a string created by the toString() method.
  11502. */
  11503. explicit RSAKey (const String& stringRepresentation);
  11504. /** Destructor. */
  11505. ~RSAKey();
  11506. bool operator== (const RSAKey& other) const throw();
  11507. bool operator!= (const RSAKey& other) const throw();
  11508. /** Turns the key into a string representation.
  11509. This can be reloaded using the constructor that takes a string.
  11510. */
  11511. const String toString() const;
  11512. /** Encodes or decodes a value.
  11513. Call this on the public key object to encode some data, then use the matching
  11514. private key object to decode it.
  11515. Returns false if the operation couldn't be completed, e.g. if this key hasn't been
  11516. initialised correctly.
  11517. NOTE: This method dumbly applies this key to this data. If you encode some data
  11518. and then try to decode it with a key that doesn't match, this method will still
  11519. happily do its job and return true, but the result won't be what you were expecting.
  11520. It's your responsibility to check that the result is what you wanted.
  11521. */
  11522. bool applyToValue (BigInteger& value) const;
  11523. /** Creates a public/private key-pair.
  11524. Each key will perform one-way encryption that can only be reversed by
  11525. using the other key.
  11526. The numBits parameter specifies the size of key, e.g. 128, 256, 512 bit. Bigger
  11527. sizes are more secure, but this method will take longer to execute.
  11528. The randomSeeds parameter lets you optionally pass it a set of values with
  11529. which to seed the random number generation, improving the security of the
  11530. keys generated. If you supply these, make sure you provide more than 2 values,
  11531. and the more your provide, the better the security.
  11532. */
  11533. static void createKeyPair (RSAKey& publicKey,
  11534. RSAKey& privateKey,
  11535. int numBits,
  11536. const int* randomSeeds = 0,
  11537. int numRandomSeeds = 0);
  11538. juce_UseDebuggingNewOperator
  11539. protected:
  11540. BigInteger part1, part2;
  11541. private:
  11542. static const BigInteger findBestCommonDivisor (const BigInteger& p, const BigInteger& q);
  11543. };
  11544. #endif // __JUCE_RSAKEY_JUCEHEADER__
  11545. /*** End of inlined file: juce_RSAKey.h ***/
  11546. #endif
  11547. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11548. /*** Start of inlined file: juce_DirectoryIterator.h ***/
  11549. #ifndef __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11550. #define __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11551. /**
  11552. Searches through a the files in a directory, returning each file that is found.
  11553. A DirectoryIterator will search through a directory and its subdirectories using
  11554. a wildcard filepattern match.
  11555. If you may be finding a large number of files, this is better than
  11556. using File::findChildFiles() because it doesn't block while it finds them
  11557. all, and this is more memory-efficient.
  11558. It can also guess how far it's got using a wildly inaccurate algorithm.
  11559. */
  11560. class JUCE_API DirectoryIterator
  11561. {
  11562. public:
  11563. /** Creates a DirectoryIterator for a given directory.
  11564. After creating one of these, call its next() method to get the
  11565. first file - e.g. @code
  11566. DirectoryIterator iter (File ("/animals/mooses"), true, "*.moose");
  11567. while (iter.next())
  11568. {
  11569. File theFileItFound (iter.getFile());
  11570. ... etc
  11571. }
  11572. @endcode
  11573. @param directory the directory to search in
  11574. @param isRecursive whether all the subdirectories should also be searched
  11575. @param wildCard the file pattern to match
  11576. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying
  11577. whether to look for files, directories, or both.
  11578. */
  11579. DirectoryIterator (const File& directory,
  11580. bool isRecursive,
  11581. const String& wildCard = "*",
  11582. int whatToLookFor = File::findFiles);
  11583. /** Destructor. */
  11584. ~DirectoryIterator();
  11585. /** Moves the iterator along to the next file.
  11586. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11587. false if there are no more matching files.
  11588. */
  11589. bool next();
  11590. /** Moves the iterator along to the next file, and returns various properties of that file.
  11591. If you need to find out details about the file, it's more efficient to call this method than
  11592. to call the normal next() method and then find out the details afterwards.
  11593. All the parameters are optional, so pass null pointers for any items that you're not
  11594. interested in.
  11595. @returns true if a file was found (you can then use getFile() to see what it was) - or
  11596. false if there are no more matching files. If it returns false, then none of the
  11597. parameters will be filled-in.
  11598. */
  11599. bool next (bool* isDirectory, bool* isHidden, int64* fileSize,
  11600. Time* modTime, Time* creationTime, bool* isReadOnly);
  11601. /** Returns the file that the iterator is currently pointing at.
  11602. The result of this call is only valid after a call to next() has returned true.
  11603. */
  11604. const File getFile() const;
  11605. /** Returns a guess of how far through the search the iterator has got.
  11606. @returns a value 0.0 to 1.0 to show the progress, although this won't be
  11607. very accurate.
  11608. */
  11609. float getEstimatedProgress() const;
  11610. juce_UseDebuggingNewOperator
  11611. private:
  11612. friend class File;
  11613. class NativeIterator
  11614. {
  11615. public:
  11616. NativeIterator (const File& directory, const String& wildCard);
  11617. ~NativeIterator();
  11618. bool next (String& filenameFound,
  11619. bool* isDirectory, bool* isHidden, int64* fileSize,
  11620. Time* modTime, Time* creationTime, bool* isReadOnly);
  11621. class Pimpl;
  11622. juce_UseDebuggingNewOperator
  11623. private:
  11624. friend class DirectoryIterator;
  11625. friend class ScopedPointer<Pimpl>;
  11626. ScopedPointer<Pimpl> pimpl;
  11627. NativeIterator (const NativeIterator&);
  11628. NativeIterator& operator= (const NativeIterator&);
  11629. };
  11630. friend class ScopedPointer<NativeIterator::Pimpl>;
  11631. NativeIterator fileFinder;
  11632. String wildCard, path;
  11633. int index;
  11634. mutable int totalNumFiles;
  11635. const int whatToLookFor;
  11636. const bool isRecursive;
  11637. ScopedPointer <DirectoryIterator> subIterator;
  11638. File currentFile;
  11639. DirectoryIterator (const DirectoryIterator&);
  11640. DirectoryIterator& operator= (const DirectoryIterator&);
  11641. };
  11642. #endif // __JUCE_DIRECTORYITERATOR_JUCEHEADER__
  11643. /*** End of inlined file: juce_DirectoryIterator.h ***/
  11644. #endif
  11645. #ifndef __JUCE_FILE_JUCEHEADER__
  11646. #endif
  11647. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11648. /*** Start of inlined file: juce_FileInputStream.h ***/
  11649. #ifndef __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11650. #define __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11651. /**
  11652. An input stream that reads from a local file.
  11653. @see InputStream, FileOutputStream, File::createInputStream
  11654. */
  11655. class JUCE_API FileInputStream : public InputStream
  11656. {
  11657. public:
  11658. /** Creates a FileInputStream.
  11659. @param fileToRead the file to read from - if the file can't be accessed for some
  11660. reason, then the stream will just contain no data
  11661. */
  11662. explicit FileInputStream (const File& fileToRead);
  11663. /** Destructor. */
  11664. ~FileInputStream();
  11665. const File& getFile() const throw() { return file; }
  11666. int64 getTotalLength();
  11667. int read (void* destBuffer, int maxBytesToRead);
  11668. bool isExhausted();
  11669. int64 getPosition();
  11670. bool setPosition (int64 pos);
  11671. juce_UseDebuggingNewOperator
  11672. private:
  11673. File file;
  11674. void* fileHandle;
  11675. int64 currentPosition, totalSize;
  11676. bool needToSeek;
  11677. FileInputStream (const FileInputStream&);
  11678. FileInputStream& operator= (const FileInputStream&);
  11679. };
  11680. #endif // __JUCE_FILEINPUTSTREAM_JUCEHEADER__
  11681. /*** End of inlined file: juce_FileInputStream.h ***/
  11682. #endif
  11683. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11684. /*** Start of inlined file: juce_FileOutputStream.h ***/
  11685. #ifndef __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11686. #define __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11687. /**
  11688. An output stream that writes into a local file.
  11689. @see OutputStream, FileInputStream, File::createOutputStream
  11690. */
  11691. class JUCE_API FileOutputStream : public OutputStream
  11692. {
  11693. public:
  11694. /** Creates a FileOutputStream.
  11695. If the file doesn't exist, it will first be created. If the file can't be
  11696. created or opened, the failedToOpen() method will return
  11697. true.
  11698. If the file already exists when opened, the stream's write-postion will
  11699. be set to the end of the file. To overwrite an existing file,
  11700. use File::deleteFile() before opening the stream, or use setPosition(0)
  11701. after it's opened (although this won't truncate the file).
  11702. It's better to use File::createOutputStream() to create one of these, rather
  11703. than using the class directly.
  11704. @see TemporaryFile
  11705. */
  11706. FileOutputStream (const File& fileToWriteTo,
  11707. int bufferSizeToUse = 16384);
  11708. /** Destructor. */
  11709. ~FileOutputStream();
  11710. /** Returns the file that this stream is writing to.
  11711. */
  11712. const File& getFile() const { return file; }
  11713. /** Returns true if the stream couldn't be opened for some reason.
  11714. */
  11715. bool failedToOpen() const { return fileHandle == 0; }
  11716. void flush();
  11717. int64 getPosition();
  11718. bool setPosition (int64 pos);
  11719. bool write (const void* data, int numBytes);
  11720. juce_UseDebuggingNewOperator
  11721. private:
  11722. File file;
  11723. void* fileHandle;
  11724. int64 currentPosition;
  11725. int bufferSize, bytesInBuffer;
  11726. HeapBlock <char> buffer;
  11727. void flushInternal();
  11728. int64 getPositionInternal() const;
  11729. FileOutputStream (const FileOutputStream&);
  11730. FileOutputStream& operator= (const FileOutputStream&);
  11731. };
  11732. #endif // __JUCE_FILEOUTPUTSTREAM_JUCEHEADER__
  11733. /*** End of inlined file: juce_FileOutputStream.h ***/
  11734. #endif
  11735. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11736. /*** Start of inlined file: juce_FileSearchPath.h ***/
  11737. #ifndef __JUCE_FILESEARCHPATH_JUCEHEADER__
  11738. #define __JUCE_FILESEARCHPATH_JUCEHEADER__
  11739. /**
  11740. Encapsulates a set of folders that make up a search path.
  11741. @see File
  11742. */
  11743. class JUCE_API FileSearchPath
  11744. {
  11745. public:
  11746. /** Creates an empty search path. */
  11747. FileSearchPath();
  11748. /** Creates a search path from a string of pathnames.
  11749. The path can be semicolon- or comma-separated, e.g.
  11750. "/foo/bar;/foo/moose;/fish/moose"
  11751. The separate folders are tokenised and added to the search path.
  11752. */
  11753. FileSearchPath (const String& path);
  11754. /** Creates a copy of another search path. */
  11755. FileSearchPath (const FileSearchPath& other);
  11756. /** Destructor. */
  11757. ~FileSearchPath();
  11758. /** Uses a string containing a list of pathnames to re-initialise this list.
  11759. This search path is cleared and the semicolon- or comma-separated folders
  11760. in this string are added instead. e.g. "/foo/bar;/foo/moose;/fish/moose"
  11761. */
  11762. FileSearchPath& operator= (const String& path);
  11763. /** Returns the number of folders in this search path.
  11764. @see operator[]
  11765. */
  11766. int getNumPaths() const;
  11767. /** Returns one of the folders in this search path.
  11768. The file returned isn't guaranteed to actually be a valid directory.
  11769. @see getNumPaths
  11770. */
  11771. const File operator[] (int index) const;
  11772. /** Returns the search path as a semicolon-separated list of directories. */
  11773. const String toString() const;
  11774. /** Adds a new directory to the search path.
  11775. The new directory is added to the end of the list if the insertIndex parameter is
  11776. less than zero, otherwise it is inserted at the given index.
  11777. */
  11778. void add (const File& directoryToAdd,
  11779. int insertIndex = -1);
  11780. /** Adds a new directory to the search path if it's not already in there. */
  11781. void addIfNotAlreadyThere (const File& directoryToAdd);
  11782. /** Removes a directory from the search path. */
  11783. void remove (int indexToRemove);
  11784. /** Merges another search path into this one.
  11785. This will remove any duplicate directories.
  11786. */
  11787. void addPath (const FileSearchPath& other);
  11788. /** Removes any directories that are actually subdirectories of one of the other directories in the search path.
  11789. If the search is intended to be recursive, there's no point having nested folders in the search
  11790. path, because they'll just get searched twice and you'll get duplicate results.
  11791. e.g. if the path is "c:\abc\de;c:\abc", this method will simplify it to "c:\abc"
  11792. */
  11793. void removeRedundantPaths();
  11794. /** Removes any directories that don't actually exist. */
  11795. void removeNonExistentPaths();
  11796. /** Searches the path for a wildcard.
  11797. This will search all the directories in the search path in order, adding any
  11798. matching files to the results array.
  11799. @param results an array to append the results to
  11800. @param whatToLookFor a value from the File::TypesOfFileToFind enum, specifying whether to
  11801. return files, directories, or both.
  11802. @param searchRecursively whether to recursively search the subdirectories too
  11803. @param wildCardPattern a pattern to match against the filenames
  11804. @returns the number of files added to the array
  11805. @see File::findChildFiles
  11806. */
  11807. int findChildFiles (Array<File>& results,
  11808. int whatToLookFor,
  11809. bool searchRecursively,
  11810. const String& wildCardPattern = "*") const;
  11811. /** Finds out whether a file is inside one of the path's directories.
  11812. This will return true if the specified file is a child of one of the
  11813. directories specified by this path. Note that this doesn't actually do any
  11814. searching or check that the files exist - it just looks at the pathnames
  11815. to work out whether the file would be inside a directory.
  11816. @param fileToCheck the file to look for
  11817. @param checkRecursively if true, then this will return true if the file is inside a
  11818. subfolder of one of the path's directories (at any depth). If false
  11819. it will only return true if the file is actually a direct child
  11820. of one of the directories.
  11821. @see File::isAChildOf
  11822. */
  11823. bool isFileInPath (const File& fileToCheck,
  11824. bool checkRecursively) const;
  11825. juce_UseDebuggingNewOperator
  11826. private:
  11827. StringArray directories;
  11828. void init (const String& path);
  11829. };
  11830. #endif // __JUCE_FILESEARCHPATH_JUCEHEADER__
  11831. /*** End of inlined file: juce_FileSearchPath.h ***/
  11832. #endif
  11833. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11834. /*** Start of inlined file: juce_NamedPipe.h ***/
  11835. #ifndef __JUCE_NAMEDPIPE_JUCEHEADER__
  11836. #define __JUCE_NAMEDPIPE_JUCEHEADER__
  11837. /**
  11838. A cross-process pipe that can have data written to and read from it.
  11839. Two or more processes can use these for inter-process communication.
  11840. @see InterprocessConnection
  11841. */
  11842. class JUCE_API NamedPipe
  11843. {
  11844. public:
  11845. /** Creates a NamedPipe. */
  11846. NamedPipe();
  11847. /** Destructor. */
  11848. ~NamedPipe();
  11849. /** Tries to open a pipe that already exists.
  11850. Returns true if it succeeds.
  11851. */
  11852. bool openExisting (const String& pipeName);
  11853. /** Tries to create a new pipe.
  11854. Returns true if it succeeds.
  11855. */
  11856. bool createNewPipe (const String& pipeName);
  11857. /** Closes the pipe, if it's open. */
  11858. void close();
  11859. /** True if the pipe is currently open. */
  11860. bool isOpen() const;
  11861. /** Returns the last name that was used to try to open this pipe. */
  11862. const String getName() const;
  11863. /** Reads data from the pipe.
  11864. This will block until another thread has written enough data into the pipe to fill
  11865. the number of bytes specified, or until another thread calls the cancelPendingReads()
  11866. method.
  11867. If the operation fails, it returns -1, otherwise, it will return the number of
  11868. bytes read.
  11869. If timeOutMilliseconds is less than zero, it will wait indefinitely, otherwise
  11870. this is a maximum timeout for reading from the pipe.
  11871. */
  11872. int read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds = 5000);
  11873. /** Writes some data to the pipe.
  11874. If the operation fails, it returns -1, otherwise, it will return the number of
  11875. bytes written.
  11876. */
  11877. int write (const void* sourceBuffer, int numBytesToWrite,
  11878. int timeOutMilliseconds = 2000);
  11879. /** If any threads are currently blocked on a read operation, this tells them to abort.
  11880. */
  11881. void cancelPendingReads();
  11882. juce_UseDebuggingNewOperator
  11883. private:
  11884. void* internal;
  11885. String currentPipeName;
  11886. CriticalSection lock;
  11887. NamedPipe (const NamedPipe&);
  11888. NamedPipe& operator= (const NamedPipe&);
  11889. bool openInternal (const String& pipeName, const bool createPipe);
  11890. };
  11891. #endif // __JUCE_NAMEDPIPE_JUCEHEADER__
  11892. /*** End of inlined file: juce_NamedPipe.h ***/
  11893. #endif
  11894. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11895. /*** Start of inlined file: juce_TemporaryFile.h ***/
  11896. #ifndef __JUCE_TEMPORARYFILE_JUCEHEADER__
  11897. #define __JUCE_TEMPORARYFILE_JUCEHEADER__
  11898. /**
  11899. Manages a temporary file, which will be deleted when this object is deleted.
  11900. This object is intended to be used as a stack based object, using its scope
  11901. to make sure the temporary file isn't left lying around.
  11902. For example:
  11903. @code
  11904. {
  11905. File myTargetFile ("~/myfile.txt");
  11906. // this will choose a file called something like "~/myfile_temp239348.txt"
  11907. // which definitely doesn't exist at the time the constructor is called.
  11908. TemporaryFile temp (myTargetFile);
  11909. // create a stream to the temporary file, and write some data to it...
  11910. ScopedPointer <FileOutputStream> out (temp.getFile().createOutputStream());
  11911. if (out != 0)
  11912. {
  11913. out->write ( ...etc )
  11914. out->flush();
  11915. out = 0; // (deletes the stream)
  11916. // ..now we've finished writing, this will rename the temp file to
  11917. // make it replace the target file we specified above.
  11918. bool succeeded = temp.overwriteTargetFileWithTemporary();
  11919. }
  11920. // ..and even if something went wrong and our overwrite failed,
  11921. // as the TemporaryFile object goes out of scope here, it'll make sure
  11922. // that the temp file gets deleted.
  11923. }
  11924. @endcode
  11925. @see File, FileOutputStream
  11926. */
  11927. class JUCE_API TemporaryFile
  11928. {
  11929. public:
  11930. enum OptionFlags
  11931. {
  11932. useHiddenFile = 1, /**< Indicates that the temporary file should be hidden -
  11933. i.e. its name should start with a dot. */
  11934. putNumbersInBrackets = 2 /**< Indicates that when numbers are appended to make sure
  11935. the file is unique, they should go in brackets rather
  11936. than just being appended (see File::getNonexistentSibling() )*/
  11937. };
  11938. /** Creates a randomly-named temporary file in the default temp directory.
  11939. @param suffix a file suffix to use for the file
  11940. @param optionFlags a combination of the values listed in the OptionFlags enum
  11941. The file will not be created until you write to it. And remember that when
  11942. this object is deleted, the file will also be deleted!
  11943. */
  11944. TemporaryFile (const String& suffix = String::empty,
  11945. int optionFlags = 0);
  11946. /** Creates a temporary file in the same directory as a specified file.
  11947. This is useful if you have a file that you want to overwrite, but don't
  11948. want to harm the original file if the write operation fails. You can
  11949. use this to create a temporary file next to the target file, then
  11950. write to the temporary file, and finally use overwriteTargetFileWithTemporary()
  11951. to replace the target file with the one you've just written.
  11952. This class won't create any files until you actually write to them. And remember
  11953. that when this object is deleted, the temporary file will also be deleted!
  11954. @param targetFile the file that you intend to overwrite - the temporary
  11955. file will be created in the same directory as this
  11956. @param optionFlags a combination of the values listed in the OptionFlags enum
  11957. */
  11958. TemporaryFile (const File& targetFile,
  11959. int optionFlags = 0);
  11960. /** Destructor.
  11961. When this object is deleted it will make sure that its temporary file is
  11962. also deleted! If the operation fails, it'll throw an assertion in debug
  11963. mode.
  11964. */
  11965. ~TemporaryFile();
  11966. /** Returns the temporary file. */
  11967. const File getFile() const { return temporaryFile; }
  11968. /** Returns the target file that was specified in the constructor. */
  11969. const File getTargetFile() const { return targetFile; }
  11970. /** Tries to move the temporary file to overwrite the target file that was
  11971. specified in the constructor.
  11972. If you used the constructor that specified a target file, this will attempt
  11973. to replace that file with the temporary one.
  11974. Before calling this, make sure:
  11975. - that you've actually written to the temporary file
  11976. - that you've closed any open streams that you were using to write to it
  11977. - and that you don't have any streams open to the target file, which would
  11978. prevent it being overwritten
  11979. If the file move succeeds, this returns false, and the temporary file will
  11980. have disappeared. If it fails, the temporary file will probably still exist,
  11981. but will be deleted when this object is destroyed.
  11982. */
  11983. bool overwriteTargetFileWithTemporary() const;
  11984. juce_UseDebuggingNewOperator
  11985. private:
  11986. File temporaryFile, targetFile;
  11987. void createTempFile (const File& parentDirectory, String name, const String& suffix, int optionFlags);
  11988. TemporaryFile (const TemporaryFile&);
  11989. TemporaryFile& operator= (const TemporaryFile&);
  11990. };
  11991. #endif // __JUCE_TEMPORARYFILE_JUCEHEADER__
  11992. /*** End of inlined file: juce_TemporaryFile.h ***/
  11993. #endif
  11994. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11995. /*** Start of inlined file: juce_ZipFile.h ***/
  11996. #ifndef __JUCE_ZIPFILE_JUCEHEADER__
  11997. #define __JUCE_ZIPFILE_JUCEHEADER__
  11998. /*** Start of inlined file: juce_InputSource.h ***/
  11999. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12000. #define __JUCE_INPUTSOURCE_JUCEHEADER__
  12001. /**
  12002. A lightweight object that can create a stream to read some kind of resource.
  12003. This may be used to refer to a file, or some other kind of source, allowing a
  12004. caller to create an input stream that can read from it when required.
  12005. @see FileInputSource
  12006. */
  12007. class JUCE_API InputSource
  12008. {
  12009. public:
  12010. InputSource() throw() {}
  12011. /** Destructor. */
  12012. virtual ~InputSource() {}
  12013. /** Returns a new InputStream to read this item.
  12014. @returns an inputstream that the caller will delete, or 0 if
  12015. the filename isn't found.
  12016. */
  12017. virtual InputStream* createInputStream() = 0;
  12018. /** Returns a new InputStream to read an item, relative.
  12019. @param relatedItemPath the relative pathname of the resource that is required
  12020. @returns an inputstream that the caller will delete, or 0 if
  12021. the item isn't found.
  12022. */
  12023. virtual InputStream* createInputStreamFor (const String& relatedItemPath) = 0;
  12024. /** Returns a hash code that uniquely represents this item.
  12025. */
  12026. virtual int64 hashCode() const = 0;
  12027. juce_UseDebuggingNewOperator
  12028. };
  12029. #endif // __JUCE_INPUTSOURCE_JUCEHEADER__
  12030. /*** End of inlined file: juce_InputSource.h ***/
  12031. /**
  12032. Decodes a ZIP file from a stream.
  12033. This can enumerate the items in a ZIP file and can create suitable stream objects
  12034. to read each one.
  12035. */
  12036. class JUCE_API ZipFile
  12037. {
  12038. public:
  12039. /** Creates a ZipFile for a given stream.
  12040. @param inputStream the stream to read from
  12041. @param deleteStreamWhenDestroyed if set to true, the object passed-in
  12042. will be deleted when this ZipFile object is deleted
  12043. */
  12044. ZipFile (InputStream* inputStream, bool deleteStreamWhenDestroyed);
  12045. /** Creates a ZipFile based for a file. */
  12046. ZipFile (const File& file);
  12047. /** Creates a ZipFile for an input source.
  12048. The inputSource object will be owned by the zip file, which will delete
  12049. it later when not needed.
  12050. */
  12051. ZipFile (InputSource* inputSource);
  12052. /** Destructor. */
  12053. ~ZipFile();
  12054. /**
  12055. Contains information about one of the entries in a ZipFile.
  12056. @see ZipFile::getEntry
  12057. */
  12058. struct ZipEntry
  12059. {
  12060. /** The name of the file, which may also include a partial pathname. */
  12061. String filename;
  12062. /** The file's original size. */
  12063. unsigned int uncompressedSize;
  12064. /** The last time the file was modified. */
  12065. Time fileTime;
  12066. };
  12067. /** Returns the number of items in the zip file. */
  12068. int getNumEntries() const throw();
  12069. /** Returns a structure that describes one of the entries in the zip file.
  12070. This may return zero if the index is out of range.
  12071. @see ZipFile::ZipEntry
  12072. */
  12073. const ZipEntry* getEntry (int index) const throw();
  12074. /** Returns the index of the first entry with a given filename.
  12075. This uses a case-sensitive comparison to look for a filename in the
  12076. list of entries. It might return -1 if no match is found.
  12077. @see ZipFile::ZipEntry
  12078. */
  12079. int getIndexOfFileName (const String& fileName) const throw();
  12080. /** Returns a structure that describes one of the entries in the zip file.
  12081. This uses a case-sensitive comparison to look for a filename in the
  12082. list of entries. It might return 0 if no match is found.
  12083. @see ZipFile::ZipEntry
  12084. */
  12085. const ZipEntry* getEntry (const String& fileName) const throw();
  12086. /** Sorts the list of entries, based on the filename.
  12087. */
  12088. void sortEntriesByFilename();
  12089. /** Creates a stream that can read from one of the zip file's entries.
  12090. The stream that is returned must be deleted by the caller (and
  12091. zero might be returned if a stream can't be opened for some reason).
  12092. The stream must not be used after the ZipFile object that created
  12093. has been deleted.
  12094. */
  12095. InputStream* createStreamForEntry (int index);
  12096. /** Uncompresses all of the files in the zip file.
  12097. This will expand all the entires into a target directory. The relative
  12098. paths of the entries are used.
  12099. @param targetDirectory the root folder to uncompress to
  12100. @param shouldOverwriteFiles whether to overwrite existing files with similarly-named ones
  12101. */
  12102. void uncompressTo (const File& targetDirectory,
  12103. bool shouldOverwriteFiles = true);
  12104. juce_UseDebuggingNewOperator
  12105. private:
  12106. class ZipInputStream;
  12107. class ZipFilenameComparator;
  12108. class ZipEntryInfo;
  12109. friend class ZipInputStream;
  12110. friend class ZipFilenameComparator;
  12111. friend class ZipEntryInfo;
  12112. OwnedArray <ZipEntryInfo> entries;
  12113. CriticalSection lock;
  12114. InputStream* inputStream;
  12115. ScopedPointer <InputStream> streamToDelete;
  12116. ScopedPointer <InputSource> inputSource;
  12117. #if JUCE_DEBUG
  12118. int numOpenStreams;
  12119. #endif
  12120. void init();
  12121. int findEndOfZipEntryTable (InputStream* in, int& numEntries);
  12122. static int compareElements (const ZipEntryInfo* first, const ZipEntryInfo* second);
  12123. ZipFile (const ZipFile&);
  12124. ZipFile& operator= (const ZipFile&);
  12125. };
  12126. #endif // __JUCE_ZIPFILE_JUCEHEADER__
  12127. /*** End of inlined file: juce_ZipFile.h ***/
  12128. #endif
  12129. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12130. /*** Start of inlined file: juce_Socket.h ***/
  12131. #ifndef __JUCE_SOCKET_JUCEHEADER__
  12132. #define __JUCE_SOCKET_JUCEHEADER__
  12133. /**
  12134. A wrapper for a streaming (TCP) socket.
  12135. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12136. sockets, you could also try the InterprocessConnection class.
  12137. @see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
  12138. */
  12139. class JUCE_API StreamingSocket
  12140. {
  12141. public:
  12142. /** Creates an uninitialised socket.
  12143. To connect it, use the connect() method, after which you can read() or write()
  12144. to it.
  12145. To wait for other sockets to connect to this one, the createListener() method
  12146. enters "listener" mode, and can be used to spawn new sockets for each connection
  12147. that comes along.
  12148. */
  12149. StreamingSocket();
  12150. /** Destructor. */
  12151. ~StreamingSocket();
  12152. /** Binds the socket to the specified local port.
  12153. @returns true on success; false may indicate that another socket is already bound
  12154. on the same port
  12155. */
  12156. bool bindToPort (int localPortNumber);
  12157. /** Tries to connect the socket to hostname:port.
  12158. If timeOutMillisecs is 0, then this method will block until the operating system
  12159. rejects the connection (which could take a long time).
  12160. @returns true if it succeeds.
  12161. @see isConnected
  12162. */
  12163. bool connect (const String& remoteHostname,
  12164. int remotePortNumber,
  12165. int timeOutMillisecs = 3000);
  12166. /** True if the socket is currently connected. */
  12167. bool isConnected() const throw() { return connected; }
  12168. /** Closes the connection. */
  12169. void close();
  12170. /** Returns the name of the currently connected host. */
  12171. const String& getHostName() const throw() { return hostName; }
  12172. /** Returns the port number that's currently open. */
  12173. int getPort() const throw() { return portNumber; }
  12174. /** True if the socket is connected to this machine rather than over the network. */
  12175. bool isLocal() const throw();
  12176. /** Waits until the socket is ready for reading or writing.
  12177. If readyForReading is true, it will wait until the socket is ready for
  12178. reading; if false, it will wait until it's ready for writing.
  12179. If the timeout is < 0, it will wait forever, or else will give up after
  12180. the specified time.
  12181. If the socket is ready on return, this returns 1. If it times-out before
  12182. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12183. */
  12184. int waitUntilReady (bool readyForReading,
  12185. int timeoutMsecs) const;
  12186. /** Reads bytes from the socket.
  12187. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12188. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12189. flag is false, the method will return as much data as is currently available
  12190. without blocking.
  12191. @returns the number of bytes read, or -1 if there was an error.
  12192. @see waitUntilReady
  12193. */
  12194. int read (void* destBuffer, int maxBytesToRead,
  12195. bool blockUntilSpecifiedAmountHasArrived);
  12196. /** Writes bytes to the socket from a buffer.
  12197. Note that this method will block unless you have checked the socket is ready
  12198. for writing before calling it (see the waitUntilReady() method).
  12199. @returns the number of bytes written, or -1 if there was an error.
  12200. */
  12201. int write (const void* sourceBuffer, int numBytesToWrite);
  12202. /** Puts this socket into "listener" mode.
  12203. When in this mode, your thread can call waitForNextConnection() repeatedly,
  12204. which will spawn new sockets for each new connection, so that these can
  12205. be handled in parallel by other threads.
  12206. @param portNumber the port number to listen on
  12207. @param localHostName the interface address to listen on - pass an empty
  12208. string to listen on all addresses
  12209. @returns true if it manages to open the socket successfully.
  12210. @see waitForNextConnection
  12211. */
  12212. bool createListener (int portNumber, const String& localHostName = String::empty);
  12213. /** When in "listener" mode, this waits for a connection and spawns it as a new
  12214. socket.
  12215. The object that gets returned will be owned by the caller.
  12216. This method can only be called after using createListener().
  12217. @see createListener
  12218. */
  12219. StreamingSocket* waitForNextConnection() const;
  12220. juce_UseDebuggingNewOperator
  12221. private:
  12222. String hostName;
  12223. int volatile portNumber, handle;
  12224. bool connected, isListener;
  12225. StreamingSocket (const String& hostname, int portNumber, int handle);
  12226. StreamingSocket (const StreamingSocket&);
  12227. StreamingSocket& operator= (const StreamingSocket&);
  12228. };
  12229. /**
  12230. A wrapper for a datagram (UDP) socket.
  12231. This allows low-level use of sockets; for an easier-to-use messaging layer on top of
  12232. sockets, you could also try the InterprocessConnection class.
  12233. @see StreamingSocket, InterprocessConnection, InterprocessConnectionServer
  12234. */
  12235. class JUCE_API DatagramSocket
  12236. {
  12237. public:
  12238. /**
  12239. Creates an (uninitialised) datagram socket.
  12240. The localPortNumber is the port on which to bind this socket. If this value is 0,
  12241. the port number is assigned by the operating system.
  12242. To use the socket for sending, call the connect() method. This will not immediately
  12243. make a connection, but will save the destination you've provided. After this, you can
  12244. call read() or write().
  12245. If enableBroadcasting is true, the socket will be allowed to send broadcast messages
  12246. (may require extra privileges on linux)
  12247. To wait for other sockets to connect to this one, call waitForNextConnection().
  12248. */
  12249. DatagramSocket (int localPortNumber,
  12250. bool enableBroadcasting = false);
  12251. /** Destructor. */
  12252. ~DatagramSocket();
  12253. /** Binds the socket to the specified local port.
  12254. @returns true on success; false may indicate that another socket is already bound
  12255. on the same port
  12256. */
  12257. bool bindToPort (int localPortNumber);
  12258. /** Tries to connect the socket to hostname:port.
  12259. If timeOutMillisecs is 0, then this method will block until the operating system
  12260. rejects the connection (which could take a long time).
  12261. @returns true if it succeeds.
  12262. @see isConnected
  12263. */
  12264. bool connect (const String& remoteHostname,
  12265. int remotePortNumber,
  12266. int timeOutMillisecs = 3000);
  12267. /** True if the socket is currently connected. */
  12268. bool isConnected() const throw() { return connected; }
  12269. /** Closes the connection. */
  12270. void close();
  12271. /** Returns the name of the currently connected host. */
  12272. const String& getHostName() const throw() { return hostName; }
  12273. /** Returns the port number that's currently open. */
  12274. int getPort() const throw() { return portNumber; }
  12275. /** True if the socket is connected to this machine rather than over the network. */
  12276. bool isLocal() const throw();
  12277. /** Waits until the socket is ready for reading or writing.
  12278. If readyForReading is true, it will wait until the socket is ready for
  12279. reading; if false, it will wait until it's ready for writing.
  12280. If the timeout is < 0, it will wait forever, or else will give up after
  12281. the specified time.
  12282. If the socket is ready on return, this returns 1. If it times-out before
  12283. the socket becomes ready, it returns 0. If an error occurs, it returns -1.
  12284. */
  12285. int waitUntilReady (bool readyForReading,
  12286. int timeoutMsecs) const;
  12287. /** Reads bytes from the socket.
  12288. If blockUntilSpecifiedAmountHasArrived is true, the method will block until
  12289. maxBytesToRead bytes have been read, (or until an error occurs). If this
  12290. flag is false, the method will return as much data as is currently available
  12291. without blocking.
  12292. @returns the number of bytes read, or -1 if there was an error.
  12293. @see waitUntilReady
  12294. */
  12295. int read (void* destBuffer, int maxBytesToRead,
  12296. bool blockUntilSpecifiedAmountHasArrived);
  12297. /** Writes bytes to the socket from a buffer.
  12298. Note that this method will block unless you have checked the socket is ready
  12299. for writing before calling it (see the waitUntilReady() method).
  12300. @returns the number of bytes written, or -1 if there was an error.
  12301. */
  12302. int write (const void* sourceBuffer, int numBytesToWrite);
  12303. /** This waits for incoming data to be sent, and returns a socket that can be used
  12304. to read it.
  12305. The object that gets returned is owned by the caller, and can't be used for
  12306. sending, but can be used to read the data.
  12307. */
  12308. DatagramSocket* waitForNextConnection() const;
  12309. juce_UseDebuggingNewOperator
  12310. private:
  12311. String hostName;
  12312. int volatile portNumber, handle;
  12313. bool connected, allowBroadcast;
  12314. void* serverAddress;
  12315. DatagramSocket (const String& hostname, int portNumber, int handle, int localPortNumber);
  12316. DatagramSocket (const DatagramSocket&);
  12317. DatagramSocket& operator= (const DatagramSocket&);
  12318. };
  12319. #endif // __JUCE_SOCKET_JUCEHEADER__
  12320. /*** End of inlined file: juce_Socket.h ***/
  12321. #endif
  12322. #ifndef __JUCE_URL_JUCEHEADER__
  12323. /*** Start of inlined file: juce_URL.h ***/
  12324. #ifndef __JUCE_URL_JUCEHEADER__
  12325. #define __JUCE_URL_JUCEHEADER__
  12326. /**
  12327. Represents a URL and has a bunch of useful functions to manipulate it.
  12328. This class can be used to launch URLs in browsers, and also to create
  12329. InputStreams that can read from remote http or ftp sources.
  12330. */
  12331. class JUCE_API URL
  12332. {
  12333. public:
  12334. /** Creates an empty URL. */
  12335. URL();
  12336. /** Creates a URL from a string. */
  12337. URL (const String& url);
  12338. /** Creates a copy of another URL. */
  12339. URL (const URL& other);
  12340. /** Destructor. */
  12341. ~URL();
  12342. /** Copies this URL from another one. */
  12343. URL& operator= (const URL& other);
  12344. /** Returns a string version of the URL.
  12345. If includeGetParameters is true and any parameters have been set with the
  12346. withParameter() method, then the string will have these appended on the
  12347. end and url-encoded.
  12348. */
  12349. const String toString (bool includeGetParameters) const;
  12350. /** True if it seems to be valid. */
  12351. bool isWellFormed() const;
  12352. /** Returns just the domain part of the URL.
  12353. E.g. for "http://www.xyz.com/foobar", this will return "www.xyz.com".
  12354. */
  12355. const String getDomain() const;
  12356. /** Returns the path part of the URL.
  12357. E.g. for "http://www.xyz.com/foo/bar?x=1", this will return "foo/bar".
  12358. */
  12359. const String getSubPath() const;
  12360. /** Returns the scheme of the URL.
  12361. E.g. for "http://www.xyz.com/foobar", this will return "http". (It won't
  12362. include the colon).
  12363. */
  12364. const String getScheme() const;
  12365. /** Returns a new version of this URL that uses a different sub-path.
  12366. E.g. if the URL is "http://www.xyz.com/foo?x=1" and you call this with
  12367. "bar", it'll return "http://www.xyz.com/bar?x=1".
  12368. */
  12369. const URL withNewSubPath (const String& newPath) const;
  12370. /** Returns a copy of this URL, with a GET or POST parameter added to the end.
  12371. Any control characters in the value will be encoded.
  12372. e.g. calling "withParameter ("amount", "some fish") for the url "www.fish.com"
  12373. would produce a new url whose toString(true) method would return
  12374. "www.fish.com?amount=some+fish".
  12375. */
  12376. const URL withParameter (const String& parameterName,
  12377. const String& parameterValue) const;
  12378. /** Returns a copy of this URl, with a file-upload type parameter added to it.
  12379. When performing a POST where one of your parameters is a binary file, this
  12380. lets you specify the file.
  12381. Note that the filename is stored, but the file itself won't actually be read
  12382. until this URL is later used to create a network input stream.
  12383. */
  12384. const URL withFileToUpload (const String& parameterName,
  12385. const File& fileToUpload,
  12386. const String& mimeType) const;
  12387. /** Returns a set of all the parameters encoded into the url.
  12388. E.g. for the url "www.fish.com?type=haddock&amount=some+fish", this array would
  12389. contain two pairs: "type" => "haddock" and "amount" => "some fish".
  12390. The values returned will have been cleaned up to remove any escape characters.
  12391. @see getNamedParameter, withParameter
  12392. */
  12393. const StringPairArray& getParameters() const;
  12394. /** Returns the set of files that should be uploaded as part of a POST operation.
  12395. This is the set of files that were added to the URL with the withFileToUpload()
  12396. method.
  12397. */
  12398. const StringPairArray& getFilesToUpload() const;
  12399. /** Returns the set of mime types associated with each of the upload files.
  12400. */
  12401. const StringPairArray& getMimeTypesOfUploadFiles() const;
  12402. /** Returns a copy of this URL, with a block of data to send as the POST data.
  12403. If you're setting the POST data, be careful not to have any parameters set
  12404. as well, otherwise it'll all get thrown in together, and might not have the
  12405. desired effect.
  12406. If the URL already contains some POST data, this will replace it, rather
  12407. than being appended to it.
  12408. This data will only be used if you specify a post operation when you call
  12409. createInputStream().
  12410. */
  12411. const URL withPOSTData (const String& postData) const;
  12412. /** Returns the data that was set using withPOSTData().
  12413. */
  12414. const String getPostData() const { return postData; }
  12415. /** Tries to launch the system's default browser to open the URL.
  12416. Returns true if this seems to have worked.
  12417. */
  12418. bool launchInDefaultBrowser() const;
  12419. /** Takes a guess as to whether a string might be a valid website address.
  12420. This isn't foolproof!
  12421. */
  12422. static bool isProbablyAWebsiteURL (const String& possibleURL);
  12423. /** Takes a guess as to whether a string might be a valid email address.
  12424. This isn't foolproof!
  12425. */
  12426. static bool isProbablyAnEmailAddress (const String& possibleEmailAddress);
  12427. /** This callback function can be used by the createInputStream() method.
  12428. It allows your app to receive progress updates during a lengthy POST operation. If you
  12429. want to continue the operation, this should return true, or false to abort.
  12430. */
  12431. typedef bool (OpenStreamProgressCallback) (void* context, int bytesSent, int totalBytes);
  12432. /** Attempts to open a stream that can read from this URL.
  12433. @param usePostCommand if true, it will try to do use a http 'POST' to pass
  12434. the paramters, otherwise it'll encode them into the
  12435. URL and do a 'GET'.
  12436. @param progressCallback if this is non-zero, it lets you supply a callback function
  12437. to keep track of the operation's progress. This can be useful
  12438. for lengthy POST operations, so that you can provide user feedback.
  12439. @param progressCallbackContext if a callback is specified, this value will be passed to
  12440. the function
  12441. @param extraHeaders if not empty, this string is appended onto the headers that
  12442. are used for the request. It must therefore be a valid set of HTML
  12443. header directives, separated by newlines.
  12444. @param connectionTimeOutMs if 0, this will use whatever default setting the OS chooses. If
  12445. a negative number, it will be infinite. Otherwise it specifies a
  12446. time in milliseconds.
  12447. @param responseHeaders if this is non-zero, all the (key, value) pairs received as headers
  12448. in the response will be stored in this array
  12449. @returns an input stream that the caller must delete, or a null pointer if there was an
  12450. error trying to open it.
  12451. */
  12452. InputStream* createInputStream (bool usePostCommand,
  12453. OpenStreamProgressCallback* progressCallback = 0,
  12454. void* progressCallbackContext = 0,
  12455. const String& extraHeaders = String::empty,
  12456. int connectionTimeOutMs = 0,
  12457. StringPairArray* responseHeaders = 0) const;
  12458. /** Tries to download the entire contents of this URL into a binary data block.
  12459. If it succeeds, this will return true and append the data it read onto the end
  12460. of the memory block.
  12461. @param destData the memory block to append the new data to
  12462. @param usePostCommand whether to use a POST command to get the data (uses
  12463. a GET command if this is false)
  12464. @see readEntireTextStream, readEntireXmlStream
  12465. */
  12466. bool readEntireBinaryStream (MemoryBlock& destData,
  12467. bool usePostCommand = false) const;
  12468. /** Tries to download the entire contents of this URL as a string.
  12469. If it fails, this will return an empty string, otherwise it will return the
  12470. contents of the downloaded file. If you need to distinguish between a read
  12471. operation that fails and one that returns an empty string, you'll need to use
  12472. a different method, such as readEntireBinaryStream().
  12473. @param usePostCommand whether to use a POST command to get the data (uses
  12474. a GET command if this is false)
  12475. @see readEntireBinaryStream, readEntireXmlStream
  12476. */
  12477. const String readEntireTextStream (bool usePostCommand = false) const;
  12478. /** Tries to download the entire contents of this URL and parse it as XML.
  12479. If it fails, or if the text that it reads can't be parsed as XML, this will
  12480. return 0.
  12481. When it returns a valid XmlElement object, the caller is responsibile for deleting
  12482. this object when no longer needed.
  12483. @param usePostCommand whether to use a POST command to get the data (uses
  12484. a GET command if this is false)
  12485. @see readEntireBinaryStream, readEntireTextStream
  12486. */
  12487. XmlElement* readEntireXmlStream (bool usePostCommand = false) const;
  12488. /** Adds escape sequences to a string to encode any characters that aren't
  12489. legal in a URL.
  12490. E.g. any spaces will be replaced with "%20".
  12491. This is the opposite of removeEscapeChars().
  12492. If isParameter is true, it means that the string is going to be used
  12493. as a parameter, so it also encodes '$' and ',' (which would otherwise
  12494. be legal in a URL.
  12495. @see removeEscapeChars
  12496. */
  12497. static const String addEscapeChars (const String& stringToAddEscapeCharsTo,
  12498. bool isParameter);
  12499. /** Replaces any escape character sequences in a string with their original
  12500. character codes.
  12501. E.g. any instances of "%20" will be replaced by a space.
  12502. This is the opposite of addEscapeChars().
  12503. @see addEscapeChars
  12504. */
  12505. static const String removeEscapeChars (const String& stringToRemoveEscapeCharsFrom);
  12506. juce_UseDebuggingNewOperator
  12507. private:
  12508. String url, postData;
  12509. StringPairArray parameters, filesToUpload, mimeTypes;
  12510. };
  12511. #endif // __JUCE_URL_JUCEHEADER__
  12512. /*** End of inlined file: juce_URL.h ***/
  12513. #endif
  12514. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12515. /*** Start of inlined file: juce_BufferedInputStream.h ***/
  12516. #ifndef __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12517. #define __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12518. /** Wraps another input stream, and reads from it using an intermediate buffer
  12519. If you're using an input stream such as a file input stream, and making lots of
  12520. small read accesses to it, it's probably sensible to wrap it in one of these,
  12521. so that the source stream gets accessed in larger chunk sizes, meaning less
  12522. work for the underlying stream.
  12523. */
  12524. class JUCE_API BufferedInputStream : public InputStream
  12525. {
  12526. public:
  12527. /** Creates a BufferedInputStream from an input source.
  12528. @param sourceStream the source stream to read from
  12529. @param bufferSize the size of reservoir to use to buffer the source
  12530. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12531. deleted by this object when it is itself deleted.
  12532. */
  12533. BufferedInputStream (InputStream* sourceStream,
  12534. int bufferSize,
  12535. bool deleteSourceWhenDestroyed);
  12536. /** Destructor.
  12537. This may also delete the source stream, if that option was chosen when the
  12538. buffered stream was created.
  12539. */
  12540. ~BufferedInputStream();
  12541. int64 getTotalLength();
  12542. int64 getPosition();
  12543. bool setPosition (int64 newPosition);
  12544. int read (void* destBuffer, int maxBytesToRead);
  12545. const String readString();
  12546. bool isExhausted();
  12547. juce_UseDebuggingNewOperator
  12548. private:
  12549. InputStream* const source;
  12550. ScopedPointer <InputStream> sourceToDelete;
  12551. int bufferSize;
  12552. int64 position, lastReadPos, bufferStart, bufferOverlap;
  12553. HeapBlock <char> buffer;
  12554. void ensureBuffered();
  12555. BufferedInputStream (const BufferedInputStream&);
  12556. BufferedInputStream& operator= (const BufferedInputStream&);
  12557. };
  12558. #endif // __JUCE_BUFFEREDINPUTSTREAM_JUCEHEADER__
  12559. /*** End of inlined file: juce_BufferedInputStream.h ***/
  12560. #endif
  12561. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12562. /*** Start of inlined file: juce_FileInputSource.h ***/
  12563. #ifndef __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12564. #define __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12565. /**
  12566. A type of InputSource that represents a normal file.
  12567. @see InputSource
  12568. */
  12569. class JUCE_API FileInputSource : public InputSource
  12570. {
  12571. public:
  12572. FileInputSource (const File& file);
  12573. ~FileInputSource();
  12574. InputStream* createInputStream();
  12575. InputStream* createInputStreamFor (const String& relatedItemPath);
  12576. int64 hashCode() const;
  12577. juce_UseDebuggingNewOperator
  12578. private:
  12579. const File file;
  12580. FileInputSource (const FileInputSource&);
  12581. FileInputSource& operator= (const FileInputSource&);
  12582. };
  12583. #endif // __JUCE_FILEINPUTSOURCE_JUCEHEADER__
  12584. /*** End of inlined file: juce_FileInputSource.h ***/
  12585. #endif
  12586. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12587. /*** Start of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12588. #ifndef __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12589. #define __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12590. class GZIPCompressorHelper;
  12591. /**
  12592. A stream which uses zlib to compress the data written into it.
  12593. @see GZIPDecompressorInputStream
  12594. */
  12595. class JUCE_API GZIPCompressorOutputStream : public OutputStream
  12596. {
  12597. public:
  12598. /** Creates a compression stream.
  12599. @param destStream the stream into which the compressed data should
  12600. be written
  12601. @param compressionLevel how much to compress the data, between 1 and 9, where
  12602. 1 is the fastest/lowest compression, and 9 is the
  12603. slowest/highest compression. Any value outside this range
  12604. indicates that a default compression level should be used.
  12605. @param deleteDestStreamWhenDestroyed whether or not to delete the destStream object when
  12606. this stream is destroyed
  12607. @param noWrap this is used internally by the ZipFile class
  12608. and should be ignored by user applications
  12609. */
  12610. GZIPCompressorOutputStream (OutputStream* destStream,
  12611. int compressionLevel = 0,
  12612. bool deleteDestStreamWhenDestroyed = false,
  12613. bool noWrap = false);
  12614. /** Destructor. */
  12615. ~GZIPCompressorOutputStream();
  12616. void flush();
  12617. int64 getPosition();
  12618. bool setPosition (int64 newPosition);
  12619. bool write (const void* destBuffer, int howMany);
  12620. juce_UseDebuggingNewOperator
  12621. private:
  12622. OutputStream* const destStream;
  12623. ScopedPointer <OutputStream> streamToDelete;
  12624. HeapBlock <uint8> buffer;
  12625. ScopedPointer <GZIPCompressorHelper> helper;
  12626. bool doNextBlock();
  12627. GZIPCompressorOutputStream (const GZIPCompressorOutputStream&);
  12628. GZIPCompressorOutputStream& operator= (const GZIPCompressorOutputStream&);
  12629. };
  12630. #endif // __JUCE_GZIPCOMPRESSOROUTPUTSTREAM_JUCEHEADER__
  12631. /*** End of inlined file: juce_GZIPCompressorOutputStream.h ***/
  12632. #endif
  12633. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12634. /*** Start of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12635. #ifndef __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12636. #define __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12637. class GZIPDecompressHelper;
  12638. /**
  12639. This stream will decompress a source-stream using zlib.
  12640. Tip: if you're reading lots of small items from one of these streams, you
  12641. can increase the performance enormously by passing it through a
  12642. BufferedInputStream, so that it has to read larger blocks less often.
  12643. @see GZIPCompressorOutputStream
  12644. */
  12645. class JUCE_API GZIPDecompressorInputStream : public InputStream
  12646. {
  12647. public:
  12648. /** Creates a decompressor stream.
  12649. @param sourceStream the stream to read from
  12650. @param deleteSourceWhenDestroyed whether or not to delete the source stream
  12651. when this object is destroyed
  12652. @param noWrap this is used internally by the ZipFile class
  12653. and should be ignored by user applications
  12654. @param uncompressedStreamLength if the creator knows the length that the
  12655. uncompressed stream will be, then it can supply this
  12656. value, which will be returned by getTotalLength()
  12657. */
  12658. GZIPDecompressorInputStream (InputStream* sourceStream,
  12659. bool deleteSourceWhenDestroyed,
  12660. bool noWrap = false,
  12661. int64 uncompressedStreamLength = -1);
  12662. /** Destructor. */
  12663. ~GZIPDecompressorInputStream();
  12664. int64 getPosition();
  12665. bool setPosition (int64 pos);
  12666. int64 getTotalLength();
  12667. bool isExhausted();
  12668. int read (void* destBuffer, int maxBytesToRead);
  12669. juce_UseDebuggingNewOperator
  12670. private:
  12671. InputStream* const sourceStream;
  12672. ScopedPointer <InputStream> streamToDelete;
  12673. const int64 uncompressedStreamLength;
  12674. const bool noWrap;
  12675. bool isEof;
  12676. int activeBufferSize;
  12677. int64 originalSourcePos, currentPos;
  12678. HeapBlock <uint8> buffer;
  12679. ScopedPointer <GZIPDecompressHelper> helper;
  12680. GZIPDecompressorInputStream (const GZIPDecompressorInputStream&);
  12681. GZIPDecompressorInputStream& operator= (const GZIPDecompressorInputStream&);
  12682. };
  12683. #endif // __JUCE_GZIPDECOMPRESSORINPUTSTREAM_JUCEHEADER__
  12684. /*** End of inlined file: juce_GZIPDecompressorInputStream.h ***/
  12685. #endif
  12686. #ifndef __JUCE_INPUTSOURCE_JUCEHEADER__
  12687. #endif
  12688. #ifndef __JUCE_INPUTSTREAM_JUCEHEADER__
  12689. #endif
  12690. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12691. /*** Start of inlined file: juce_MemoryInputStream.h ***/
  12692. #ifndef __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12693. #define __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12694. /**
  12695. Allows a block of data and to be accessed as a stream.
  12696. This can either be used to refer to a shared block of memory, or can make its
  12697. own internal copy of the data when the MemoryInputStream is created.
  12698. */
  12699. class JUCE_API MemoryInputStream : public InputStream
  12700. {
  12701. public:
  12702. /** Creates a MemoryInputStream.
  12703. @param sourceData the block of data to use as the stream's source
  12704. @param sourceDataSize the number of bytes in the source data block
  12705. @param keepInternalCopyOfData if false, the stream will just keep a pointer to
  12706. the source data, so this data shouldn't be changed
  12707. for the lifetime of the stream; if this parameter is
  12708. true, the stream will make its own copy of the
  12709. data and use that.
  12710. */
  12711. MemoryInputStream (const void* sourceData,
  12712. size_t sourceDataSize,
  12713. bool keepInternalCopyOfData);
  12714. /** Creates a MemoryInputStream.
  12715. @param data a block of data to use as the stream's source
  12716. @param keepInternalCopyOfData if false, the stream will just keep a reference to
  12717. the source data, so this data shouldn't be changed
  12718. for the lifetime of the stream; if this parameter is
  12719. true, the stream will make its own copy of the
  12720. data and use that.
  12721. */
  12722. MemoryInputStream (const MemoryBlock& data,
  12723. bool keepInternalCopyOfData);
  12724. /** Destructor. */
  12725. ~MemoryInputStream();
  12726. int64 getPosition();
  12727. bool setPosition (int64 pos);
  12728. int64 getTotalLength();
  12729. bool isExhausted();
  12730. int read (void* destBuffer, int maxBytesToRead);
  12731. juce_UseDebuggingNewOperator
  12732. private:
  12733. const char* data;
  12734. size_t dataSize, position;
  12735. MemoryBlock internalCopy;
  12736. MemoryInputStream (const MemoryInputStream&);
  12737. MemoryInputStream& operator= (const MemoryInputStream&);
  12738. };
  12739. #endif // __JUCE_MEMORYINPUTSTREAM_JUCEHEADER__
  12740. /*** End of inlined file: juce_MemoryInputStream.h ***/
  12741. #endif
  12742. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12743. /*** Start of inlined file: juce_MemoryOutputStream.h ***/
  12744. #ifndef __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12745. #define __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12746. /** Writes data to an internal memory buffer, which grows as required.
  12747. The data that was written into the stream can then be accessed later as
  12748. a contiguous block of memory.
  12749. */
  12750. class JUCE_API MemoryOutputStream : public OutputStream
  12751. {
  12752. public:
  12753. /** Creates an empty memory stream ready for writing into.
  12754. @param initialSize the intial amount of capacity to allocate for writing into
  12755. */
  12756. MemoryOutputStream (size_t initialSize = 256);
  12757. /** Creates a memory stream for writing into into a pre-existing MemoryBlock object.
  12758. Note that the destination block will always be larger than the amount of data
  12759. that has been written to the stream, because the MemoryOutputStream keeps some
  12760. spare capactity at its end. To trim the block's size down to fit the actual
  12761. data, call flush(), or delete the MemoryOutputStream.
  12762. @param memoryBlockToWriteTo the block into which new data will be written.
  12763. @param appendToExistingBlockContent if this is true, the contents of the block will be
  12764. kept, and new data will be appended to it. If false,
  12765. the block will be cleared before use
  12766. */
  12767. MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  12768. bool appendToExistingBlockContent);
  12769. /** Destructor.
  12770. This will free any data that was written to it.
  12771. */
  12772. ~MemoryOutputStream();
  12773. /** Returns a pointer to the data that has been written to the stream.
  12774. @see getDataSize
  12775. */
  12776. const void* getData() const throw();
  12777. /** Returns the number of bytes of data that have been written to the stream.
  12778. @see getData
  12779. */
  12780. size_t getDataSize() const throw() { return size; }
  12781. /** Resets the stream, clearing any data that has been written to it so far. */
  12782. void reset() throw();
  12783. /** Increases the internal storage capacity to be able to contain at least the specified
  12784. amount of data without needing to be resized.
  12785. */
  12786. void preallocate (size_t bytesToPreallocate);
  12787. /** Returns a String created from the (UTF8) data that has been written to the stream. */
  12788. const String toUTF8() const;
  12789. /** Attempts to detect the encoding of the data and convert it to a string.
  12790. @see String::createStringFromData
  12791. */
  12792. const String toString() const;
  12793. /** If the stream is writing to a user-supplied MemoryBlock, this will trim any excess
  12794. capacity off the block, so that its length matches the amount of actual data that
  12795. has been written so far.
  12796. */
  12797. void flush();
  12798. bool write (const void* buffer, int howMany);
  12799. int64 getPosition() { return position; }
  12800. bool setPosition (int64 newPosition);
  12801. int writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite);
  12802. juce_UseDebuggingNewOperator
  12803. private:
  12804. MemoryBlock& data;
  12805. MemoryBlock internalBlock;
  12806. size_t position, size;
  12807. MemoryOutputStream (const MemoryOutputStream&);
  12808. MemoryOutputStream& operator= (const MemoryOutputStream&);
  12809. };
  12810. /** Copies all the data that has been written to a MemoryOutputStream into another stream. */
  12811. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead);
  12812. #endif // __JUCE_MEMORYOUTPUTSTREAM_JUCEHEADER__
  12813. /*** End of inlined file: juce_MemoryOutputStream.h ***/
  12814. #endif
  12815. #ifndef __JUCE_OUTPUTSTREAM_JUCEHEADER__
  12816. #endif
  12817. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12818. /*** Start of inlined file: juce_SubregionStream.h ***/
  12819. #ifndef __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12820. #define __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12821. /** Wraps another input stream, and reads from a specific part of it.
  12822. This lets you take a subsection of a stream and present it as an entire
  12823. stream in its own right.
  12824. */
  12825. class JUCE_API SubregionStream : public InputStream
  12826. {
  12827. public:
  12828. /** Creates a SubregionStream from an input source.
  12829. @param sourceStream the source stream to read from
  12830. @param startPositionInSourceStream this is the position in the source stream that
  12831. corresponds to position 0 in this stream
  12832. @param lengthOfSourceStream this specifies the maximum number of bytes
  12833. from the source stream that will be passed through
  12834. by this stream. When the position of this stream
  12835. exceeds lengthOfSourceStream, it will cause an end-of-stream.
  12836. If the length passed in here is greater than the length
  12837. of the source stream (as returned by getTotalLength()),
  12838. then the smaller value will be used.
  12839. Passing a negative value for this parameter means it
  12840. will keep reading until the source's end-of-stream.
  12841. @param deleteSourceWhenDestroyed whether the sourceStream that is passed in should be
  12842. deleted by this object when it is itself deleted.
  12843. */
  12844. SubregionStream (InputStream* sourceStream,
  12845. int64 startPositionInSourceStream,
  12846. int64 lengthOfSourceStream,
  12847. bool deleteSourceWhenDestroyed);
  12848. /** Destructor.
  12849. This may also delete the source stream, if that option was chosen when the
  12850. buffered stream was created.
  12851. */
  12852. ~SubregionStream();
  12853. int64 getTotalLength();
  12854. int64 getPosition();
  12855. bool setPosition (int64 newPosition);
  12856. int read (void* destBuffer, int maxBytesToRead);
  12857. bool isExhausted();
  12858. juce_UseDebuggingNewOperator
  12859. private:
  12860. InputStream* const source;
  12861. ScopedPointer <InputStream> sourceToDelete;
  12862. const int64 startPositionInSourceStream, lengthOfSourceStream;
  12863. SubregionStream (const SubregionStream&);
  12864. SubregionStream& operator= (const SubregionStream&);
  12865. };
  12866. #endif // __JUCE_SUBREGIONSTREAM_JUCEHEADER__
  12867. /*** End of inlined file: juce_SubregionStream.h ***/
  12868. #endif
  12869. #ifndef __JUCE_CHARACTERFUNCTIONS_JUCEHEADER__
  12870. #endif
  12871. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12872. /*** Start of inlined file: juce_LocalisedStrings.h ***/
  12873. #ifndef __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12874. #define __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12875. /** Used in the same way as the T(text) macro, this will attempt to translate a
  12876. string into a localised version using the LocalisedStrings class.
  12877. @see LocalisedStrings
  12878. */
  12879. #define TRANS(stringLiteral) \
  12880. LocalisedStrings::translateWithCurrentMappings (stringLiteral)
  12881. /**
  12882. Used to convert strings to localised foreign-language versions.
  12883. This is basically a look-up table of strings and their translated equivalents.
  12884. It can be loaded from a text file, so that you can supply a set of localised
  12885. versions of strings that you use in your app.
  12886. To use it in your code, simply call the translate() method on each string that
  12887. might have foreign versions, and if none is found, the method will just return
  12888. the original string.
  12889. The translation file should start with some lines specifying a description of
  12890. the language it contains, and also a list of ISO country codes where it might
  12891. be appropriate to use the file. After that, each line of the file should contain
  12892. a pair of quoted strings with an '=' sign.
  12893. E.g. for a french translation, the file might be:
  12894. @code
  12895. language: French
  12896. countries: fr be mc ch lu
  12897. "hello" = "bonjour"
  12898. "goodbye" = "au revoir"
  12899. @endcode
  12900. If the strings need to contain a quote character, they can use '\"' instead, and
  12901. if the first non-whitespace character on a line isn't a quote, then it's ignored,
  12902. (you can use this to add comments).
  12903. Note that this is a singleton class, so don't create or destroy the object directly.
  12904. There's also a TRANS(text) macro defined to make it easy to use the this.
  12905. E.g. @code
  12906. printSomething (TRANS("hello"));
  12907. @endcode
  12908. This macro is used in the Juce classes themselves, so your application has a chance to
  12909. intercept and translate any internal Juce text strings that might be shown. (You can easily
  12910. get a list of all the messages by searching for the TRANS() macro in the Juce source
  12911. code).
  12912. */
  12913. class JUCE_API LocalisedStrings
  12914. {
  12915. public:
  12916. /** Creates a set of translations from the text of a translation file.
  12917. When you create one of these, you can call setCurrentMappings() to make it
  12918. the set of mappings that the system's using.
  12919. */
  12920. LocalisedStrings (const String& fileContents);
  12921. /** Creates a set of translations from a file.
  12922. When you create one of these, you can call setCurrentMappings() to make it
  12923. the set of mappings that the system's using.
  12924. */
  12925. LocalisedStrings (const File& fileToLoad);
  12926. /** Destructor. */
  12927. ~LocalisedStrings();
  12928. /** Selects the current set of mappings to be used by the system.
  12929. The object you pass in will be automatically deleted when no longer needed, so
  12930. don't keep a pointer to it. You can also pass in zero to remove the current
  12931. mappings.
  12932. See also the TRANS() macro, which uses the current set to do its translation.
  12933. @see translateWithCurrentMappings
  12934. */
  12935. static void setCurrentMappings (LocalisedStrings* newTranslations);
  12936. /** Returns the currently selected set of mappings.
  12937. This is the object that was last passed to setCurrentMappings(). It may
  12938. be 0 if none has been created.
  12939. */
  12940. static LocalisedStrings* getCurrentMappings();
  12941. /** Tries to translate a string using the currently selected set of mappings.
  12942. If no mapping has been set, or if the mapping doesn't contain a translation
  12943. for the string, this will just return the original string.
  12944. See also the TRANS() macro, which uses this method to do its translation.
  12945. @see setCurrentMappings, getCurrentMappings
  12946. */
  12947. static const String translateWithCurrentMappings (const String& text);
  12948. /** Tries to translate a string using the currently selected set of mappings.
  12949. If no mapping has been set, or if the mapping doesn't contain a translation
  12950. for the string, this will just return the original string.
  12951. See also the TRANS() macro, which uses this method to do its translation.
  12952. @see setCurrentMappings, getCurrentMappings
  12953. */
  12954. static const String translateWithCurrentMappings (const char* text);
  12955. /** Attempts to look up a string and return its localised version.
  12956. If the string isn't found in the list, the original string will be returned.
  12957. */
  12958. const String translate (const String& text) const;
  12959. /** Returns the name of the language specified in the translation file.
  12960. This is specified in the file using a line starting with "language:", e.g.
  12961. @code
  12962. language: german
  12963. @endcode
  12964. */
  12965. const String getLanguageName() const { return languageName; }
  12966. /** Returns the list of suitable country codes listed in the translation file.
  12967. These is specified in the file using a line starting with "countries:", e.g.
  12968. @code
  12969. countries: fr be mc ch lu
  12970. @endcode
  12971. The country codes are supposed to be 2-character ISO complient codes.
  12972. */
  12973. const StringArray getCountryCodes() const { return countryCodes; }
  12974. /** Indicates whether to use a case-insensitive search when looking up a string.
  12975. This defaults to true.
  12976. */
  12977. void setIgnoresCase (const bool shouldIgnoreCase);
  12978. juce_UseDebuggingNewOperator
  12979. private:
  12980. String languageName;
  12981. StringArray countryCodes;
  12982. StringPairArray translations;
  12983. void loadFromText (const String& fileContents);
  12984. };
  12985. #endif // __JUCE_LOCALISEDSTRINGS_JUCEHEADER__
  12986. /*** End of inlined file: juce_LocalisedStrings.h ***/
  12987. #endif
  12988. #ifndef __JUCE_STRING_JUCEHEADER__
  12989. #endif
  12990. #ifndef __JUCE_STRINGARRAY_JUCEHEADER__
  12991. #endif
  12992. #ifndef __JUCE_STRINGPAIRARRAY_JUCEHEADER__
  12993. #endif
  12994. #ifndef __JUCE_STRINGPOOL_JUCEHEADER__
  12995. #endif
  12996. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12997. /*** Start of inlined file: juce_XmlDocument.h ***/
  12998. #ifndef __JUCE_XMLDOCUMENT_JUCEHEADER__
  12999. #define __JUCE_XMLDOCUMENT_JUCEHEADER__
  13000. /**
  13001. Parses a text-based XML document and creates an XmlElement object from it.
  13002. The parser will parse DTDs to load external entities but won't
  13003. check the document for validity against the DTD.
  13004. e.g.
  13005. @code
  13006. XmlDocument myDocument (File ("myfile.xml"));
  13007. XmlElement* mainElement = myDocument.getDocumentElement();
  13008. if (mainElement == 0)
  13009. {
  13010. String error = myDocument.getLastParseError();
  13011. }
  13012. else
  13013. {
  13014. ..use the element
  13015. }
  13016. @endcode
  13017. @see XmlElement
  13018. */
  13019. class JUCE_API XmlDocument
  13020. {
  13021. public:
  13022. /** Creates an XmlDocument from the xml text.
  13023. The text doesn't actually get parsed until the getDocumentElement() method is
  13024. called.
  13025. */
  13026. XmlDocument (const String& documentText);
  13027. /** Creates an XmlDocument from a file.
  13028. The text doesn't actually get parsed until the getDocumentElement() method is
  13029. called.
  13030. */
  13031. XmlDocument (const File& file);
  13032. /** Destructor. */
  13033. ~XmlDocument();
  13034. /** Creates an XmlElement object to represent the main document node.
  13035. This method will do the actual parsing of the text, and if there's a
  13036. parse error, it may returns 0 (and you can find out the error using
  13037. the getLastParseError() method).
  13038. @param onlyReadOuterDocumentElement if true, the parser will only read the
  13039. first section of the file, and will only
  13040. return the outer document element - this
  13041. allows quick checking of large files to
  13042. see if they contain the correct type of
  13043. tag, without having to parse the entire file
  13044. @returns a new XmlElement which the caller will need to delete, or null if
  13045. there was an error.
  13046. @see getLastParseError
  13047. */
  13048. XmlElement* getDocumentElement (const bool onlyReadOuterDocumentElement = false);
  13049. /** Returns the parsing error that occurred the last time getDocumentElement was called.
  13050. @returns the error, or an empty string if there was no error.
  13051. */
  13052. const String& getLastParseError() const throw();
  13053. /** Sets an input source object to use for parsing documents that reference external entities.
  13054. If the document has been created from a file, this probably won't be needed, but
  13055. if you're parsing some text and there might be a DTD that references external
  13056. files, you may need to create a custom input source that can retrieve the
  13057. other files it needs.
  13058. The object that is passed-in will be deleted automatically when no longer needed.
  13059. @see InputSource
  13060. */
  13061. void setInputSource (InputSource* const newSource) throw();
  13062. /** Sets a flag to change the treatment of empty text elements.
  13063. If this is true (the default state), then any text elements that contain only
  13064. whitespace characters will be ingored during parsing. If you need to catch
  13065. whitespace-only text, then you should set this to false before calling the
  13066. getDocumentElement() method.
  13067. */
  13068. void setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw();
  13069. juce_UseDebuggingNewOperator
  13070. private:
  13071. String originalText;
  13072. const juce_wchar* input;
  13073. bool outOfData, errorOccurred;
  13074. bool identifierLookupTable [128];
  13075. String lastError, dtdText;
  13076. StringArray tokenisedDTD;
  13077. bool needToLoadDTD, ignoreEmptyTextElements;
  13078. ScopedPointer <InputSource> inputSource;
  13079. void setLastError (const String& desc, const bool carryOn);
  13080. void skipHeader();
  13081. void skipNextWhiteSpace();
  13082. juce_wchar readNextChar() throw();
  13083. XmlElement* readNextElement (const bool alsoParseSubElements);
  13084. void readChildElements (XmlElement* parent);
  13085. int findNextTokenLength() throw();
  13086. void readQuotedString (String& result);
  13087. void readEntity (String& result);
  13088. static bool isXmlIdentifierCharSlow (juce_wchar c) throw();
  13089. bool isXmlIdentifierChar (juce_wchar c) const throw();
  13090. const String getFileContents (const String& filename) const;
  13091. const String expandEntity (const String& entity);
  13092. const String expandExternalEntity (const String& entity);
  13093. const String getParameterEntity (const String& entity);
  13094. XmlDocument (const XmlDocument&);
  13095. XmlDocument& operator= (const XmlDocument&);
  13096. };
  13097. #endif // __JUCE_XMLDOCUMENT_JUCEHEADER__
  13098. /*** End of inlined file: juce_XmlDocument.h ***/
  13099. #endif
  13100. #ifndef __JUCE_XMLELEMENT_JUCEHEADER__
  13101. #endif
  13102. #ifndef __JUCE_CRITICALSECTION_JUCEHEADER__
  13103. #endif
  13104. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13105. /*** Start of inlined file: juce_InterProcessLock.h ***/
  13106. #ifndef __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13107. #define __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13108. /**
  13109. Acts as a critical section which processes can use to block each other.
  13110. @see CriticalSection
  13111. */
  13112. class JUCE_API InterProcessLock
  13113. {
  13114. public:
  13115. /** Creates a lock object.
  13116. @param name a name that processes will use to identify this lock object
  13117. */
  13118. explicit InterProcessLock (const String& name);
  13119. /** Destructor.
  13120. This will also release the lock if it's currently held by this process.
  13121. */
  13122. ~InterProcessLock();
  13123. /** Attempts to lock the critical section.
  13124. @param timeOutMillisecs how many milliseconds to wait if the lock
  13125. is already held by another process - a value of
  13126. 0 will return immediately, negative values will wait
  13127. forever
  13128. @returns true if the lock could be gained within the timeout period, or
  13129. false if the timeout expired.
  13130. */
  13131. bool enter (int timeOutMillisecs = -1);
  13132. /** Releases the lock if it's currently held by this process.
  13133. */
  13134. void exit();
  13135. /**
  13136. Automatically locks and unlocks an InterProcessLock object.
  13137. This works like a ScopedLock, but using an InterprocessLock rather than
  13138. a CriticalSection.
  13139. @see ScopedLock
  13140. */
  13141. class ScopedLockType
  13142. {
  13143. public:
  13144. /** Creates a scoped lock.
  13145. As soon as it is created, this will lock the InterProcessLock, and
  13146. when the ScopedLockType object is deleted, the InterProcessLock will
  13147. be unlocked.
  13148. Note that since an InterprocessLock can fail due to errors, you should check
  13149. isLocked() to make sure that the lock was successful before using it.
  13150. Make sure this object is created and deleted by the same thread,
  13151. otherwise there are no guarantees what will happen! Best just to use it
  13152. as a local stack object, rather than creating one with the new() operator.
  13153. */
  13154. explicit ScopedLockType (InterProcessLock& lock) : lock_ (lock) { lockWasSuccessful = lock.enter(); }
  13155. /** Destructor.
  13156. The InterProcessLock will be unlocked when the destructor is called.
  13157. Make sure this object is created and deleted by the same thread,
  13158. otherwise there are no guarantees what will happen!
  13159. */
  13160. inline ~ScopedLockType() { lock_.exit(); }
  13161. /** Returns true if the InterProcessLock was successfully locked. */
  13162. bool isLocked() const throw() { return lockWasSuccessful; }
  13163. private:
  13164. InterProcessLock& lock_;
  13165. bool lockWasSuccessful;
  13166. ScopedLockType (const ScopedLockType&);
  13167. ScopedLockType& operator= (const ScopedLockType&);
  13168. };
  13169. juce_UseDebuggingNewOperator
  13170. private:
  13171. class Pimpl;
  13172. friend class ScopedPointer <Pimpl>;
  13173. ScopedPointer <Pimpl> pimpl;
  13174. CriticalSection lock;
  13175. String name;
  13176. InterProcessLock (const InterProcessLock&);
  13177. InterProcessLock& operator= (const InterProcessLock&);
  13178. };
  13179. #endif // __JUCE_INTERPROCESSLOCK_JUCEHEADER__
  13180. /*** End of inlined file: juce_InterProcessLock.h ***/
  13181. #endif
  13182. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13183. /*** Start of inlined file: juce_Process.h ***/
  13184. #ifndef __JUCE_PROCESS_JUCEHEADER__
  13185. #define __JUCE_PROCESS_JUCEHEADER__
  13186. /** Represents the current executable's process.
  13187. This contains methods for controlling the current application at the
  13188. process-level.
  13189. @see Thread, JUCEApplication
  13190. */
  13191. class JUCE_API Process
  13192. {
  13193. public:
  13194. enum ProcessPriority
  13195. {
  13196. LowPriority = 0,
  13197. NormalPriority = 1,
  13198. HighPriority = 2,
  13199. RealtimePriority = 3
  13200. };
  13201. /** Changes the current process's priority.
  13202. @param priority the process priority, where
  13203. 0=low, 1=normal, 2=high, 3=realtime
  13204. */
  13205. static void setPriority (const ProcessPriority priority);
  13206. /** Kills the current process immediately.
  13207. This is an emergency process terminator that kills the application
  13208. immediately - it's intended only for use only when something goes
  13209. horribly wrong.
  13210. @see JUCEApplication::quit
  13211. */
  13212. static void terminate();
  13213. /** Returns true if this application process is the one that the user is
  13214. currently using.
  13215. */
  13216. static bool isForegroundProcess();
  13217. /** Raises the current process's privilege level.
  13218. Does nothing if this isn't supported by the current OS, or if process
  13219. privilege level is fixed.
  13220. */
  13221. static void raisePrivilege();
  13222. /** Lowers the current process's privilege level.
  13223. Does nothing if this isn't supported by the current OS, or if process
  13224. privilege level is fixed.
  13225. */
  13226. static void lowerPrivilege();
  13227. /** Returns true if this process is being hosted by a debugger.
  13228. */
  13229. static bool JUCE_CALLTYPE isRunningUnderDebugger();
  13230. private:
  13231. Process();
  13232. Process (const Process&);
  13233. Process& operator= (const Process&);
  13234. };
  13235. #endif // __JUCE_PROCESS_JUCEHEADER__
  13236. /*** End of inlined file: juce_Process.h ***/
  13237. #endif
  13238. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13239. /*** Start of inlined file: juce_ReadWriteLock.h ***/
  13240. #ifndef __JUCE_READWRITELOCK_JUCEHEADER__
  13241. #define __JUCE_READWRITELOCK_JUCEHEADER__
  13242. /*** Start of inlined file: juce_WaitableEvent.h ***/
  13243. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13244. #define __JUCE_WAITABLEEVENT_JUCEHEADER__
  13245. /**
  13246. Allows threads to wait for events triggered by other threads.
  13247. A thread can call wait() on a WaitableObject, and this will suspend the
  13248. calling thread until another thread wakes it up by calling the signal()
  13249. method.
  13250. */
  13251. class JUCE_API WaitableEvent
  13252. {
  13253. public:
  13254. /** Creates a WaitableEvent object.
  13255. @param manualReset If this is false, the event will be reset automatically when the wait()
  13256. method is called. If manualReset is true, then once the event is signalled,
  13257. the only way to reset it will be by calling the reset() method.
  13258. */
  13259. WaitableEvent (bool manualReset = false) throw();
  13260. /** Destructor.
  13261. If other threads are waiting on this object when it gets deleted, this
  13262. can cause nasty errors, so be careful!
  13263. */
  13264. ~WaitableEvent() throw();
  13265. /** Suspends the calling thread until the event has been signalled.
  13266. This will wait until the object's signal() method is called by another thread,
  13267. or until the timeout expires.
  13268. After the event has been signalled, this method will return true and if manualReset
  13269. was set to false in the WaitableEvent's constructor, then the event will be reset.
  13270. @param timeOutMilliseconds the maximum time to wait, in milliseconds. A negative
  13271. value will cause it to wait forever.
  13272. @returns true if the object has been signalled, false if the timeout expires first.
  13273. @see signal, reset
  13274. */
  13275. bool wait (int timeOutMilliseconds = -1) const throw();
  13276. /** Wakes up any threads that are currently waiting on this object.
  13277. If signal() is called when nothing is waiting, the next thread to call wait()
  13278. will return immediately and reset the signal.
  13279. @see wait, reset
  13280. */
  13281. void signal() const throw();
  13282. /** Resets the event to an unsignalled state.
  13283. If it's not already signalled, this does nothing.
  13284. */
  13285. void reset() const throw();
  13286. juce_UseDebuggingNewOperator
  13287. private:
  13288. void* internal;
  13289. WaitableEvent (const WaitableEvent&);
  13290. WaitableEvent& operator= (const WaitableEvent&);
  13291. };
  13292. #endif // __JUCE_WAITABLEEVENT_JUCEHEADER__
  13293. /*** End of inlined file: juce_WaitableEvent.h ***/
  13294. /*** Start of inlined file: juce_Thread.h ***/
  13295. #ifndef __JUCE_THREAD_JUCEHEADER__
  13296. #define __JUCE_THREAD_JUCEHEADER__
  13297. /**
  13298. Encapsulates a thread.
  13299. Subclasses derive from Thread and implement the run() method, in which they
  13300. do their business. The thread can then be started with the startThread() method
  13301. and controlled with various other methods.
  13302. This class also contains some thread-related static methods, such
  13303. as sleep(), yield(), getCurrentThreadId() etc.
  13304. @see CriticalSection, WaitableEvent, Process, ThreadWithProgressWindow,
  13305. MessageManagerLock
  13306. */
  13307. class JUCE_API Thread
  13308. {
  13309. public:
  13310. /**
  13311. Creates a thread.
  13312. When first created, the thread is not running. Use the startThread()
  13313. method to start it.
  13314. */
  13315. explicit Thread (const String& threadName);
  13316. /** Destructor.
  13317. Deleting a Thread object that is running will only give the thread a
  13318. brief opportunity to stop itself cleanly, so it's recommended that you
  13319. should always call stopThread() with a decent timeout before deleting,
  13320. to avoid the thread being forcibly killed (which is a Bad Thing).
  13321. */
  13322. virtual ~Thread();
  13323. /** Must be implemented to perform the thread's actual code.
  13324. Remember that the thread must regularly check the threadShouldExit()
  13325. method whilst running, and if this returns true it should return from
  13326. the run() method as soon as possible to avoid being forcibly killed.
  13327. @see threadShouldExit, startThread
  13328. */
  13329. virtual void run() = 0;
  13330. // Thread control functions..
  13331. /** Starts the thread running.
  13332. This will start the thread's run() method.
  13333. (if it's already started, startThread() won't do anything).
  13334. @see stopThread
  13335. */
  13336. void startThread();
  13337. /** Starts the thread with a given priority.
  13338. Launches the thread with a given priority, where 0 = lowest, 10 = highest.
  13339. If the thread is already running, its priority will be changed.
  13340. @see startThread, setPriority
  13341. */
  13342. void startThread (int priority);
  13343. /** Attempts to stop the thread running.
  13344. This method will cause the threadShouldExit() method to return true
  13345. and call notify() in case the thread is currently waiting.
  13346. Hopefully the thread will then respond to this by exiting cleanly, and
  13347. the stopThread method will wait for a given time-period for this to
  13348. happen.
  13349. If the thread is stuck and fails to respond after the time-out, it gets
  13350. forcibly killed, which is a very bad thing to happen, as it could still
  13351. be holding locks, etc. which are needed by other parts of your program.
  13352. @param timeOutMilliseconds The number of milliseconds to wait for the
  13353. thread to finish before killing it by force. A negative
  13354. value in here will wait forever.
  13355. @see signalThreadShouldExit, threadShouldExit, waitForThreadToExit, isThreadRunning
  13356. */
  13357. void stopThread (int timeOutMilliseconds);
  13358. /** Returns true if the thread is currently active */
  13359. bool isThreadRunning() const;
  13360. /** Sets a flag to tell the thread it should stop.
  13361. Calling this means that the threadShouldExit() method will then return true.
  13362. The thread should be regularly checking this to see whether it should exit.
  13363. If your thread makes use of wait(), you might want to call notify() after calling
  13364. this method, to interrupt any waits that might be in progress, and allow it
  13365. to reach a point where it can exit.
  13366. @see threadShouldExit
  13367. @see waitForThreadToExit
  13368. */
  13369. void signalThreadShouldExit();
  13370. /** Checks whether the thread has been told to stop running.
  13371. Threads need to check this regularly, and if it returns true, they should
  13372. return from their run() method at the first possible opportunity.
  13373. @see signalThreadShouldExit
  13374. */
  13375. inline bool threadShouldExit() const { return threadShouldExit_; }
  13376. /** Waits for the thread to stop.
  13377. This will waits until isThreadRunning() is false or until a timeout expires.
  13378. @param timeOutMilliseconds the time to wait, in milliseconds. If this value
  13379. is less than zero, it will wait forever.
  13380. @returns true if the thread exits, or false if the timeout expires first.
  13381. */
  13382. bool waitForThreadToExit (int timeOutMilliseconds) const;
  13383. /** Changes the thread's priority.
  13384. May return false if for some reason the priority can't be changed.
  13385. @param priority the new priority, in the range 0 (lowest) to 10 (highest). A priority
  13386. of 5 is normal.
  13387. */
  13388. bool setPriority (int priority);
  13389. /** Changes the priority of the caller thread.
  13390. Similar to setPriority(), but this static method acts on the caller thread.
  13391. May return false if for some reason the priority can't be changed.
  13392. @see setPriority
  13393. */
  13394. static bool setCurrentThreadPriority (int priority);
  13395. /** Sets the affinity mask for the thread.
  13396. This will only have an effect next time the thread is started - i.e. if the
  13397. thread is already running when called, it'll have no effect.
  13398. @see setCurrentThreadAffinityMask
  13399. */
  13400. void setAffinityMask (uint32 affinityMask);
  13401. /** Changes the affinity mask for the caller thread.
  13402. This will change the affinity mask for the thread that calls this static method.
  13403. @see setAffinityMask
  13404. */
  13405. static void setCurrentThreadAffinityMask (uint32 affinityMask);
  13406. // this can be called from any thread that needs to pause..
  13407. static void JUCE_CALLTYPE sleep (int milliseconds);
  13408. /** Yields the calling thread's current time-slot. */
  13409. static void JUCE_CALLTYPE yield();
  13410. /** Makes the thread wait for a notification.
  13411. This puts the thread to sleep until either the timeout period expires, or
  13412. another thread calls the notify() method to wake it up.
  13413. A negative time-out value means that the method will wait indefinitely.
  13414. @returns true if the event has been signalled, false if the timeout expires.
  13415. */
  13416. bool wait (int timeOutMilliseconds) const;
  13417. /** Wakes up the thread.
  13418. If the thread has called the wait() method, this will wake it up.
  13419. @see wait
  13420. */
  13421. void notify() const;
  13422. /** A value type used for thread IDs.
  13423. @see getCurrentThreadId(), getThreadId()
  13424. */
  13425. typedef void* ThreadID;
  13426. /** Returns an id that identifies the caller thread.
  13427. To find the ID of a particular thread object, use getThreadId().
  13428. @returns a unique identifier that identifies the calling thread.
  13429. @see getThreadId
  13430. */
  13431. static ThreadID getCurrentThreadId();
  13432. /** Finds the thread object that is currently running.
  13433. Note that the main UI thread (or other non-Juce threads) don't have a Thread
  13434. object associated with them, so this will return 0.
  13435. */
  13436. static Thread* getCurrentThread();
  13437. /** Returns the ID of this thread.
  13438. That means the ID of this thread object - not of the thread that's calling the method.
  13439. This can change when the thread is started and stopped, and will be invalid if the
  13440. thread's not actually running.
  13441. @see getCurrentThreadId
  13442. */
  13443. ThreadID getThreadId() const throw() { return threadId_; }
  13444. /** Returns the name of the thread.
  13445. This is the name that gets set in the constructor.
  13446. */
  13447. const String getThreadName() const { return threadName_; }
  13448. /** Returns the number of currently-running threads.
  13449. @returns the number of Thread objects known to be currently running.
  13450. @see stopAllThreads
  13451. */
  13452. static int getNumRunningThreads();
  13453. /** Tries to stop all currently-running threads.
  13454. This will attempt to stop all the threads known to be running at the moment.
  13455. */
  13456. static void stopAllThreads (int timeoutInMillisecs);
  13457. juce_UseDebuggingNewOperator
  13458. private:
  13459. const String threadName_;
  13460. void* volatile threadHandle_;
  13461. CriticalSection startStopLock;
  13462. WaitableEvent startSuspensionEvent_, defaultEvent_;
  13463. int threadPriority_;
  13464. ThreadID threadId_;
  13465. uint32 affinityMask_;
  13466. bool volatile threadShouldExit_;
  13467. friend void JUCE_API juce_threadEntryPoint (void*);
  13468. static void threadEntryPoint (Thread* thread);
  13469. static Array<Thread*> runningThreads;
  13470. static CriticalSection runningThreadsLock;
  13471. Thread (const Thread&);
  13472. Thread& operator= (const Thread&);
  13473. };
  13474. #endif // __JUCE_THREAD_JUCEHEADER__
  13475. /*** End of inlined file: juce_Thread.h ***/
  13476. /**
  13477. A critical section that allows multiple simultaneous readers.
  13478. Features of this type of lock are:
  13479. - Multiple readers can hold the lock at the same time, but only one writer
  13480. can hold it at once.
  13481. - Writers trying to gain the lock will be blocked until all readers and writers
  13482. have released it
  13483. - Readers trying to gain the lock while a writer is waiting to acquire it will be
  13484. blocked until the writer has obtained and released it
  13485. - If a thread already has a read lock and tries to obtain a write lock, it will succeed if
  13486. there are no other readers
  13487. - If a thread already has the write lock and tries to obtain a read lock, this will succeed.
  13488. - Recursive locking is supported.
  13489. @see ScopedReadLock, ScopedWriteLock, CriticalSection
  13490. */
  13491. class JUCE_API ReadWriteLock
  13492. {
  13493. public:
  13494. /**
  13495. Creates a ReadWriteLock object.
  13496. */
  13497. ReadWriteLock() throw();
  13498. /** Destructor.
  13499. If the object is deleted whilst locked, any subsequent behaviour
  13500. is unpredictable.
  13501. */
  13502. ~ReadWriteLock() throw();
  13503. /** Locks this object for reading.
  13504. Multiple threads can simulaneously lock the object for reading, but if another
  13505. thread has it locked for writing, then this will block until it releases the
  13506. lock.
  13507. @see exitRead, ScopedReadLock
  13508. */
  13509. void enterRead() const throw();
  13510. /** Releases the read-lock.
  13511. If the caller thread hasn't got the lock, this can have unpredictable results.
  13512. If the enterRead() method has been called multiple times by the thread, each
  13513. call must be matched by a call to exitRead() before other threads will be allowed
  13514. to take over the lock.
  13515. @see enterRead, ScopedReadLock
  13516. */
  13517. void exitRead() const throw();
  13518. /** Locks this object for writing.
  13519. This will block until any other threads that have it locked for reading or
  13520. writing have released their lock.
  13521. @see exitWrite, ScopedWriteLock
  13522. */
  13523. void enterWrite() const throw();
  13524. /** Tries to lock this object for writing.
  13525. This is like enterWrite(), but doesn't block - it returns true if it manages
  13526. to obtain the lock.
  13527. @see enterWrite
  13528. */
  13529. bool tryEnterWrite() const throw();
  13530. /** Releases the write-lock.
  13531. If the caller thread hasn't got the lock, this can have unpredictable results.
  13532. If the enterWrite() method has been called multiple times by the thread, each
  13533. call must be matched by a call to exit() before other threads will be allowed
  13534. to take over the lock.
  13535. @see enterWrite, ScopedWriteLock
  13536. */
  13537. void exitWrite() const throw();
  13538. juce_UseDebuggingNewOperator
  13539. private:
  13540. CriticalSection accessLock;
  13541. WaitableEvent waitEvent;
  13542. mutable int numWaitingWriters, numWriters;
  13543. mutable Thread::ThreadID writerThreadId;
  13544. mutable Array <Thread::ThreadID> readerThreads;
  13545. ReadWriteLock (const ReadWriteLock&);
  13546. ReadWriteLock& operator= (const ReadWriteLock&);
  13547. };
  13548. #endif // __JUCE_READWRITELOCK_JUCEHEADER__
  13549. /*** End of inlined file: juce_ReadWriteLock.h ***/
  13550. #endif
  13551. #ifndef __JUCE_SCOPEDLOCK_JUCEHEADER__
  13552. #endif
  13553. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13554. /*** Start of inlined file: juce_ScopedReadLock.h ***/
  13555. #ifndef __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13556. #define __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13557. /**
  13558. Automatically locks and unlocks a ReadWriteLock object.
  13559. Use one of these as a local variable to control access to a ReadWriteLock.
  13560. e.g. @code
  13561. ReadWriteLock myLock;
  13562. for (;;)
  13563. {
  13564. const ScopedReadLock myScopedLock (myLock);
  13565. // myLock is now locked
  13566. ...do some stuff...
  13567. // myLock gets unlocked here.
  13568. }
  13569. @endcode
  13570. @see ReadWriteLock, ScopedWriteLock
  13571. */
  13572. class JUCE_API ScopedReadLock
  13573. {
  13574. public:
  13575. /** Creates a ScopedReadLock.
  13576. As soon as it is created, this will call ReadWriteLock::enterRead(), and
  13577. when the ScopedReadLock object is deleted, the ReadWriteLock will
  13578. be unlocked.
  13579. Make sure this object is created and deleted by the same thread,
  13580. otherwise there are no guarantees what will happen! Best just to use it
  13581. as a local stack object, rather than creating one with the new() operator.
  13582. */
  13583. inline explicit ScopedReadLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterRead(); }
  13584. /** Destructor.
  13585. The ReadWriteLock's exitRead() method will be called when the destructor is called.
  13586. Make sure this object is created and deleted by the same thread,
  13587. otherwise there are no guarantees what will happen!
  13588. */
  13589. inline ~ScopedReadLock() throw() { lock_.exitRead(); }
  13590. private:
  13591. const ReadWriteLock& lock_;
  13592. ScopedReadLock (const ScopedReadLock&);
  13593. ScopedReadLock& operator= (const ScopedReadLock&);
  13594. };
  13595. #endif // __JUCE_SCOPEDREADLOCK_JUCEHEADER__
  13596. /*** End of inlined file: juce_ScopedReadLock.h ***/
  13597. #endif
  13598. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13599. /*** Start of inlined file: juce_ScopedTryLock.h ***/
  13600. #ifndef __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13601. #define __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13602. /**
  13603. Automatically tries to lock and unlock a CriticalSection object.
  13604. Use one of these as a local variable to control access to a CriticalSection.
  13605. e.g. @code
  13606. CriticalSection myCriticalSection;
  13607. for (;;)
  13608. {
  13609. const ScopedTryLock myScopedTryLock (myCriticalSection);
  13610. // Unlike using a ScopedLock, this may fail to actually get the lock, so you
  13611. // should test this with the isLocked() method before doing your thread-unsafe
  13612. // action..
  13613. if (myScopedTryLock.isLocked())
  13614. {
  13615. ...do some stuff...
  13616. }
  13617. else
  13618. {
  13619. ..our attempt at locking failed because another thread had already locked it..
  13620. }
  13621. // myCriticalSection gets unlocked here (if it was locked)
  13622. }
  13623. @endcode
  13624. @see CriticalSection::tryEnter, ScopedLock, ScopedUnlock, ScopedReadLock
  13625. */
  13626. class JUCE_API ScopedTryLock
  13627. {
  13628. public:
  13629. /** Creates a ScopedTryLock.
  13630. As soon as it is created, this will try to lock the CriticalSection, and
  13631. when the ScopedTryLock object is deleted, the CriticalSection will
  13632. be unlocked if the lock was successful.
  13633. Make sure this object is created and deleted by the same thread,
  13634. otherwise there are no guarantees what will happen! Best just to use it
  13635. as a local stack object, rather than creating one with the new() operator.
  13636. */
  13637. inline explicit ScopedTryLock (const CriticalSection& lock) throw() : lock_ (lock), lockWasSuccessful (lock.tryEnter()) {}
  13638. /** Destructor.
  13639. The CriticalSection will be unlocked (if locked) when the destructor is called.
  13640. Make sure this object is created and deleted by the same thread,
  13641. otherwise there are no guarantees what will happen!
  13642. */
  13643. inline ~ScopedTryLock() throw() { if (lockWasSuccessful) lock_.exit(); }
  13644. /** Returns true if the CriticalSection was successfully locked. */
  13645. bool isLocked() const throw() { return lockWasSuccessful; }
  13646. private:
  13647. const CriticalSection& lock_;
  13648. const bool lockWasSuccessful;
  13649. ScopedTryLock (const ScopedTryLock&);
  13650. ScopedTryLock& operator= (const ScopedTryLock&);
  13651. };
  13652. #endif // __JUCE_SCOPEDTRYLOCK_JUCEHEADER__
  13653. /*** End of inlined file: juce_ScopedTryLock.h ***/
  13654. #endif
  13655. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13656. /*** Start of inlined file: juce_ScopedWriteLock.h ***/
  13657. #ifndef __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13658. #define __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13659. /**
  13660. Automatically locks and unlocks a ReadWriteLock object.
  13661. Use one of these as a local variable to control access to a ReadWriteLock.
  13662. e.g. @code
  13663. ReadWriteLock myLock;
  13664. for (;;)
  13665. {
  13666. const ScopedWriteLock myScopedLock (myLock);
  13667. // myLock is now locked
  13668. ...do some stuff...
  13669. // myLock gets unlocked here.
  13670. }
  13671. @endcode
  13672. @see ReadWriteLock, ScopedReadLock
  13673. */
  13674. class JUCE_API ScopedWriteLock
  13675. {
  13676. public:
  13677. /** Creates a ScopedWriteLock.
  13678. As soon as it is created, this will call ReadWriteLock::enterWrite(), and
  13679. when the ScopedWriteLock object is deleted, the ReadWriteLock will
  13680. be unlocked.
  13681. Make sure this object is created and deleted by the same thread,
  13682. otherwise there are no guarantees what will happen! Best just to use it
  13683. as a local stack object, rather than creating one with the new() operator.
  13684. */
  13685. inline explicit ScopedWriteLock (const ReadWriteLock& lock) throw() : lock_ (lock) { lock.enterWrite(); }
  13686. /** Destructor.
  13687. The ReadWriteLock's exitWrite() method will be called when the destructor is called.
  13688. Make sure this object is created and deleted by the same thread,
  13689. otherwise there are no guarantees what will happen!
  13690. */
  13691. inline ~ScopedWriteLock() throw() { lock_.exitWrite(); }
  13692. private:
  13693. const ReadWriteLock& lock_;
  13694. ScopedWriteLock (const ScopedWriteLock&);
  13695. ScopedWriteLock& operator= (const ScopedWriteLock&);
  13696. };
  13697. #endif // __JUCE_SCOPEDWRITELOCK_JUCEHEADER__
  13698. /*** End of inlined file: juce_ScopedWriteLock.h ***/
  13699. #endif
  13700. #ifndef __JUCE_THREAD_JUCEHEADER__
  13701. #endif
  13702. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13703. /*** Start of inlined file: juce_ThreadPool.h ***/
  13704. #ifndef __JUCE_THREADPOOL_JUCEHEADER__
  13705. #define __JUCE_THREADPOOL_JUCEHEADER__
  13706. class ThreadPool;
  13707. class ThreadPoolThread;
  13708. /**
  13709. A task that is executed by a ThreadPool object.
  13710. A ThreadPool keeps a list of ThreadPoolJob objects which are executed by
  13711. its threads.
  13712. The runJob() method needs to be implemented to do the task, and if the code that
  13713. does the work takes a significant time to run, it must keep checking the shouldExit()
  13714. method to see if something is trying to interrupt the job. If shouldExit() returns
  13715. true, the runJob() method must return immediately.
  13716. @see ThreadPool, Thread
  13717. */
  13718. class JUCE_API ThreadPoolJob
  13719. {
  13720. public:
  13721. /** Creates a thread pool job object.
  13722. After creating your job, add it to a thread pool with ThreadPool::addJob().
  13723. */
  13724. explicit ThreadPoolJob (const String& name);
  13725. /** Destructor. */
  13726. virtual ~ThreadPoolJob();
  13727. /** Returns the name of this job.
  13728. @see setJobName
  13729. */
  13730. const String getJobName() const;
  13731. /** Changes the job's name.
  13732. @see getJobName
  13733. */
  13734. void setJobName (const String& newName);
  13735. /** These are the values that can be returned by the runJob() method.
  13736. */
  13737. enum JobStatus
  13738. {
  13739. jobHasFinished = 0, /**< indicates that the job has finished and can be
  13740. removed from the pool. */
  13741. jobHasFinishedAndShouldBeDeleted, /**< indicates that the job has finished and that it
  13742. should be automatically deleted by the pool. */
  13743. jobNeedsRunningAgain /**< indicates that the job would like to be called
  13744. again when a thread is free. */
  13745. };
  13746. /** Peforms the actual work that this job needs to do.
  13747. Your subclass must implement this method, in which is does its work.
  13748. If the code in this method takes a significant time to run, it must repeatedly check
  13749. the shouldExit() method to see if something is trying to interrupt the job.
  13750. If shouldExit() ever returns true, the runJob() method must return immediately.
  13751. If this method returns jobHasFinished, then the job will be removed from the pool
  13752. immediately. If it returns jobNeedsRunningAgain, then the job will be left in the
  13753. pool and will get a chance to run again as soon as a thread is free.
  13754. @see shouldExit()
  13755. */
  13756. virtual JobStatus runJob() = 0;
  13757. /** Returns true if this job is currently running its runJob() method. */
  13758. bool isRunning() const { return isActive; }
  13759. /** Returns true if something is trying to interrupt this job and make it stop.
  13760. Your runJob() method must call this whenever it gets a chance, and if it ever
  13761. returns true, the runJob() method must return immediately.
  13762. @see signalJobShouldExit()
  13763. */
  13764. bool shouldExit() const { return shouldStop; }
  13765. /** Calling this will cause the shouldExit() method to return true, and the job
  13766. should (if it's been implemented correctly) stop as soon as possible.
  13767. @see shouldExit()
  13768. */
  13769. void signalJobShouldExit();
  13770. juce_UseDebuggingNewOperator
  13771. private:
  13772. friend class ThreadPool;
  13773. friend class ThreadPoolThread;
  13774. String jobName;
  13775. ThreadPool* pool;
  13776. bool shouldStop, isActive, shouldBeDeleted;
  13777. ThreadPoolJob (const ThreadPoolJob&);
  13778. ThreadPoolJob& operator= (const ThreadPoolJob&);
  13779. };
  13780. /**
  13781. A set of threads that will run a list of jobs.
  13782. When a ThreadPoolJob object is added to the ThreadPool's list, its run() method
  13783. will be called by the next pooled thread that becomes free.
  13784. @see ThreadPoolJob, Thread
  13785. */
  13786. class JUCE_API ThreadPool
  13787. {
  13788. public:
  13789. /** Creates a thread pool.
  13790. Once you've created a pool, you can give it some things to do with the addJob()
  13791. method.
  13792. @param numberOfThreads the maximum number of actual threads to run.
  13793. @param startThreadsOnlyWhenNeeded if this is true, then no threads will be started
  13794. until there are some jobs to run. If false, then
  13795. all the threads will be fired-up immediately so that
  13796. they're ready for action
  13797. @param stopThreadsWhenNotUsedTimeoutMs if this timeout is > 0, then if any threads have been
  13798. inactive for this length of time, they will automatically
  13799. be stopped until more jobs come along and they're needed
  13800. */
  13801. ThreadPool (int numberOfThreads,
  13802. bool startThreadsOnlyWhenNeeded = true,
  13803. int stopThreadsWhenNotUsedTimeoutMs = 5000);
  13804. /** Destructor.
  13805. This will attempt to remove all the jobs before deleting, but if you want to
  13806. specify a timeout, you should call removeAllJobs() explicitly before deleting
  13807. the pool.
  13808. */
  13809. ~ThreadPool();
  13810. /** A callback class used when you need to select which ThreadPoolJob objects are suitable
  13811. for some kind of operation.
  13812. @see ThreadPool::removeAllJobs
  13813. */
  13814. class JUCE_API JobSelector
  13815. {
  13816. public:
  13817. virtual ~JobSelector() {}
  13818. /** Should return true if the specified thread matches your criteria for whatever
  13819. operation that this object is being used for.
  13820. Any implementation of this method must be extremely fast and thread-safe!
  13821. */
  13822. virtual bool isJobSuitable (ThreadPoolJob* job) = 0;
  13823. };
  13824. /** Adds a job to the queue.
  13825. Once a job has been added, then the next time a thread is free, it will run
  13826. the job's ThreadPoolJob::runJob() method. Depending on the return value of the
  13827. runJob() method, the pool will either remove the job from the pool or add it to
  13828. the back of the queue to be run again.
  13829. */
  13830. void addJob (ThreadPoolJob* job);
  13831. /** Tries to remove a job from the pool.
  13832. If the job isn't yet running, this will simply remove it. If it is running, it
  13833. will wait for it to finish.
  13834. If the timeout period expires before the job finishes running, then the job will be
  13835. left in the pool and this will return false. It returns true if the job is sucessfully
  13836. stopped and removed.
  13837. @param job the job to remove
  13838. @param interruptIfRunning if true, then if the job is currently busy, its
  13839. ThreadPoolJob::signalJobShouldExit() method will be called to try
  13840. to interrupt it. If false, then if the job will be allowed to run
  13841. until it stops normally (or the timeout expires)
  13842. @param timeOutMilliseconds the length of time this method should wait for the job to finish
  13843. before giving up and returning false
  13844. */
  13845. bool removeJob (ThreadPoolJob* job,
  13846. bool interruptIfRunning,
  13847. int timeOutMilliseconds);
  13848. /** Tries to remove all jobs from the pool.
  13849. @param interruptRunningJobs if true, then all running jobs will have their ThreadPoolJob::signalJobShouldExit()
  13850. methods called to try to interrupt them
  13851. @param timeOutMilliseconds the length of time this method should wait for all the jobs to finish
  13852. before giving up and returning false
  13853. @param deleteInactiveJobs if true, any jobs that aren't currently running will be deleted. If false,
  13854. they will simply be removed from the pool. Jobs that are already running when
  13855. this method is called can choose whether they should be deleted by
  13856. returning jobHasFinishedAndShouldBeDeleted from their runJob() method.
  13857. @param selectedJobsToRemove if this is non-zero, the JobSelector object is asked to decide which
  13858. jobs should be removed. If it is zero, all jobs are removed
  13859. @returns true if all jobs are successfully stopped and removed; false if the timeout period
  13860. expires while waiting for one or more jobs to stop
  13861. */
  13862. bool removeAllJobs (bool interruptRunningJobs,
  13863. int timeOutMilliseconds,
  13864. bool deleteInactiveJobs = false,
  13865. JobSelector* selectedJobsToRemove = 0);
  13866. /** Returns the number of jobs currently running or queued.
  13867. */
  13868. int getNumJobs() const;
  13869. /** Returns one of the jobs in the queue.
  13870. Note that this can be a very volatile list as jobs might be continuously getting shifted
  13871. around in the list, and this method may return 0 if the index is currently out-of-range.
  13872. */
  13873. ThreadPoolJob* getJob (int index) const;
  13874. /** Returns true if the given job is currently queued or running.
  13875. @see isJobRunning()
  13876. */
  13877. bool contains (const ThreadPoolJob* job) const;
  13878. /** Returns true if the given job is currently being run by a thread.
  13879. */
  13880. bool isJobRunning (const ThreadPoolJob* job) const;
  13881. /** Waits until a job has finished running and has been removed from the pool.
  13882. This will wait until the job is no longer in the pool - i.e. until its
  13883. runJob() method returns ThreadPoolJob::jobHasFinished.
  13884. If the timeout period expires before the job finishes, this will return false;
  13885. it returns true if the job has finished successfully.
  13886. */
  13887. bool waitForJobToFinish (const ThreadPoolJob* job,
  13888. int timeOutMilliseconds) const;
  13889. /** Returns a list of the names of all the jobs currently running or queued.
  13890. If onlyReturnActiveJobs is true, only the ones currently running are returned.
  13891. */
  13892. const StringArray getNamesOfAllJobs (bool onlyReturnActiveJobs) const;
  13893. /** Changes the priority of all the threads.
  13894. This will call Thread::setPriority() for each thread in the pool.
  13895. May return false if for some reason the priority can't be changed.
  13896. */
  13897. bool setThreadPriorities (int newPriority);
  13898. juce_UseDebuggingNewOperator
  13899. private:
  13900. const int threadStopTimeout;
  13901. int priority;
  13902. class ThreadPoolThread;
  13903. OwnedArray <ThreadPoolThread> threads;
  13904. Array <ThreadPoolJob*> jobs;
  13905. CriticalSection lock;
  13906. uint32 lastJobEndTime;
  13907. WaitableEvent jobFinishedSignal;
  13908. friend class ThreadPoolThread;
  13909. bool runNextJob();
  13910. ThreadPool (const ThreadPool&);
  13911. ThreadPool& operator= (const ThreadPool&);
  13912. };
  13913. #endif // __JUCE_THREADPOOL_JUCEHEADER__
  13914. /*** End of inlined file: juce_ThreadPool.h ***/
  13915. #endif
  13916. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13917. /*** Start of inlined file: juce_TimeSliceThread.h ***/
  13918. #ifndef __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13919. #define __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13920. /**
  13921. Used by the TimeSliceThread class.
  13922. To register your class with a TimeSliceThread, derive from this class and
  13923. use the TimeSliceThread::addTimeSliceClient() method to add it to the list.
  13924. Make sure you always call TimeSliceThread::removeTimeSliceClient() before
  13925. deleting your client!
  13926. @see TimeSliceThread
  13927. */
  13928. class JUCE_API TimeSliceClient
  13929. {
  13930. public:
  13931. /** Destructor. */
  13932. virtual ~TimeSliceClient() {}
  13933. /** Called back by a TimeSliceThread.
  13934. When you register this class with it, a TimeSliceThread will repeatedly call
  13935. this method.
  13936. The implementation of this method should use its time-slice to do something that's
  13937. quick - never block for longer than absolutely necessary.
  13938. @returns Your method should return true if it needs more time, or false if it's
  13939. not too busy and doesn't need calling back urgently. If all the thread's
  13940. clients indicate that they're not busy, then it'll save CPU by sleeping for
  13941. up to half a second in between callbacks. You can force the TimeSliceThread
  13942. to wake up and poll again immediately by calling its notify() method.
  13943. */
  13944. virtual bool useTimeSlice() = 0;
  13945. };
  13946. /**
  13947. A thread that keeps a list of clients, and calls each one in turn, giving them
  13948. all a chance to run some sort of short task.
  13949. @see TimeSliceClient, Thread
  13950. */
  13951. class JUCE_API TimeSliceThread : public Thread
  13952. {
  13953. public:
  13954. /**
  13955. Creates a TimeSliceThread.
  13956. When first created, the thread is not running. Use the startThread()
  13957. method to start it.
  13958. */
  13959. explicit TimeSliceThread (const String& threadName);
  13960. /** Destructor.
  13961. Deleting a Thread object that is running will only give the thread a
  13962. brief opportunity to stop itself cleanly, so it's recommended that you
  13963. should always call stopThread() with a decent timeout before deleting,
  13964. to avoid the thread being forcibly killed (which is a Bad Thing).
  13965. */
  13966. ~TimeSliceThread();
  13967. /** Adds a client to the list.
  13968. The client's callbacks will start immediately (possibly before the method
  13969. has returned).
  13970. */
  13971. void addTimeSliceClient (TimeSliceClient* client);
  13972. /** Removes a client from the list.
  13973. This method will make sure that all callbacks to the client have completely
  13974. finished before the method returns.
  13975. */
  13976. void removeTimeSliceClient (TimeSliceClient* client);
  13977. /** Returns the number of registered clients. */
  13978. int getNumClients() const;
  13979. /** Returns one of the registered clients. */
  13980. TimeSliceClient* getClient (int index) const;
  13981. /** @internal */
  13982. void run();
  13983. juce_UseDebuggingNewOperator
  13984. private:
  13985. CriticalSection callbackLock, listLock;
  13986. Array <TimeSliceClient*> clients;
  13987. int index;
  13988. TimeSliceClient* clientBeingCalled;
  13989. bool clientsChanged;
  13990. TimeSliceThread (const TimeSliceThread&);
  13991. TimeSliceThread& operator= (const TimeSliceThread&);
  13992. };
  13993. #endif // __JUCE_TIMESLICETHREAD_JUCEHEADER__
  13994. /*** End of inlined file: juce_TimeSliceThread.h ***/
  13995. #endif
  13996. #ifndef __JUCE_WAITABLEEVENT_JUCEHEADER__
  13997. #endif
  13998. #endif
  13999. /*** End of inlined file: juce_core_includes.h ***/
  14000. // if you're compiling a command-line app, you might want to just include the core headers,
  14001. // so you can set this macro before including juce.h
  14002. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  14003. /*** Start of inlined file: juce_app_includes.h ***/
  14004. #ifndef __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  14005. #define __JUCE_JUCE_APP_INCLUDES_INCLUDEFILES__
  14006. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  14007. /*** Start of inlined file: juce_Application.h ***/
  14008. #ifndef __JUCE_APPLICATION_JUCEHEADER__
  14009. #define __JUCE_APPLICATION_JUCEHEADER__
  14010. /*** Start of inlined file: juce_ApplicationCommandTarget.h ***/
  14011. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  14012. #define __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  14013. /*** Start of inlined file: juce_Component.h ***/
  14014. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  14015. #define __JUCE_COMPONENT_JUCEHEADER__
  14016. /*** Start of inlined file: juce_MouseCursor.h ***/
  14017. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  14018. #define __JUCE_MOUSECURSOR_JUCEHEADER__
  14019. class Image;
  14020. class ComponentPeer;
  14021. class Component;
  14022. /**
  14023. Represents a mouse cursor image.
  14024. This object can either be used to represent one of the standard mouse
  14025. cursor shapes, or a custom one generated from an image.
  14026. */
  14027. class JUCE_API MouseCursor
  14028. {
  14029. public:
  14030. /** The set of available standard mouse cursors. */
  14031. enum StandardCursorType
  14032. {
  14033. NoCursor = 0, /**< An invisible cursor. */
  14034. NormalCursor, /**< The stardard arrow cursor. */
  14035. WaitCursor, /**< The normal hourglass or spinning-beachball 'busy' cursor. */
  14036. IBeamCursor, /**< A vertical I-beam for positioning within text. */
  14037. CrosshairCursor, /**< A pair of crosshairs. */
  14038. CopyingCursor, /**< The normal arrow cursor, but with a "+" on it to indicate
  14039. that you're dragging a copy of something. */
  14040. PointingHandCursor, /**< A hand with a pointing finger, for clicking on web-links. */
  14041. DraggingHandCursor, /**< An open flat hand for dragging heavy objects around. */
  14042. LeftRightResizeCursor, /**< An arrow pointing left and right. */
  14043. UpDownResizeCursor, /**< an arrow pointing up and down. */
  14044. UpDownLeftRightResizeCursor, /**< An arrow pointing up, down, left and right. */
  14045. TopEdgeResizeCursor, /**< A platform-specific cursor for resizing the top-edge of a window. */
  14046. BottomEdgeResizeCursor, /**< A platform-specific cursor for resizing the bottom-edge of a window. */
  14047. LeftEdgeResizeCursor, /**< A platform-specific cursor for resizing the left-edge of a window. */
  14048. RightEdgeResizeCursor, /**< A platform-specific cursor for resizing the right-edge of a window. */
  14049. TopLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the top-left-corner of a window. */
  14050. TopRightCornerResizeCursor, /**< A platform-specific cursor for resizing the top-right-corner of a window. */
  14051. BottomLeftCornerResizeCursor, /**< A platform-specific cursor for resizing the bottom-left-corner of a window. */
  14052. BottomRightCornerResizeCursor /**< A platform-specific cursor for resizing the bottom-right-corner of a window. */
  14053. };
  14054. /** Creates the standard arrow cursor. */
  14055. MouseCursor();
  14056. /** Creates one of the standard mouse cursor */
  14057. MouseCursor (StandardCursorType type);
  14058. /** Creates a custom cursor from an image.
  14059. @param image the image to use for the cursor - if this is bigger than the
  14060. system can manage, it might get scaled down first, and might
  14061. also have to be turned to black-and-white if it can't do colour
  14062. cursors.
  14063. @param hotSpotX the x position of the cursor's hotspot within the image
  14064. @param hotSpotY the y position of the cursor's hotspot within the image
  14065. */
  14066. MouseCursor (const Image& image, int hotSpotX, int hotSpotY);
  14067. /** Creates a copy of another cursor object. */
  14068. MouseCursor (const MouseCursor& other);
  14069. /** Copies this cursor from another object. */
  14070. MouseCursor& operator= (const MouseCursor& other);
  14071. /** Destructor. */
  14072. ~MouseCursor();
  14073. /** Checks whether two mouse cursors are the same.
  14074. For custom cursors, two cursors created from the same image won't be
  14075. recognised as the same, only MouseCursor objects that have been
  14076. copied from the same object.
  14077. */
  14078. bool operator== (const MouseCursor& other) const throw();
  14079. /** Checks whether two mouse cursors are the same.
  14080. For custom cursors, two cursors created from the same image won't be
  14081. recognised as the same, only MouseCursor objects that have been
  14082. copied from the same object.
  14083. */
  14084. bool operator!= (const MouseCursor& other) const throw();
  14085. /** Makes the system show its default 'busy' cursor.
  14086. This will turn the system cursor to an hourglass or spinning beachball
  14087. until the next time the mouse is moved, or hideWaitCursor() is called.
  14088. This is handy if the message loop is about to block for a couple of
  14089. seconds while busy and you want to give the user feedback about this.
  14090. @see MessageManager::setTimeBeforeShowingWaitCursor
  14091. */
  14092. static void showWaitCursor();
  14093. /** If showWaitCursor has been called, this will return the mouse to its
  14094. normal state.
  14095. This will look at what component is under the mouse, and update the
  14096. cursor to be the correct one for that component.
  14097. @see showWaitCursor
  14098. */
  14099. static void hideWaitCursor();
  14100. juce_UseDebuggingNewOperator
  14101. private:
  14102. class SharedCursorHandle;
  14103. friend class SharedCursorHandle;
  14104. SharedCursorHandle* cursorHandle;
  14105. friend class MouseInputSourceInternal;
  14106. void showInWindow (ComponentPeer* window) const;
  14107. void showInAllWindows() const;
  14108. void* getHandle() const throw();
  14109. static void* createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY);
  14110. static void* createStandardMouseCursor (MouseCursor::StandardCursorType type);
  14111. static void deleteMouseCursor (void* cursorHandle, bool isStandard);
  14112. };
  14113. #endif // __JUCE_MOUSECURSOR_JUCEHEADER__
  14114. /*** End of inlined file: juce_MouseCursor.h ***/
  14115. /*** Start of inlined file: juce_MouseListener.h ***/
  14116. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  14117. #define __JUCE_MOUSELISTENER_JUCEHEADER__
  14118. class MouseEvent;
  14119. /**
  14120. A MouseListener can be registered with a component to receive callbacks
  14121. about mouse events that happen to that component.
  14122. @see Component::addMouseListener, Component::removeMouseListener
  14123. */
  14124. class JUCE_API MouseListener
  14125. {
  14126. public:
  14127. /** Destructor. */
  14128. virtual ~MouseListener() {}
  14129. /** Called when the mouse moves inside a component.
  14130. If the mouse button isn't pressed and the mouse moves over a component,
  14131. this will be called to let the component react to this.
  14132. A component will always get a mouseEnter callback before a mouseMove.
  14133. @param e details about the position and status of the mouse event, including
  14134. the source component in which it occurred
  14135. @see mouseEnter, mouseExit, mouseDrag, contains
  14136. */
  14137. virtual void mouseMove (const MouseEvent& e);
  14138. /** Called when the mouse first enters a component.
  14139. If the mouse button isn't pressed and the mouse moves into a component,
  14140. this will be called to let the component react to this.
  14141. When the mouse button is pressed and held down while being moved in
  14142. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  14143. mouseDrag messages are sent to the component that the mouse was originally
  14144. clicked on, until the button is released.
  14145. @param e details about the position and status of the mouse event, including
  14146. the source component in which it occurred
  14147. @see mouseExit, mouseDrag, mouseMove, contains
  14148. */
  14149. virtual void mouseEnter (const MouseEvent& e);
  14150. /** Called when the mouse moves out of a component.
  14151. This will be called when the mouse moves off the edge of this
  14152. component.
  14153. If the mouse button was pressed, and it was then dragged off the
  14154. edge of the component and released, then this callback will happen
  14155. when the button is released, after the mouseUp callback.
  14156. @param e details about the position and status of the mouse event, including
  14157. the source component in which it occurred
  14158. @see mouseEnter, mouseDrag, mouseMove, contains
  14159. */
  14160. virtual void mouseExit (const MouseEvent& e);
  14161. /** Called when a mouse button is pressed.
  14162. The MouseEvent object passed in contains lots of methods for finding out
  14163. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14164. were held down at the time.
  14165. Once a button is held down, the mouseDrag method will be called when the
  14166. mouse moves, until the button is released.
  14167. @param e details about the position and status of the mouse event, including
  14168. the source component in which it occurred
  14169. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  14170. */
  14171. virtual void mouseDown (const MouseEvent& e);
  14172. /** Called when the mouse is moved while a button is held down.
  14173. When a mouse button is pressed inside a component, that component
  14174. receives mouseDrag callbacks each time the mouse moves, even if the
  14175. mouse strays outside the component's bounds.
  14176. @param e details about the position and status of the mouse event, including
  14177. the source component in which it occurred
  14178. @see mouseDown, mouseUp, mouseMove, contains, setDragRepeatInterval
  14179. */
  14180. virtual void mouseDrag (const MouseEvent& e);
  14181. /** Called when a mouse button is released.
  14182. A mouseUp callback is sent to the component in which a button was pressed
  14183. even if the mouse is actually over a different component when the
  14184. button is released.
  14185. The MouseEvent object passed in contains lots of methods for finding out
  14186. which buttons were down just before they were released.
  14187. @param e details about the position and status of the mouse event, including
  14188. the source component in which it occurred
  14189. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  14190. */
  14191. virtual void mouseUp (const MouseEvent& e);
  14192. /** Called when a mouse button has been double-clicked on a component.
  14193. The MouseEvent object passed in contains lots of methods for finding out
  14194. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  14195. were held down at the time.
  14196. @param e details about the position and status of the mouse event, including
  14197. the source component in which it occurred
  14198. @see mouseDown, mouseUp
  14199. */
  14200. virtual void mouseDoubleClick (const MouseEvent& e);
  14201. /** Called when the mouse-wheel is moved.
  14202. This callback is sent to the component that the mouse is over when the
  14203. wheel is moved.
  14204. If not overridden, the component will forward this message to its parent, so
  14205. that parent components can collect mouse-wheel messages that happen to
  14206. child components which aren't interested in them.
  14207. @param e details about the position and status of the mouse event, including
  14208. the source component in which it occurred
  14209. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  14210. value means the wheel has been pushed to the right, negative means it
  14211. was pushed to the left
  14212. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  14213. value means the wheel has been pushed upwards, negative means it
  14214. was pushed downwards
  14215. */
  14216. virtual void mouseWheelMove (const MouseEvent& e,
  14217. float wheelIncrementX,
  14218. float wheelIncrementY);
  14219. };
  14220. #endif // __JUCE_MOUSELISTENER_JUCEHEADER__
  14221. /*** End of inlined file: juce_MouseListener.h ***/
  14222. /*** Start of inlined file: juce_MouseEvent.h ***/
  14223. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  14224. #define __JUCE_MOUSEEVENT_JUCEHEADER__
  14225. class Component;
  14226. class MouseInputSource;
  14227. /*** Start of inlined file: juce_ModifierKeys.h ***/
  14228. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  14229. #define __JUCE_MODIFIERKEYS_JUCEHEADER__
  14230. /**
  14231. Represents the state of the mouse buttons and modifier keys.
  14232. This is used both by mouse events and by KeyPress objects to describe
  14233. the state of keys such as shift, control, alt, etc.
  14234. @see KeyPress, MouseEvent::mods
  14235. */
  14236. class JUCE_API ModifierKeys
  14237. {
  14238. public:
  14239. /** Creates a ModifierKeys object from a raw set of flags.
  14240. @param flags to represent the keys that are down
  14241. @see shiftModifier, ctrlModifier, altModifier, leftButtonModifier,
  14242. rightButtonModifier, commandModifier, popupMenuClickModifier
  14243. */
  14244. ModifierKeys (int flags = 0) throw();
  14245. /** Creates a copy of another object. */
  14246. ModifierKeys (const ModifierKeys& other) throw();
  14247. /** Copies this object from another one. */
  14248. ModifierKeys& operator= (const ModifierKeys& other) throw();
  14249. /** Checks whether the 'command' key flag is set (or 'ctrl' on Windows/Linux).
  14250. This is a platform-agnostic way of checking for the operating system's
  14251. preferred command-key modifier - so on the Mac it tests for the Apple key, on
  14252. Windows/Linux, it's actually checking for the CTRL key.
  14253. */
  14254. inline bool isCommandDown() const throw() { return (flags & commandModifier) != 0; }
  14255. /** Checks whether the user is trying to launch a pop-up menu.
  14256. This checks for platform-specific modifiers that might indicate that the user
  14257. is following the operating system's normal method of showing a pop-up menu.
  14258. So on Windows/Linux, this method is really testing for a right-click.
  14259. On the Mac, it tests for either the CTRL key being down, or a right-click.
  14260. */
  14261. inline bool isPopupMenu() const throw() { return (flags & popupMenuClickModifier) != 0; }
  14262. /** Checks whether the flag is set for the left mouse-button. */
  14263. inline bool isLeftButtonDown() const throw() { return (flags & leftButtonModifier) != 0; }
  14264. /** Checks whether the flag is set for the right mouse-button.
  14265. Note that for detecting popup-menu clicks, you should be using isPopupMenu() instead, as
  14266. this is platform-independent (and makes your code more explanatory too).
  14267. */
  14268. inline bool isRightButtonDown() const throw() { return (flags & rightButtonModifier) != 0; }
  14269. inline bool isMiddleButtonDown() const throw() { return (flags & middleButtonModifier) != 0; }
  14270. /** Tests for any of the mouse-button flags. */
  14271. inline bool isAnyMouseButtonDown() const throw() { return (flags & allMouseButtonModifiers) != 0; }
  14272. /** Tests for any of the modifier key flags. */
  14273. inline bool isAnyModifierKeyDown() const throw() { return (flags & (shiftModifier | ctrlModifier | altModifier | commandModifier)) != 0; }
  14274. /** Checks whether the shift key's flag is set. */
  14275. inline bool isShiftDown() const throw() { return (flags & shiftModifier) != 0; }
  14276. /** Checks whether the CTRL key's flag is set.
  14277. Remember that it's better to use the platform-agnostic routines to test for command-key and
  14278. popup-menu modifiers.
  14279. @see isCommandDown, isPopupMenu
  14280. */
  14281. inline bool isCtrlDown() const throw() { return (flags & ctrlModifier) != 0; }
  14282. /** Checks whether the shift key's flag is set. */
  14283. inline bool isAltDown() const throw() { return (flags & altModifier) != 0; }
  14284. /** Flags that represent the different keys. */
  14285. enum Flags
  14286. {
  14287. /** Shift key flag. */
  14288. shiftModifier = 1,
  14289. /** CTRL key flag. */
  14290. ctrlModifier = 2,
  14291. /** ALT key flag. */
  14292. altModifier = 4,
  14293. /** Left mouse button flag. */
  14294. leftButtonModifier = 16,
  14295. /** Right mouse button flag. */
  14296. rightButtonModifier = 32,
  14297. /** Middle mouse button flag. */
  14298. middleButtonModifier = 64,
  14299. #if JUCE_MAC
  14300. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14301. commandModifier = 8,
  14302. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14303. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14304. popupMenuClickModifier = rightButtonModifier | ctrlModifier,
  14305. #else
  14306. /** Command key flag - on windows this is the same as the CTRL key flag. */
  14307. commandModifier = ctrlModifier,
  14308. /** Popup menu flag - on windows this is the same as rightButtonModifier, on the
  14309. Mac it's the same as (rightButtonModifier | ctrlModifier). */
  14310. popupMenuClickModifier = rightButtonModifier,
  14311. #endif
  14312. /** Represents a combination of all the shift, alt, ctrl and command key modifiers. */
  14313. allKeyboardModifiers = shiftModifier | ctrlModifier | altModifier | commandModifier,
  14314. /** Represents a combination of all the mouse buttons at once. */
  14315. allMouseButtonModifiers = leftButtonModifier | rightButtonModifier | middleButtonModifier,
  14316. };
  14317. /** Returns a copy of only the mouse-button flags */
  14318. const ModifierKeys withOnlyMouseButtons() const throw() { return ModifierKeys (flags & allMouseButtonModifiers); }
  14319. /** Returns a copy of only the non-mouse flags */
  14320. const ModifierKeys withoutMouseButtons() const throw() { return ModifierKeys (flags & ~allMouseButtonModifiers); }
  14321. bool operator== (const ModifierKeys& other) const throw() { return flags == other.flags; }
  14322. bool operator!= (const ModifierKeys& other) const throw() { return flags != other.flags; }
  14323. /** Returns the raw flags for direct testing. */
  14324. inline int getRawFlags() const throw() { return flags; }
  14325. inline const ModifierKeys withoutFlags (int rawFlagsToClear) const throw() { return ModifierKeys (flags & ~rawFlagsToClear); }
  14326. inline const ModifierKeys withFlags (int rawFlagsToSet) const throw() { return ModifierKeys (flags | rawFlagsToSet); }
  14327. /** Tests a combination of flags and returns true if any of them are set. */
  14328. inline bool testFlags (const int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  14329. /** Returns the total number of mouse buttons that are down. */
  14330. int getNumMouseButtonsDown() const throw();
  14331. /** Creates a ModifierKeys object to represent the last-known state of the
  14332. keyboard and mouse buttons.
  14333. @see getCurrentModifiersRealtime
  14334. */
  14335. static const ModifierKeys getCurrentModifiers() throw();
  14336. /** Creates a ModifierKeys object to represent the current state of the
  14337. keyboard and mouse buttons.
  14338. This isn't often needed and isn't recommended, but will actively check all the
  14339. mouse and key states rather than just returning their last-known state like
  14340. getCurrentModifiers() does.
  14341. This is only needed in special circumstances for up-to-date modifier information
  14342. at times when the app's event loop isn't running normally.
  14343. */
  14344. static const ModifierKeys getCurrentModifiersRealtime() throw();
  14345. private:
  14346. int flags;
  14347. static ModifierKeys currentModifiers;
  14348. friend class ComponentPeer;
  14349. friend class MouseInputSource;
  14350. friend class MouseInputSourceInternal;
  14351. static void updateCurrentModifiers() throw();
  14352. };
  14353. #endif // __JUCE_MODIFIERKEYS_JUCEHEADER__
  14354. /*** End of inlined file: juce_ModifierKeys.h ***/
  14355. /*** Start of inlined file: juce_Point.h ***/
  14356. #ifndef __JUCE_POINT_JUCEHEADER__
  14357. #define __JUCE_POINT_JUCEHEADER__
  14358. /*** Start of inlined file: juce_AffineTransform.h ***/
  14359. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14360. #define __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14361. /**
  14362. Represents a 2D affine-transformation matrix.
  14363. An affine transformation is a transformation such as a rotation, scale, shear,
  14364. resize or translation.
  14365. These are used for various 2D transformation tasks, e.g. with Path objects.
  14366. @see Path, Point, Line
  14367. */
  14368. class JUCE_API AffineTransform
  14369. {
  14370. public:
  14371. /** Creates an identity transform. */
  14372. AffineTransform() throw();
  14373. /** Creates a copy of another transform. */
  14374. AffineTransform (const AffineTransform& other) throw();
  14375. /** Creates a transform from a set of raw matrix values.
  14376. The resulting matrix is:
  14377. (mat00 mat01 mat02)
  14378. (mat10 mat11 mat12)
  14379. ( 0 0 1 )
  14380. */
  14381. AffineTransform (float mat00, float mat01, float mat02,
  14382. float mat10, float mat11, float mat12) throw();
  14383. /** Copies from another AffineTransform object */
  14384. AffineTransform& operator= (const AffineTransform& other) throw();
  14385. /** Compares two transforms. */
  14386. bool operator== (const AffineTransform& other) const throw();
  14387. /** Compares two transforms. */
  14388. bool operator!= (const AffineTransform& other) const throw();
  14389. /** A ready-to-use identity transform, which you can use to append other
  14390. transformations to.
  14391. e.g. @code
  14392. AffineTransform myTransform = AffineTransform::identity.rotated (.5f)
  14393. .scaled (2.0f);
  14394. @endcode
  14395. */
  14396. static const AffineTransform identity;
  14397. /** Transforms a 2D co-ordinate using this matrix. */
  14398. template <typename ValueType>
  14399. void transformPoint (ValueType& x, ValueType& y) const throw()
  14400. {
  14401. const ValueType oldX = x;
  14402. x = static_cast <ValueType> (mat00 * oldX + mat01 * y + mat02);
  14403. y = static_cast <ValueType> (mat10 * oldX + mat11 * y + mat12);
  14404. }
  14405. /** Transforms two 2D co-ordinates using this matrix.
  14406. This is just a shortcut for calling transformPoint() on each of these pairs of
  14407. coordinates in turn. (And putting all the calculations into one function hopefully
  14408. also gives the compiler a bit more scope for pipelining it).
  14409. */
  14410. template <typename ValueType>
  14411. void transformPoints (ValueType& x1, ValueType& y1,
  14412. ValueType& x2, ValueType& y2) const throw()
  14413. {
  14414. const ValueType oldX1 = x1, oldX2 = x2;
  14415. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  14416. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  14417. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  14418. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  14419. }
  14420. /** Transforms three 2D co-ordinates using this matrix.
  14421. This is just a shortcut for calling transformPoint() on each of these pairs of
  14422. coordinates in turn. (And putting all the calculations into one function hopefully
  14423. also gives the compiler a bit more scope for pipelining it).
  14424. */
  14425. template <typename ValueType>
  14426. void transformPoints (ValueType& x1, ValueType& y1,
  14427. ValueType& x2, ValueType& y2,
  14428. ValueType& x3, ValueType& y3) const throw()
  14429. {
  14430. const ValueType oldX1 = x1, oldX2 = x2, oldX3 = x3;
  14431. x1 = static_cast <ValueType> (mat00 * oldX1 + mat01 * y1 + mat02);
  14432. y1 = static_cast <ValueType> (mat10 * oldX1 + mat11 * y1 + mat12);
  14433. x2 = static_cast <ValueType> (mat00 * oldX2 + mat01 * y2 + mat02);
  14434. y2 = static_cast <ValueType> (mat10 * oldX2 + mat11 * y2 + mat12);
  14435. x3 = static_cast <ValueType> (mat00 * oldX3 + mat01 * y3 + mat02);
  14436. y3 = static_cast <ValueType> (mat10 * oldX3 + mat11 * y3 + mat12);
  14437. }
  14438. /** Returns a new transform which is the same as this one followed by a translation. */
  14439. const AffineTransform translated (float deltaX,
  14440. float deltaY) const throw();
  14441. /** Returns a new transform which is a translation. */
  14442. static const AffineTransform translation (float deltaX,
  14443. float deltaY) throw();
  14444. /** Returns a transform which is the same as this one followed by a rotation.
  14445. The rotation is specified by a number of radians to rotate clockwise, centred around
  14446. the origin (0, 0).
  14447. */
  14448. const AffineTransform rotated (float angleInRadians) const throw();
  14449. /** Returns a transform which is the same as this one followed by a rotation about a given point.
  14450. The rotation is specified by a number of radians to rotate clockwise, centred around
  14451. the co-ordinates passed in.
  14452. */
  14453. const AffineTransform rotated (float angleInRadians,
  14454. float pivotX,
  14455. float pivotY) const throw();
  14456. /** Returns a new transform which is a rotation about (0, 0). */
  14457. static const AffineTransform rotation (float angleInRadians) throw();
  14458. /** Returns a new transform which is a rotation about a given point. */
  14459. static const AffineTransform rotation (float angleInRadians,
  14460. float pivotX,
  14461. float pivotY) throw();
  14462. /** Returns a transform which is the same as this one followed by a re-scaling.
  14463. The scaling is centred around the origin (0, 0).
  14464. */
  14465. const AffineTransform scaled (float factorX,
  14466. float factorY) const throw();
  14467. /** Returns a new transform which is a re-scale about the origin. */
  14468. static const AffineTransform scale (float factorX,
  14469. float factorY) throw();
  14470. /** Returns a transform which is the same as this one followed by a shear.
  14471. The shear is centred around the origin (0, 0).
  14472. */
  14473. const AffineTransform sheared (float shearX,
  14474. float shearY) const throw();
  14475. /** Returns a matrix which is the inverse operation of this one.
  14476. Some matrices don't have an inverse - in this case, the method will just return
  14477. an identity transform.
  14478. */
  14479. const AffineTransform inverted() const throw();
  14480. /** Returns the transform that will map three known points onto three coordinates
  14481. that are supplied.
  14482. This returns the transform that will transform (0, 0) into (x00, y00),
  14483. (1, 0) to (x10, y10), and (0, 1) to (x01, y01).
  14484. */
  14485. static const AffineTransform fromTargetPoints (float x00, float y00,
  14486. float x10, float y10,
  14487. float x01, float y01) throw();
  14488. /** Returns the transform that will map three specified points onto three target points.
  14489. */
  14490. static const AffineTransform fromTargetPoints (float sourceX1, float sourceY1, float targetX1, float targetY1,
  14491. float sourceX2, float sourceY2, float targetX2, float targetY2,
  14492. float sourceX3, float sourceY3, float targetX3, float targetY3) throw();
  14493. /** Returns the result of concatenating another transformation after this one. */
  14494. const AffineTransform followedBy (const AffineTransform& other) const throw();
  14495. /** Returns true if this transform has no effect on points. */
  14496. bool isIdentity() const throw();
  14497. /** Returns true if this transform maps to a singularity - i.e. if it has no inverse. */
  14498. bool isSingularity() const throw();
  14499. /** Returns true if the transform only translates, and doesn't scale or rotate the
  14500. points. */
  14501. bool isOnlyTranslation() const throw();
  14502. /** If this transform is only a translation, this returns the X offset.
  14503. @see isOnlyTranslation
  14504. */
  14505. float getTranslationX() const throw() { return mat02; }
  14506. /** If this transform is only a translation, this returns the X offset.
  14507. @see isOnlyTranslation
  14508. */
  14509. float getTranslationY() const throw() { return mat12; }
  14510. /* The transform matrix is:
  14511. (mat00 mat01 mat02)
  14512. (mat10 mat11 mat12)
  14513. ( 0 0 1 )
  14514. */
  14515. float mat00, mat01, mat02;
  14516. float mat10, mat11, mat12;
  14517. juce_UseDebuggingNewOperator
  14518. private:
  14519. const AffineTransform followedBy (float mat00, float mat01, float mat02,
  14520. float mat10, float mat11, float mat12) const throw();
  14521. };
  14522. #endif // __JUCE_AFFINETRANSFORM_JUCEHEADER__
  14523. /*** End of inlined file: juce_AffineTransform.h ***/
  14524. /**
  14525. A pair of (x, y) co-ordinates.
  14526. The ValueType template should be a primitive type such as int, float, double,
  14527. rather than a class.
  14528. @see Line, Path, AffineTransform
  14529. */
  14530. template <typename ValueType>
  14531. class Point
  14532. {
  14533. public:
  14534. /** Creates a point with co-ordinates (0, 0). */
  14535. Point() throw() : x (0), y (0) {}
  14536. /** Creates a copy of another point. */
  14537. Point (const Point& other) throw() : x (other.x), y (other.y) {}
  14538. /** Creates a point from an (x, y) position. */
  14539. Point (const ValueType initialX, const ValueType initialY) throw() : x (initialX), y (initialY) {}
  14540. /** Destructor. */
  14541. ~Point() throw() {}
  14542. /** Copies this point from another one. */
  14543. Point& operator= (const Point& other) throw() { x = other.x; y = other.y; return *this; }
  14544. inline bool operator== (const Point& other) const throw() { return x == other.x && y == other.y; }
  14545. inline bool operator!= (const Point& other) const throw() { return x != other.x || y != other.y; }
  14546. /** Returns true if the point is (0, 0). */
  14547. bool isOrigin() const throw() { return x == ValueType() && y == ValueType(); }
  14548. /** Returns the point's x co-ordinate. */
  14549. inline ValueType getX() const throw() { return x; }
  14550. /** Returns the point's y co-ordinate. */
  14551. inline ValueType getY() const throw() { return y; }
  14552. /** Sets the point's x co-ordinate. */
  14553. inline void setX (const ValueType newX) throw() { x = newX; }
  14554. /** Sets the point's y co-ordinate. */
  14555. inline void setY (const ValueType newY) throw() { y = newY; }
  14556. /** Returns a point which has the same Y position as this one, but a new X. */
  14557. const Point withX (const ValueType newX) const throw() { return Point (newX, y); }
  14558. /** Returns a point which has the same X position as this one, but a new Y. */
  14559. const Point withY (const ValueType newY) const throw() { return Point (x, newY); }
  14560. /** Changes the point's x and y co-ordinates. */
  14561. void setXY (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  14562. /** Adds a pair of co-ordinates to this value. */
  14563. void addXY (const ValueType xToAdd, const ValueType yToAdd) throw() { x += xToAdd; y += yToAdd; }
  14564. /** Returns a point with a given offset from this one. */
  14565. const Point translated (const ValueType xDelta, const ValueType yDelta) const throw() { return Point (x + xDelta, y + yDelta); }
  14566. /** Adds two points together. */
  14567. const Point operator+ (const Point& other) const throw() { return Point (x + other.x, y + other.y); }
  14568. /** Adds another point's co-ordinates to this one. */
  14569. Point& operator+= (const Point& other) throw() { x += other.x; y += other.y; return *this; }
  14570. /** Subtracts one points from another. */
  14571. const Point operator- (const Point& other) const throw() { return Point (x - other.x, y - other.y); }
  14572. /** Subtracts another point's co-ordinates to this one. */
  14573. Point& operator-= (const Point& other) throw() { x -= other.x; y -= other.y; return *this; }
  14574. /** Returns a point whose coordinates are multiplied by a given value. */
  14575. const Point operator* (const ValueType multiplier) const throw() { return Point (x * multiplier, y * multiplier); }
  14576. /** Multiplies the point's co-ordinates by a value. */
  14577. Point& operator*= (const ValueType multiplier) throw() { x *= multiplier; y *= multiplier; return *this; }
  14578. /** Returns a point whose coordinates are divided by a given value. */
  14579. const Point operator/ (const ValueType divisor) const throw() { return Point (x / divisor, y / divisor); }
  14580. /** Divides the point's co-ordinates by a value. */
  14581. Point& operator/= (const ValueType divisor) throw() { x /= divisor; y /= divisor; return *this; }
  14582. /** Returns the inverse of this point. */
  14583. const Point operator-() const throw() { return Point (-x, -y); }
  14584. /** Returns the straight-line distance between this point and another one. */
  14585. ValueType getDistanceFromOrigin() const throw() { return (ValueType) juce_hypot (x, y); }
  14586. /** Returns the straight-line distance between this point and another one. */
  14587. ValueType getDistanceFrom (const Point& other) const throw() { return (ValueType) juce_hypot (x - other.x, y - other.y); }
  14588. /** Returns the angle from this point to another one.
  14589. The return value is the number of radians clockwise from the 3 o'clock direction,
  14590. where this point is the centre and the other point is on the circumference.
  14591. */
  14592. ValueType getAngleToPoint (const Point& other) const throw() { return (ValueType) std::atan2 (other.x - x, other.y - y); }
  14593. /** Taking this point to be the centre of a circle, this returns a point on its circumference.
  14594. @param radius the radius of the circle.
  14595. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14596. */
  14597. const Point getPointOnCircumference (const float radius, const float angle) const throw() { return Point<float> (x + radius * std::sin (angle),
  14598. y - radius * std::cos (angle)); }
  14599. /** Taking this point to be the centre of an ellipse, this returns a point on its circumference.
  14600. @param radiusX the horizontal radius of the circle.
  14601. @param radiusY the vertical radius of the circle.
  14602. @param angle the angle of the point, in radians clockwise from the 12 o'clock position.
  14603. */
  14604. const Point getPointOnCircumference (const float radiusX, const float radiusY, const float angle) const throw() { return Point<float> (x + radiusX * std::sin (angle),
  14605. y - radiusY * std::cos (angle)); }
  14606. /** Uses a transform to change the point's co-ordinates.
  14607. This will only compile if ValueType = float!
  14608. @see AffineTransform::transformPoint
  14609. */
  14610. void applyTransform (const AffineTransform& transform) throw() { transform.transformPoint (x, y); }
  14611. /** Returns the position of this point, if it is transformed by a given AffineTransform. */
  14612. const Point transformedBy (const AffineTransform& transform) const throw() { return Point (transform.mat00 * x + transform.mat01 * y + transform.mat02,
  14613. transform.mat10 * x + transform.mat11 * y + transform.mat12); }
  14614. /** Casts this point to a Point<float> object. */
  14615. const Point<float> toFloat() const throw() { return Point<float> (static_cast <float> (x), static_cast<float> (y)); }
  14616. /** Casts this point to a Point<int> object. */
  14617. const Point<int> toInt() const throw() { return Point<int> (static_cast <int> (x), static_cast<int> (y)); }
  14618. /** Returns the point as a string in the form "x, y". */
  14619. const String toString() const { return String (x) + ", " + String (y); }
  14620. juce_UseDebuggingNewOperator
  14621. private:
  14622. ValueType x, y;
  14623. };
  14624. #endif // __JUCE_POINT_JUCEHEADER__
  14625. /*** End of inlined file: juce_Point.h ***/
  14626. /**
  14627. Contains position and status information about a mouse event.
  14628. @see MouseListener, Component::mouseMove, Component::mouseEnter, Component::mouseExit,
  14629. Component::mouseDown, Component::mouseUp, Component::mouseDrag
  14630. */
  14631. class JUCE_API MouseEvent
  14632. {
  14633. public:
  14634. /** Creates a MouseEvent.
  14635. Normally an application will never need to use this.
  14636. @param source the source that's invoking the event
  14637. @param position the position of the mouse, relative to the component that is passed-in
  14638. @param modifiers the key modifiers at the time of the event
  14639. @param eventComponent the component that the mouse event applies to
  14640. @param originator the component that originally received the event
  14641. @param eventTime the time the event happened
  14642. @param mouseDownPos the position of the corresponding mouse-down event (relative to the component that is passed-in).
  14643. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14644. the same as the current mouse-x position.
  14645. @param mouseDownTime the time at which the corresponding mouse-down event happened
  14646. If there isn't a corresponding mouse-down (e.g. for a mouse-move), this will just be
  14647. the same as the current mouse-event time.
  14648. @param numberOfClicks how many clicks, e.g. a double-click event will be 2, a triple-click will be 3, etc
  14649. @param mouseWasDragged whether the mouse has been dragged significantly since the previous mouse-down
  14650. */
  14651. MouseEvent (MouseInputSource& source,
  14652. const Point<int>& position,
  14653. const ModifierKeys& modifiers,
  14654. Component* eventComponent,
  14655. Component* originator,
  14656. const Time& eventTime,
  14657. const Point<int> mouseDownPos,
  14658. const Time& mouseDownTime,
  14659. int numberOfClicks,
  14660. bool mouseWasDragged) throw();
  14661. /** Destructor. */
  14662. ~MouseEvent() throw();
  14663. /** The x-position of the mouse when the event occurred.
  14664. This value is relative to the top-left of the component to which the
  14665. event applies (as indicated by the MouseEvent::eventComponent field).
  14666. */
  14667. const int x;
  14668. /** The y-position of the mouse when the event occurred.
  14669. This value is relative to the top-left of the component to which the
  14670. event applies (as indicated by the MouseEvent::eventComponent field).
  14671. */
  14672. const int y;
  14673. /** The key modifiers associated with the event.
  14674. This will let you find out which mouse buttons were down, as well as which
  14675. modifier keys were held down.
  14676. When used for mouse-up events, this will indicate the state of the mouse buttons
  14677. just before they were released, so that you can tell which button they let go of.
  14678. */
  14679. const ModifierKeys mods;
  14680. /** The component that this event applies to.
  14681. This is usually the component that the mouse was over at the time, but for mouse-drag
  14682. events the mouse could actually be over a different component and the events are
  14683. still sent to the component that the button was originally pressed on.
  14684. The x and y member variables are relative to this component's position.
  14685. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14686. component, this pointer will be updated, but originalComponent remains unchanged.
  14687. @see originalComponent
  14688. */
  14689. Component* const eventComponent;
  14690. /** The component that the event first occurred on.
  14691. If you use getEventRelativeTo() to retarget this object to be relative to a different
  14692. component, this value remains unchanged to indicate the first component that received it.
  14693. @see eventComponent
  14694. */
  14695. Component* const originalComponent;
  14696. /** The time that this mouse-event occurred.
  14697. */
  14698. const Time eventTime;
  14699. /** The source device that generated this event.
  14700. */
  14701. MouseInputSource& source;
  14702. /** Returns the x co-ordinate of the last place that a mouse was pressed.
  14703. The co-ordinate is relative to the component specified in MouseEvent::component.
  14704. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14705. */
  14706. int getMouseDownX() const throw();
  14707. /** Returns the y co-ordinate of the last place that a mouse was pressed.
  14708. The co-ordinate is relative to the component specified in MouseEvent::component.
  14709. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14710. */
  14711. int getMouseDownY() const throw();
  14712. /** Returns the co-ordinates of the last place that a mouse was pressed.
  14713. The co-ordinates are relative to the component specified in MouseEvent::component.
  14714. @see getDistanceFromDragStart, getDistanceFromDragStartX, mouseWasClicked
  14715. */
  14716. const Point<int> getMouseDownPosition() const throw();
  14717. /** Returns the straight-line distance between where the mouse is now and where it
  14718. was the last time the button was pressed.
  14719. This is quite handy for things like deciding whether the user has moved far enough
  14720. for it to be considered a drag operation.
  14721. @see getDistanceFromDragStartX
  14722. */
  14723. int getDistanceFromDragStart() const throw();
  14724. /** Returns the difference between the mouse's current x postion and where it was
  14725. when the button was last pressed.
  14726. @see getDistanceFromDragStart
  14727. */
  14728. int getDistanceFromDragStartX() const throw();
  14729. /** Returns the difference between the mouse's current y postion and where it was
  14730. when the button was last pressed.
  14731. @see getDistanceFromDragStart
  14732. */
  14733. int getDistanceFromDragStartY() const throw();
  14734. /** Returns the difference between the mouse's current postion and where it was
  14735. when the button was last pressed.
  14736. @see getDistanceFromDragStart
  14737. */
  14738. const Point<int> getOffsetFromDragStart() const throw();
  14739. /** Returns true if the mouse has just been clicked.
  14740. Used in either your mouseUp() or mouseDrag() methods, this will tell you whether
  14741. the user has dragged the mouse more than a few pixels from the place where the
  14742. mouse-down occurred.
  14743. Once they have dragged it far enough for this method to return false, it will continue
  14744. to return false until the mouse-up, even if they move the mouse back to the same
  14745. position where they originally pressed it. This means that it's very handy for
  14746. objects that can either be clicked on or dragged, as you can use it in the mouseDrag()
  14747. callback to ignore any small movements they might make while clicking.
  14748. @returns true if the mouse wasn't dragged by more than a few pixels between
  14749. the last time the button was pressed and released.
  14750. */
  14751. bool mouseWasClicked() const throw();
  14752. /** For a click event, the number of times the mouse was clicked in succession.
  14753. So for example a double-click event will return 2, a triple-click 3, etc.
  14754. */
  14755. int getNumberOfClicks() const throw() { return numberOfClicks; }
  14756. /** Returns the time that the mouse button has been held down for.
  14757. If called from a mouseDrag or mouseUp callback, this will return the
  14758. number of milliseconds since the corresponding mouseDown event occurred.
  14759. If called in other contexts, e.g. a mouseMove, then the returned value
  14760. may be 0 or an undefined value.
  14761. */
  14762. int getLengthOfMousePress() const throw();
  14763. /** The position of the mouse when the event occurred.
  14764. This position is relative to the top-left of the component to which the
  14765. event applies (as indicated by the MouseEvent::eventComponent field).
  14766. */
  14767. const Point<int> getPosition() const throw();
  14768. /** Returns the mouse x position of this event, in global screen co-ordinates.
  14769. The co-ordinates are relative to the top-left of the main monitor.
  14770. @see getScreenPosition
  14771. */
  14772. int getScreenX() const;
  14773. /** Returns the mouse y position of this event, in global screen co-ordinates.
  14774. The co-ordinates are relative to the top-left of the main monitor.
  14775. @see getScreenPosition
  14776. */
  14777. int getScreenY() const;
  14778. /** Returns the mouse position of this event, in global screen co-ordinates.
  14779. The co-ordinates are relative to the top-left of the main monitor.
  14780. @see getMouseDownScreenPosition
  14781. */
  14782. const Point<int> getScreenPosition() const;
  14783. /** Returns the x co-ordinate at which the mouse button was last pressed.
  14784. The co-ordinates are relative to the top-left of the main monitor.
  14785. @see getMouseDownScreenPosition
  14786. */
  14787. int getMouseDownScreenX() const;
  14788. /** Returns the y co-ordinate at which the mouse button was last pressed.
  14789. The co-ordinates are relative to the top-left of the main monitor.
  14790. @see getMouseDownScreenPosition
  14791. */
  14792. int getMouseDownScreenY() const;
  14793. /** Returns the co-ordinates at which the mouse button was last pressed.
  14794. The co-ordinates are relative to the top-left of the main monitor.
  14795. @see getScreenPosition
  14796. */
  14797. const Point<int> getMouseDownScreenPosition() const;
  14798. /** Creates a version of this event that is relative to a different component.
  14799. The x and y positions of the event that is returned will have been
  14800. adjusted to be relative to the new component.
  14801. */
  14802. const MouseEvent getEventRelativeTo (Component* otherComponent) const throw();
  14803. /** Creates a copy of this event with a different position.
  14804. All other members of the event object are the same, but the x and y are
  14805. replaced with these new values.
  14806. */
  14807. const MouseEvent withNewPosition (const Point<int>& newPosition) const throw();
  14808. /** Changes the application-wide setting for the double-click time limit.
  14809. This is the maximum length of time between mouse-clicks for it to be
  14810. considered a double-click. It's used by the Component class.
  14811. @see getDoubleClickTimeout, MouseListener::mouseDoubleClick
  14812. */
  14813. static void setDoubleClickTimeout (int timeOutMilliseconds) throw();
  14814. /** Returns the application-wide setting for the double-click time limit.
  14815. This is the maximum length of time between mouse-clicks for it to be
  14816. considered a double-click. It's used by the Component class.
  14817. @see setDoubleClickTimeout, MouseListener::mouseDoubleClick
  14818. */
  14819. static int getDoubleClickTimeout() throw();
  14820. juce_UseDebuggingNewOperator
  14821. private:
  14822. const Point<int> mouseDownPos;
  14823. const Time mouseDownTime;
  14824. const int numberOfClicks;
  14825. const bool wasMovedSinceMouseDown;
  14826. static int doubleClickTimeOutMs;
  14827. MouseEvent& operator= (const MouseEvent&);
  14828. };
  14829. #endif // __JUCE_MOUSEEVENT_JUCEHEADER__
  14830. /*** End of inlined file: juce_MouseEvent.h ***/
  14831. /*** Start of inlined file: juce_ComponentListener.h ***/
  14832. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14833. #define __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14834. class Component;
  14835. /**
  14836. Gets informed about changes to a component's hierarchy or position.
  14837. To monitor a component for changes, register a subclass of ComponentListener
  14838. with the component using Component::addComponentListener().
  14839. Be sure to deregister listeners before you delete them!
  14840. @see Component::addComponentListener, Component::removeComponentListener
  14841. */
  14842. class JUCE_API ComponentListener
  14843. {
  14844. public:
  14845. /** Destructor. */
  14846. virtual ~ComponentListener() {}
  14847. /** Called when the component's position or size changes.
  14848. @param component the component that was moved or resized
  14849. @param wasMoved true if the component's top-left corner has just moved
  14850. @param wasResized true if the component's width or height has just changed
  14851. @see Component::setBounds, Component::resized, Component::moved
  14852. */
  14853. virtual void componentMovedOrResized (Component& component,
  14854. bool wasMoved,
  14855. bool wasResized);
  14856. /** Called when the component is brought to the top of the z-order.
  14857. @param component the component that was moved
  14858. @see Component::toFront, Component::broughtToFront
  14859. */
  14860. virtual void componentBroughtToFront (Component& component);
  14861. /** Called when the component is made visible or invisible.
  14862. @param component the component that changed
  14863. @see Component::setVisible
  14864. */
  14865. virtual void componentVisibilityChanged (Component& component);
  14866. /** Called when the component has children added or removed.
  14867. @param component the component whose children were changed
  14868. @see Component::childrenChanged, Component::addChildComponent,
  14869. Component::removeChildComponent
  14870. */
  14871. virtual void componentChildrenChanged (Component& component);
  14872. /** Called to indicate that the component's parents have changed.
  14873. When a component is added or removed from its parent, all of its children
  14874. will produce this notification (recursively - so all children of its
  14875. children will also be called as well).
  14876. @param component the component that this listener is registered with
  14877. @see Component::parentHierarchyChanged
  14878. */
  14879. virtual void componentParentHierarchyChanged (Component& component);
  14880. /** Called when the component's name is changed.
  14881. @see Component::setName, Component::getName
  14882. */
  14883. virtual void componentNameChanged (Component& component);
  14884. /** Called when the component is in the process of being deleted.
  14885. This callback is made from inside the destructor, so be very, very cautious
  14886. about what you do inside the callback.
  14887. It will be called before the component has been removed from its parent, and
  14888. before any child components have been removed.
  14889. */
  14890. virtual void componentBeingDeleted (Component& component);
  14891. };
  14892. #endif // __JUCE_COMPONENTLISTENER_JUCEHEADER__
  14893. /*** End of inlined file: juce_ComponentListener.h ***/
  14894. /*** Start of inlined file: juce_KeyListener.h ***/
  14895. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  14896. #define __JUCE_KEYLISTENER_JUCEHEADER__
  14897. /*** Start of inlined file: juce_KeyPress.h ***/
  14898. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  14899. #define __JUCE_KEYPRESS_JUCEHEADER__
  14900. /**
  14901. Represents a key press, including any modifier keys that are needed.
  14902. E.g. a KeyPress might represent CTRL+C, SHIFT+ALT+H, Spacebar, Escape, etc.
  14903. @see Component, KeyListener, Button::addShortcut, KeyPressMappingManager
  14904. */
  14905. class JUCE_API KeyPress
  14906. {
  14907. public:
  14908. /** Creates an (invalid) KeyPress.
  14909. @see isValid
  14910. */
  14911. KeyPress() throw();
  14912. /** Creates a KeyPress for a key and some modifiers.
  14913. e.g.
  14914. CTRL+C would be: KeyPress ('c', ModifierKeys::ctrlModifier)
  14915. SHIFT+Escape would be: KeyPress (KeyPress::escapeKey, ModifierKeys::shiftModifier)
  14916. @param keyCode a code that represents the key - this value must be
  14917. one of special constants listed in this class, or an
  14918. 8-bit character code such as a letter (case is ignored),
  14919. digit or a simple key like "," or ".". Note that this
  14920. isn't the same as the textCharacter parameter, so for example
  14921. a keyCode of 'a' and a shift-key modifier should have a
  14922. textCharacter value of 'A'.
  14923. @param modifiers the modifiers to associate with the keystroke
  14924. @param textCharacter the character that would be printed if someone typed
  14925. this keypress into a text editor. This value may be
  14926. null if the keypress is a non-printing character
  14927. @see getKeyCode, isKeyCode, getModifiers
  14928. */
  14929. KeyPress (int keyCode,
  14930. const ModifierKeys& modifiers,
  14931. juce_wchar textCharacter) throw();
  14932. /** Creates a keypress with a keyCode but no modifiers or text character.
  14933. */
  14934. KeyPress (int keyCode) throw();
  14935. /** Creates a copy of another KeyPress. */
  14936. KeyPress (const KeyPress& other) throw();
  14937. /** Copies this KeyPress from another one. */
  14938. KeyPress& operator= (const KeyPress& other) throw();
  14939. /** Compares two KeyPress objects. */
  14940. bool operator== (const KeyPress& other) const throw();
  14941. /** Compares two KeyPress objects. */
  14942. bool operator!= (const KeyPress& other) const throw();
  14943. /** Returns true if this is a valid KeyPress.
  14944. A null keypress can be created by the default constructor, in case it's
  14945. needed.
  14946. */
  14947. bool isValid() const throw() { return keyCode != 0; }
  14948. /** Returns the key code itself.
  14949. This will either be one of the special constants defined in this class,
  14950. or an 8-bit character code.
  14951. */
  14952. int getKeyCode() const throw() { return keyCode; }
  14953. /** Returns the key modifiers.
  14954. @see ModifierKeys
  14955. */
  14956. const ModifierKeys getModifiers() const throw() { return mods; }
  14957. /** Returns the character that is associated with this keypress.
  14958. This is the character that you'd expect to see printed if you press this
  14959. keypress in a text editor or similar component.
  14960. */
  14961. juce_wchar getTextCharacter() const throw() { return textCharacter; }
  14962. /** Checks whether the KeyPress's key is the same as the one provided, without checking
  14963. the modifiers.
  14964. The values for key codes can either be one of the special constants defined in
  14965. this class, or an 8-bit character code.
  14966. @see getKeyCode
  14967. */
  14968. bool isKeyCode (int keyCodeToCompare) const throw() { return keyCode == keyCodeToCompare; }
  14969. /** Converts a textual key description to a KeyPress.
  14970. This attempts to decode a textual version of a keypress, e.g. "CTRL + C" or "SPACE".
  14971. This isn't designed to cope with any kind of input, but should be given the
  14972. strings that are created by the getTextDescription() method.
  14973. If the string can't be parsed, the object returned will be invalid.
  14974. @see getTextDescription
  14975. */
  14976. static const KeyPress createFromDescription (const String& textVersion);
  14977. /** Creates a textual description of the key combination.
  14978. e.g. "CTRL + C" or "DELETE".
  14979. To store a keypress in a file, use this method, along with createFromDescription()
  14980. to retrieve it later.
  14981. */
  14982. const String getTextDescription() const;
  14983. /** Checks whether the user is currently holding down the keys that make up this
  14984. KeyPress.
  14985. Note that this will return false if any extra modifier keys are
  14986. down - e.g. if the keypress is CTRL+X and the user is actually holding CTRL+ALT+x
  14987. then it will be false.
  14988. */
  14989. bool isCurrentlyDown() const;
  14990. /** Checks whether a particular key is held down, irrespective of modifiers.
  14991. The values for key codes can either be one of the special constants defined in
  14992. this class, or an 8-bit character code.
  14993. */
  14994. static bool isKeyCurrentlyDown (int keyCode);
  14995. // Key codes
  14996. //
  14997. // Note that the actual values of these are platform-specific and may change
  14998. // without warning, so don't store them anywhere as constants. For persisting/retrieving
  14999. // KeyPress objects, use getTextDescription() and createFromDescription() instead.
  15000. //
  15001. static const int spaceKey; /**< key-code for the space bar */
  15002. static const int escapeKey; /**< key-code for the escape key */
  15003. static const int returnKey; /**< key-code for the return key*/
  15004. static const int tabKey; /**< key-code for the tab key*/
  15005. static const int deleteKey; /**< key-code for the delete key (not backspace) */
  15006. static const int backspaceKey; /**< key-code for the backspace key */
  15007. static const int insertKey; /**< key-code for the insert key */
  15008. static const int upKey; /**< key-code for the cursor-up key */
  15009. static const int downKey; /**< key-code for the cursor-down key */
  15010. static const int leftKey; /**< key-code for the cursor-left key */
  15011. static const int rightKey; /**< key-code for the cursor-right key */
  15012. static const int pageUpKey; /**< key-code for the page-up key */
  15013. static const int pageDownKey; /**< key-code for the page-down key */
  15014. static const int homeKey; /**< key-code for the home key */
  15015. static const int endKey; /**< key-code for the end key */
  15016. static const int F1Key; /**< key-code for the F1 key */
  15017. static const int F2Key; /**< key-code for the F2 key */
  15018. static const int F3Key; /**< key-code for the F3 key */
  15019. static const int F4Key; /**< key-code for the F4 key */
  15020. static const int F5Key; /**< key-code for the F5 key */
  15021. static const int F6Key; /**< key-code for the F6 key */
  15022. static const int F7Key; /**< key-code for the F7 key */
  15023. static const int F8Key; /**< key-code for the F8 key */
  15024. static const int F9Key; /**< key-code for the F9 key */
  15025. static const int F10Key; /**< key-code for the F10 key */
  15026. static const int F11Key; /**< key-code for the F11 key */
  15027. static const int F12Key; /**< key-code for the F12 key */
  15028. static const int F13Key; /**< key-code for the F13 key */
  15029. static const int F14Key; /**< key-code for the F14 key */
  15030. static const int F15Key; /**< key-code for the F15 key */
  15031. static const int F16Key; /**< key-code for the F16 key */
  15032. static const int numberPad0; /**< key-code for the 0 on the numeric keypad. */
  15033. static const int numberPad1; /**< key-code for the 1 on the numeric keypad. */
  15034. static const int numberPad2; /**< key-code for the 2 on the numeric keypad. */
  15035. static const int numberPad3; /**< key-code for the 3 on the numeric keypad. */
  15036. static const int numberPad4; /**< key-code for the 4 on the numeric keypad. */
  15037. static const int numberPad5; /**< key-code for the 5 on the numeric keypad. */
  15038. static const int numberPad6; /**< key-code for the 6 on the numeric keypad. */
  15039. static const int numberPad7; /**< key-code for the 7 on the numeric keypad. */
  15040. static const int numberPad8; /**< key-code for the 8 on the numeric keypad. */
  15041. static const int numberPad9; /**< key-code for the 9 on the numeric keypad. */
  15042. static const int numberPadAdd; /**< key-code for the add sign on the numeric keypad. */
  15043. static const int numberPadSubtract; /**< key-code for the subtract sign on the numeric keypad. */
  15044. static const int numberPadMultiply; /**< key-code for the multiply sign on the numeric keypad. */
  15045. static const int numberPadDivide; /**< key-code for the divide sign on the numeric keypad. */
  15046. static const int numberPadSeparator; /**< key-code for the comma on the numeric keypad. */
  15047. static const int numberPadDecimalPoint; /**< key-code for the decimal point sign on the numeric keypad. */
  15048. static const int numberPadEquals; /**< key-code for the equals key on the numeric keypad. */
  15049. static const int numberPadDelete; /**< key-code for the delete key on the numeric keypad. */
  15050. static const int playKey; /**< key-code for a multimedia 'play' key, (not all keyboards will have one) */
  15051. static const int stopKey; /**< key-code for a multimedia 'stop' key, (not all keyboards will have one) */
  15052. static const int fastForwardKey; /**< key-code for a multimedia 'fast-forward' key, (not all keyboards will have one) */
  15053. static const int rewindKey; /**< key-code for a multimedia 'rewind' key, (not all keyboards will have one) */
  15054. juce_UseDebuggingNewOperator
  15055. private:
  15056. int keyCode;
  15057. ModifierKeys mods;
  15058. juce_wchar textCharacter;
  15059. };
  15060. #endif // __JUCE_KEYPRESS_JUCEHEADER__
  15061. /*** End of inlined file: juce_KeyPress.h ***/
  15062. class Component;
  15063. /**
  15064. Receives callbacks when keys are pressed.
  15065. You can add a key listener to a component to be informed when that component
  15066. gets key events. See the Component::addListener method for more details.
  15067. @see KeyPress, Component::addKeyListener, KeyPressMappingManager
  15068. */
  15069. class JUCE_API KeyListener
  15070. {
  15071. public:
  15072. /** Destructor. */
  15073. virtual ~KeyListener() {}
  15074. /** Called to indicate that a key has been pressed.
  15075. If your implementation returns true, then the key event is considered to have
  15076. been consumed, and will not be passed on to any other components. If it returns
  15077. false, then the key will be passed to other components that might want to use it.
  15078. @param key the keystroke, including modifier keys
  15079. @param originatingComponent the component that received the key event
  15080. @see keyStateChanged, Component::keyPressed
  15081. */
  15082. virtual bool keyPressed (const KeyPress& key,
  15083. Component* originatingComponent) = 0;
  15084. /** Called when any key is pressed or released.
  15085. When this is called, classes that might be interested in
  15086. the state of one or more keys can use KeyPress::isKeyCurrentlyDown() to
  15087. check whether their key has changed.
  15088. If your implementation returns true, then the key event is considered to have
  15089. been consumed, and will not be passed on to any other components. If it returns
  15090. false, then the key will be passed to other components that might want to use it.
  15091. @param originatingComponent the component that received the key event
  15092. @param isKeyDown true if a key is being pressed, false if one is being released
  15093. @see KeyPress, Component::keyStateChanged
  15094. */
  15095. virtual bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  15096. };
  15097. #endif // __JUCE_KEYLISTENER_JUCEHEADER__
  15098. /*** End of inlined file: juce_KeyListener.h ***/
  15099. /*** Start of inlined file: juce_KeyboardFocusTraverser.h ***/
  15100. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15101. #define __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15102. class Component;
  15103. /**
  15104. Controls the order in which focus moves between components.
  15105. The default algorithm used by this class to work out the order of traversal
  15106. is as follows:
  15107. - if two components both have an explicit focus order specified, then the
  15108. one with the lowest number comes first (see the Component::setExplicitFocusOrder()
  15109. method).
  15110. - any component with an explicit focus order greater than 0 comes before ones
  15111. that don't have an order specified.
  15112. - any unspecified components are traversed in a left-to-right, then top-to-bottom
  15113. order.
  15114. If you need traversal in a more customised way, you can create a subclass
  15115. of KeyboardFocusTraverser that uses your own algorithm, and use
  15116. Component::createFocusTraverser() to create it.
  15117. @see Component::setExplicitFocusOrder, Component::createFocusTraverser
  15118. */
  15119. class JUCE_API KeyboardFocusTraverser
  15120. {
  15121. public:
  15122. KeyboardFocusTraverser();
  15123. /** Destructor. */
  15124. virtual ~KeyboardFocusTraverser();
  15125. /** Returns the component that should be given focus after the specified one
  15126. when moving "forwards".
  15127. The default implementation will return the next component which is to the
  15128. right of or below this one.
  15129. This may return 0 if there's no suitable candidate.
  15130. */
  15131. virtual Component* getNextComponent (Component* current);
  15132. /** Returns the component that should be given focus after the specified one
  15133. when moving "backwards".
  15134. The default implementation will return the next component which is to the
  15135. left of or above this one.
  15136. This may return 0 if there's no suitable candidate.
  15137. */
  15138. virtual Component* getPreviousComponent (Component* current);
  15139. /** Returns the component that should receive focus be default within the given
  15140. parent component.
  15141. The default implementation will just return the foremost child component that
  15142. wants focus.
  15143. This may return 0 if there's no suitable candidate.
  15144. */
  15145. virtual Component* getDefaultComponent (Component* parentComponent);
  15146. };
  15147. #endif // __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  15148. /*** End of inlined file: juce_KeyboardFocusTraverser.h ***/
  15149. /*** Start of inlined file: juce_ImageEffectFilter.h ***/
  15150. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15151. #define __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  15152. /*** Start of inlined file: juce_Graphics.h ***/
  15153. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  15154. #define __JUCE_GRAPHICS_JUCEHEADER__
  15155. /*** Start of inlined file: juce_Font.h ***/
  15156. #ifndef __JUCE_FONT_JUCEHEADER__
  15157. #define __JUCE_FONT_JUCEHEADER__
  15158. /*** Start of inlined file: juce_Typeface.h ***/
  15159. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  15160. #define __JUCE_TYPEFACE_JUCEHEADER__
  15161. /*** Start of inlined file: juce_Path.h ***/
  15162. #ifndef __JUCE_PATH_JUCEHEADER__
  15163. #define __JUCE_PATH_JUCEHEADER__
  15164. /*** Start of inlined file: juce_Line.h ***/
  15165. #ifndef __JUCE_LINE_JUCEHEADER__
  15166. #define __JUCE_LINE_JUCEHEADER__
  15167. /**
  15168. Represents a line.
  15169. This class contains a bunch of useful methods for various geometric
  15170. tasks.
  15171. The ValueType template parameter should be a primitive type - float or double
  15172. are what it's designed for. Integer types will work in a basic way, but some methods
  15173. that perform mathematical operations may not compile, or they may not produce
  15174. sensible results.
  15175. @see Point, Rectangle, Path, Graphics::drawLine
  15176. */
  15177. template <typename ValueType>
  15178. class Line
  15179. {
  15180. public:
  15181. /** Creates a line, using (0, 0) as its start and end points. */
  15182. Line() throw() {}
  15183. /** Creates a copy of another line. */
  15184. Line (const Line& other) throw()
  15185. : start (other.start),
  15186. end (other.end)
  15187. {
  15188. }
  15189. /** Creates a line based on the co-ordinates of its start and end points. */
  15190. Line (ValueType startX, ValueType startY, ValueType endX, ValueType endY) throw()
  15191. : start (startX, startY),
  15192. end (endX, endY)
  15193. {
  15194. }
  15195. /** Creates a line from its start and end points. */
  15196. Line (const Point<ValueType>& startPoint,
  15197. const Point<ValueType>& endPoint) throw()
  15198. : start (startPoint),
  15199. end (endPoint)
  15200. {
  15201. }
  15202. /** Copies a line from another one. */
  15203. Line& operator= (const Line& other) throw()
  15204. {
  15205. start = other.start;
  15206. end = other.end;
  15207. return *this;
  15208. }
  15209. /** Destructor. */
  15210. ~Line() throw() {}
  15211. /** Returns the x co-ordinate of the line's start point. */
  15212. inline ValueType getStartX() const throw() { return start.getX(); }
  15213. /** Returns the y co-ordinate of the line's start point. */
  15214. inline ValueType getStartY() const throw() { return start.getY(); }
  15215. /** Returns the x co-ordinate of the line's end point. */
  15216. inline ValueType getEndX() const throw() { return end.getX(); }
  15217. /** Returns the y co-ordinate of the line's end point. */
  15218. inline ValueType getEndY() const throw() { return end.getY(); }
  15219. /** Returns the line's start point. */
  15220. inline const Point<ValueType>& getStart() const throw() { return start; }
  15221. /** Returns the line's end point. */
  15222. inline const Point<ValueType>& getEnd() const throw() { return end; }
  15223. /** Changes this line's start point */
  15224. void setStart (ValueType newStartX, ValueType newStartY) throw() { start.setXY (newStartX, newStartY); }
  15225. /** Changes this line's end point */
  15226. void setEnd (ValueType newEndX, ValueType newEndY) throw() { end.setXY (newEndX, newEndY); }
  15227. /** Changes this line's start point */
  15228. void setStart (const Point<ValueType>& newStart) throw() { start = newStart; }
  15229. /** Changes this line's end point */
  15230. void setEnd (const Point<ValueType>& newEnd) throw() { end = newEnd; }
  15231. /** Returns a line that is the same as this one, but with the start and end reversed, */
  15232. const Line reversed() const throw() { return Line (end, start); }
  15233. /** Applies an affine transform to the line's start and end points. */
  15234. void applyTransform (const AffineTransform& transform) throw()
  15235. {
  15236. start.applyTransform (transform);
  15237. end.applyTransform (transform);
  15238. }
  15239. /** Returns the length of the line. */
  15240. ValueType getLength() const throw() { return start.getDistanceFrom (end); }
  15241. /** Returns true if the line's start and end x co-ordinates are the same. */
  15242. bool isVertical() const throw() { return start.getX() == end.getX(); }
  15243. /** Returns true if the line's start and end y co-ordinates are the same. */
  15244. bool isHorizontal() const throw() { return start.getY() == end.getY(); }
  15245. /** Returns the line's angle.
  15246. This value is the number of radians clockwise from the 3 o'clock direction,
  15247. where the line's start point is considered to be at the centre.
  15248. */
  15249. ValueType getAngle() const throw() { return start.getAngleToPoint (end); }
  15250. /** Compares two lines. */
  15251. bool operator== (const Line& other) const throw() { return start == other.start && end == other.end; }
  15252. /** Compares two lines. */
  15253. bool operator!= (const Line& other) const throw() { return start != other.start || end != other.end; }
  15254. /** Finds the intersection between two lines.
  15255. @param line the other line
  15256. @param intersection the position of the point where the lines meet (or
  15257. where they would meet if they were infinitely long)
  15258. the intersection (if the lines intersect). If the lines
  15259. are parallel, this will just be set to the position
  15260. of one of the line's endpoints.
  15261. @returns true if the line segments intersect; false if they dont. Even if they
  15262. don't intersect, the intersection co-ordinates returned will still
  15263. be valid
  15264. */
  15265. bool intersects (const Line& line, Point<ValueType>& intersection) const throw()
  15266. {
  15267. return findIntersection (start, end, line.start, line.end, intersection);
  15268. }
  15269. /** Finds the intersection between two lines.
  15270. @param line the line to intersect with
  15271. @returns the point at which the lines intersect, even if this lies beyond the end of the lines
  15272. */
  15273. const Point<ValueType> getIntersection (const Line& line) const throw()
  15274. {
  15275. Point<ValueType> p;
  15276. findIntersection (start, end, line.start, line.end, p);
  15277. return p;
  15278. }
  15279. /** Returns the location of the point which is a given distance along this line.
  15280. @param distanceFromStart the distance to move along the line from its
  15281. start point. This value can be negative or longer
  15282. than the line itself
  15283. @see getPointAlongLineProportionally
  15284. */
  15285. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart) const throw()
  15286. {
  15287. return start + (end - start) * (distanceFromStart / getLength());
  15288. }
  15289. /** Returns a point which is a certain distance along and to the side of this line.
  15290. This effectively moves a given distance along the line, then another distance
  15291. perpendicularly to this, and returns the resulting position.
  15292. @param distanceFromStart the distance to move along the line from its
  15293. start point. This value can be negative or longer
  15294. than the line itself
  15295. @param perpendicularDistance how far to move sideways from the line. If you're
  15296. looking along the line from its start towards its
  15297. end, then a positive value here will move to the
  15298. right, negative value move to the left.
  15299. */
  15300. const Point<ValueType> getPointAlongLine (ValueType distanceFromStart,
  15301. ValueType perpendicularDistance) const throw()
  15302. {
  15303. const Point<ValueType> delta (end - start);
  15304. const double length = juce_hypot (delta.getX(), delta.getY());
  15305. if (length == 0)
  15306. return start;
  15307. return Point<ValueType> (start.getX() + (ValueType) ((delta.getX() * distanceFromStart - delta.getY() * perpendicularDistance) / length),
  15308. start.getY() + (ValueType) ((delta.getY() * distanceFromStart + delta.getX() * perpendicularDistance) / length));
  15309. }
  15310. /** Returns the location of the point which is a given distance along this line
  15311. proportional to the line's length.
  15312. @param proportionOfLength the distance to move along the line from its
  15313. start point, in multiples of the line's length.
  15314. So a value of 0.0 will return the line's start point
  15315. and a value of 1.0 will return its end point. (This value
  15316. can be negative or greater than 1.0).
  15317. @see getPointAlongLine
  15318. */
  15319. const Point<ValueType> getPointAlongLineProportionally (ValueType proportionOfLength) const throw()
  15320. {
  15321. return start + (end - start) * proportionOfLength;
  15322. }
  15323. /** Returns the smallest distance between this line segment and a given point.
  15324. So if the point is close to the line, this will return the perpendicular
  15325. distance from the line; if the point is a long way beyond one of the line's
  15326. end-point's, it'll return the straight-line distance to the nearest end-point.
  15327. pointOnLine receives the position of the point that is found.
  15328. @returns the point's distance from the line
  15329. @see getPositionAlongLineOfNearestPoint
  15330. */
  15331. ValueType getDistanceFromPoint (const Point<ValueType>& targetPoint,
  15332. Point<ValueType>& pointOnLine) const throw()
  15333. {
  15334. const Point<ValueType> delta (end - start);
  15335. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15336. if (length > 0)
  15337. {
  15338. const double prop = ((targetPoint.getX() - start.getX()) * delta.getX()
  15339. + (targetPoint.getY() - start.getY()) * delta.getY()) / length;
  15340. if (prop >= 0 && prop <= 1.0)
  15341. {
  15342. pointOnLine = start + delta * (ValueType) prop;
  15343. return targetPoint.getDistanceFrom (pointOnLine);
  15344. }
  15345. }
  15346. const float fromStart = targetPoint.getDistanceFrom (start);
  15347. const float fromEnd = targetPoint.getDistanceFrom (end);
  15348. if (fromStart < fromEnd)
  15349. {
  15350. pointOnLine = start;
  15351. return fromStart;
  15352. }
  15353. else
  15354. {
  15355. pointOnLine = end;
  15356. return fromEnd;
  15357. }
  15358. }
  15359. /** Finds the point on this line which is nearest to a given point, and
  15360. returns its position as a proportional position along the line.
  15361. @returns a value 0 to 1.0 which is the distance along this line from the
  15362. line's start to the point which is nearest to the point passed-in. To
  15363. turn this number into a position, use getPointAlongLineProportionally().
  15364. @see getDistanceFromPoint, getPointAlongLineProportionally
  15365. */
  15366. ValueType findNearestProportionalPositionTo (const Point<ValueType>& point) const throw()
  15367. {
  15368. const Point<ValueType> delta (end - start);
  15369. const double length = delta.getX() * delta.getX() + delta.getY() * delta.getY();
  15370. return length <= 0 ? 0
  15371. : jlimit ((ValueType) 0, (ValueType) 1,
  15372. (ValueType) (((point.getX() - start.getX()) * delta.getX()
  15373. + (point.getY() - start.getY()) * delta.getY()) / length));
  15374. }
  15375. /** Finds the point on this line which is nearest to a given point.
  15376. @see getDistanceFromPoint, findNearestProportionalPositionTo
  15377. */
  15378. const Point<ValueType> findNearestPointTo (const Point<ValueType>& point) const throw()
  15379. {
  15380. return getPointAlongLineProportionally (findNearestProportionalPositionTo (point));
  15381. }
  15382. /** Returns true if the given point lies above this line.
  15383. The return value is true if the point's y coordinate is less than the y
  15384. coordinate of this line at the given x (assuming the line extends infinitely
  15385. in both directions).
  15386. */
  15387. bool isPointAbove (const Point<ValueType>& point) const throw()
  15388. {
  15389. return start.getX() != end.getX()
  15390. && point.getY() < ((end.getY() - start.getY())
  15391. * (point.getX() - start.getX())) / (end.getX() - start.getX()) + start.getY();
  15392. }
  15393. /** Returns a shortened copy of this line.
  15394. This will chop off part of the start of this line by a certain amount, (leaving the
  15395. end-point the same), and return the new line.
  15396. */
  15397. const Line withShortenedStart (ValueType distanceToShortenBy) const throw()
  15398. {
  15399. return Line (getPointAlongLine (jmin (distanceToShortenBy, getLength())), end);
  15400. }
  15401. /** Returns a shortened copy of this line.
  15402. This will chop off part of the end of this line by a certain amount, (leaving the
  15403. start-point the same), and return the new line.
  15404. */
  15405. const Line withShortenedEnd (ValueType distanceToShortenBy) const throw()
  15406. {
  15407. const ValueType length = getLength();
  15408. return Line (start, getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  15409. }
  15410. juce_UseDebuggingNewOperator
  15411. private:
  15412. Point<ValueType> start, end;
  15413. static bool findIntersection (const Point<ValueType>& p1, const Point<ValueType>& p2,
  15414. const Point<ValueType>& p3, const Point<ValueType>& p4,
  15415. Point<ValueType>& intersection) throw()
  15416. {
  15417. if (p2 == p3)
  15418. {
  15419. intersection = p2;
  15420. return true;
  15421. }
  15422. const Point<ValueType> d1 (p2 - p1);
  15423. const Point<ValueType> d2 (p4 - p3);
  15424. const ValueType divisor = d1.getX() * d2.getY() - d2.getX() * d1.getY();
  15425. if (divisor == 0)
  15426. {
  15427. if (! (d1.isOrigin() || d2.isOrigin()))
  15428. {
  15429. if (d1.getY() == 0 && d2.getY() != 0)
  15430. {
  15431. const ValueType along = (p1.getY() - p3.getY()) / d2.getY();
  15432. intersection = p1.withX (p3.getX() + along * d2.getX());
  15433. return along >= 0 && along <= (ValueType) 1;
  15434. }
  15435. else if (d2.getY() == 0 && d1.getY() != 0)
  15436. {
  15437. const ValueType along = (p3.getY() - p1.getY()) / d1.getY();
  15438. intersection = p3.withX (p1.getX() + along * d1.getX());
  15439. return along >= 0 && along <= (ValueType) 1;
  15440. }
  15441. else if (d1.getX() == 0 && d2.getX() != 0)
  15442. {
  15443. const ValueType along = (p1.getX() - p3.getX()) / d2.getX();
  15444. intersection = p1.withY (p3.getY() + along * d2.getY());
  15445. return along >= 0 && along <= (ValueType) 1;
  15446. }
  15447. else if (d2.getX() == 0 && d1.getX() != 0)
  15448. {
  15449. const ValueType along = (p3.getX() - p1.getX()) / d1.getX();
  15450. intersection = p3.withY (p1.getY() + along * d1.getY());
  15451. return along >= 0 && along <= (ValueType) 1;
  15452. }
  15453. }
  15454. intersection = (p2 + p3) / (ValueType) 2;
  15455. return false;
  15456. }
  15457. const ValueType along1 = ((p1.getY() - p3.getY()) * d2.getX() - (p1.getX() - p3.getX()) * d2.getY()) / divisor;
  15458. intersection = p1 + d1 * along1;
  15459. if (along1 < 0 || along1 > (ValueType) 1)
  15460. return false;
  15461. const ValueType along2 = ((p1.getY() - p3.getY()) * d1.getX() - (p1.getX() - p3.getX()) * d1.getY()) / divisor;
  15462. return along2 >= 0 && along2 <= (ValueType) 1;
  15463. }
  15464. };
  15465. #endif // __JUCE_LINE_JUCEHEADER__
  15466. /*** End of inlined file: juce_Line.h ***/
  15467. /*** Start of inlined file: juce_Rectangle.h ***/
  15468. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  15469. #define __JUCE_RECTANGLE_JUCEHEADER__
  15470. class RectangleList;
  15471. /**
  15472. Manages a rectangle and allows geometric operations to be performed on it.
  15473. @see RectangleList, Path, Line, Point
  15474. */
  15475. template <typename ValueType>
  15476. class Rectangle
  15477. {
  15478. public:
  15479. /** Creates a rectangle of zero size.
  15480. The default co-ordinates will be (0, 0, 0, 0).
  15481. */
  15482. Rectangle() throw()
  15483. : x (0), y (0), w (0), h (0)
  15484. {
  15485. }
  15486. /** Creates a copy of another rectangle. */
  15487. Rectangle (const Rectangle& other) throw()
  15488. : x (other.x), y (other.y),
  15489. w (other.w), h (other.h)
  15490. {
  15491. }
  15492. /** Creates a rectangle with a given position and size. */
  15493. Rectangle (const ValueType initialX, const ValueType initialY,
  15494. const ValueType width, const ValueType height) throw()
  15495. : x (initialX), y (initialY),
  15496. w (width), h (height)
  15497. {
  15498. }
  15499. /** Creates a rectangle with a given size, and a position of (0, 0). */
  15500. Rectangle (const ValueType width, const ValueType height) throw()
  15501. : x (0), y (0), w (width), h (height)
  15502. {
  15503. }
  15504. /** Creates a Rectangle from the positions of two opposite corners. */
  15505. Rectangle (const Point<ValueType>& corner1, const Point<ValueType>& corner2) throw()
  15506. : x (jmin (corner1.getX(), corner2.getX())),
  15507. y (jmin (corner1.getY(), corner2.getY())),
  15508. w (corner1.getX() - corner2.getX()),
  15509. h (corner1.getY() - corner2.getY())
  15510. {
  15511. if (w < 0) w = -w;
  15512. if (h < 0) h = -h;
  15513. }
  15514. Rectangle& operator= (const Rectangle& other) throw()
  15515. {
  15516. x = other.x; y = other.y;
  15517. w = other.w; h = other.h;
  15518. return *this;
  15519. }
  15520. /** Destructor. */
  15521. ~Rectangle() throw() {}
  15522. /** Returns true if the rectangle's width and height are both zero or less */
  15523. bool isEmpty() const throw() { return w <= 0 || h <= 0; }
  15524. /** Returns the x co-ordinate of the rectangle's left-hand-side. */
  15525. inline ValueType getX() const throw() { return x; }
  15526. /** Returns the y co-ordinate of the rectangle's top edge. */
  15527. inline ValueType getY() const throw() { return y; }
  15528. /** Returns the width of the rectangle. */
  15529. inline ValueType getWidth() const throw() { return w; }
  15530. /** Returns the height of the rectangle. */
  15531. inline ValueType getHeight() const throw() { return h; }
  15532. /** Returns the x co-ordinate of the rectangle's right-hand-side. */
  15533. inline ValueType getRight() const throw() { return x + w; }
  15534. /** Returns the y co-ordinate of the rectangle's bottom edge. */
  15535. inline ValueType getBottom() const throw() { return y + h; }
  15536. /** Returns the x co-ordinate of the rectangle's centre. */
  15537. ValueType getCentreX() const throw() { return x + w / (ValueType) 2; }
  15538. /** Returns the y co-ordinate of the rectangle's centre. */
  15539. ValueType getCentreY() const throw() { return y + h / (ValueType) 2; }
  15540. /** Returns the centre point of the rectangle. */
  15541. const Point<ValueType> getCentre() const throw() { return Point<ValueType> (x + w / (ValueType) 2, y + h / (ValueType) 2); }
  15542. /** Returns the aspect ratio of the rectangle's width / height.
  15543. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  15544. it returns height / width. */
  15545. ValueType getAspectRatio (const bool widthOverHeight = true) const throw() { return widthOverHeight ? w / h : h / w; }
  15546. /** Returns the rectangle's top-left position as a Point. */
  15547. const Point<ValueType> getPosition() const throw() { return Point<ValueType> (x, y); }
  15548. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15549. void setPosition (const Point<ValueType>& newPos) throw() { x = newPos.getX(); y = newPos.getY(); }
  15550. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  15551. void setPosition (const ValueType newX, const ValueType newY) throw() { x = newX; y = newY; }
  15552. /** Returns a rectangle with the same size as this one, but a new position. */
  15553. const Rectangle withPosition (const Point<ValueType>& newPos) const throw() { return Rectangle (newPos.getX(), newPos.getY(), w, h); }
  15554. /** Returns the rectangle's top-left position as a Point. */
  15555. const Point<ValueType> getTopLeft() const throw() { return getPosition(); }
  15556. /** Returns the rectangle's top-right position as a Point. */
  15557. const Point<ValueType> getTopRight() const throw() { return Point<ValueType> (x + w, y); }
  15558. /** Returns the rectangle's bottom-left position as a Point. */
  15559. const Point<ValueType> getBottomLeft() const throw() { return Point<ValueType> (x, y + h); }
  15560. /** Returns the rectangle's bottom-right position as a Point. */
  15561. const Point<ValueType> getBottomRight() const throw() { return Point<ValueType> (x + w, y + h); }
  15562. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  15563. void setSize (const ValueType newWidth, const ValueType newHeight) throw() { w = newWidth; h = newHeight; }
  15564. /** Returns a rectangle with the same position as this one, but a new size. */
  15565. const Rectangle withSize (const ValueType newWidth, const ValueType newHeight) const throw() { return Rectangle (x, y, newWidth, newHeight); }
  15566. /** Changes all the rectangle's co-ordinates. */
  15567. void setBounds (const ValueType newX, const ValueType newY,
  15568. const ValueType newWidth, const ValueType newHeight) throw()
  15569. {
  15570. x = newX; y = newY; w = newWidth; h = newHeight;
  15571. }
  15572. /** Changes the rectangle's width */
  15573. void setWidth (const ValueType newWidth) throw() { w = newWidth; }
  15574. /** Changes the rectangle's height */
  15575. void setHeight (const ValueType newHeight) throw() { h = newHeight; }
  15576. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  15577. const Rectangle withX (const ValueType newX) const throw() { return Rectangle (newX, y, w, h); }
  15578. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  15579. const Rectangle withY (const ValueType newY) const throw() { return Rectangle (x, newY, w, h); }
  15580. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  15581. const Rectangle withWidth (const ValueType newWidth) const throw() { return Rectangle (x, y, newWidth, h); }
  15582. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  15583. const Rectangle withHeight (const ValueType newHeight) const throw() { return Rectangle (x, y, w, newHeight); }
  15584. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  15585. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  15586. */
  15587. void setLeft (const ValueType newLeft) throw()
  15588. {
  15589. w = jmax (ValueType(), x + w - newLeft);
  15590. x = newLeft;
  15591. }
  15592. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  15593. If the y is moved to be below the current bottom edge, the height will be set to zero.
  15594. */
  15595. void setTop (const ValueType newTop) throw()
  15596. {
  15597. h = jmax (ValueType(), y + h - newTop);
  15598. y = newTop;
  15599. }
  15600. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  15601. If the new right is below the current X value, the X will be pushed down to match it.
  15602. @see getRight
  15603. */
  15604. void setRight (const ValueType newRight) throw()
  15605. {
  15606. x = jmin (x, newRight);
  15607. w = newRight - x;
  15608. }
  15609. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  15610. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  15611. @see getBottom
  15612. */
  15613. void setBottom (const ValueType newBottom) throw()
  15614. {
  15615. y = jmin (y, newBottom);
  15616. h = newBottom - y;
  15617. }
  15618. /** Moves the rectangle's position by adding amount to its x and y co-ordinates. */
  15619. void translate (const ValueType deltaX,
  15620. const ValueType deltaY) throw()
  15621. {
  15622. x += deltaX;
  15623. y += deltaY;
  15624. }
  15625. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15626. const Rectangle translated (const ValueType deltaX,
  15627. const ValueType deltaY) const throw()
  15628. {
  15629. return Rectangle (x + deltaX, y + deltaY, w, h);
  15630. }
  15631. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15632. const Rectangle operator+ (const Point<ValueType>& deltaPosition) const throw()
  15633. {
  15634. return Rectangle (x + deltaPosition.getX(), y + deltaPosition.getY(), w, h);
  15635. }
  15636. /** Moves this rectangle by a given amount. */
  15637. Rectangle& operator+= (const Point<ValueType>& deltaPosition) throw()
  15638. {
  15639. x += deltaPosition.getX(); y += deltaPosition.getY();
  15640. return *this;
  15641. }
  15642. /** Returns a rectangle which is the same as this one moved by a given amount. */
  15643. const Rectangle operator- (const Point<ValueType>& deltaPosition) const throw()
  15644. {
  15645. return Rectangle (x - deltaPosition.getX(), y - deltaPosition.getY(), w, h);
  15646. }
  15647. /** Moves this rectangle by a given amount. */
  15648. Rectangle& operator-= (const Point<ValueType>& deltaPosition) throw()
  15649. {
  15650. x -= deltaPosition.getX(); y -= deltaPosition.getY();
  15651. return *this;
  15652. }
  15653. /** Expands the rectangle by a given amount.
  15654. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15655. @see expanded, reduce, reduced
  15656. */
  15657. void expand (const ValueType deltaX,
  15658. const ValueType deltaY) throw()
  15659. {
  15660. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15661. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15662. setBounds (x - deltaX, y - deltaY, nw, nh);
  15663. }
  15664. /** Returns a rectangle that is larger than this one by a given amount.
  15665. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  15666. @see expand, reduce, reduced
  15667. */
  15668. const Rectangle expanded (const ValueType deltaX,
  15669. const ValueType deltaY) const throw()
  15670. {
  15671. const ValueType nw = jmax (ValueType(), w + deltaX * 2);
  15672. const ValueType nh = jmax (ValueType(), h + deltaY * 2);
  15673. return Rectangle (x - deltaX, y - deltaY, nw, nh);
  15674. }
  15675. /** Shrinks the rectangle by a given amount.
  15676. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15677. @see reduced, expand, expanded
  15678. */
  15679. void reduce (const ValueType deltaX,
  15680. const ValueType deltaY) throw()
  15681. {
  15682. expand (-deltaX, -deltaY);
  15683. }
  15684. /** Returns a rectangle that is smaller than this one by a given amount.
  15685. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  15686. @see reduce, expand, expanded
  15687. */
  15688. const Rectangle reduced (const ValueType deltaX,
  15689. const ValueType deltaY) const throw()
  15690. {
  15691. return expanded (-deltaX, -deltaY);
  15692. }
  15693. /** Removes a strip from the top of this rectangle, reducing this rectangle
  15694. by the specified amount and returning the section that was removed.
  15695. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15696. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  15697. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  15698. that value.
  15699. */
  15700. const Rectangle removeFromTop (const ValueType amountToRemove) throw()
  15701. {
  15702. const Rectangle r (x, y, w, jmin (amountToRemove, h));
  15703. y += r.h; h -= r.h;
  15704. return r;
  15705. }
  15706. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  15707. by the specified amount and returning the section that was removed.
  15708. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15709. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  15710. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  15711. that value.
  15712. */
  15713. const Rectangle removeFromLeft (const ValueType amountToRemove) throw()
  15714. {
  15715. const Rectangle r (x, y, jmin (amountToRemove, w), h);
  15716. x += r.w; w -= r.w;
  15717. return r;
  15718. }
  15719. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  15720. by the specified amount and returning the section that was removed.
  15721. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15722. return (250, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  15723. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  15724. that value.
  15725. */
  15726. const Rectangle removeFromRight (ValueType amountToRemove) throw()
  15727. {
  15728. amountToRemove = jmin (amountToRemove, w);
  15729. const Rectangle r (x + w - amountToRemove, y, amountToRemove, h);
  15730. w -= amountToRemove;
  15731. return r;
  15732. }
  15733. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  15734. by the specified amount and returning the section that was removed.
  15735. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  15736. return (100, 250, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  15737. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  15738. that value.
  15739. */
  15740. const Rectangle removeFromBottom (ValueType amountToRemove) throw()
  15741. {
  15742. amountToRemove = jmin (amountToRemove, h);
  15743. const Rectangle r (x, y + h - amountToRemove, w, amountToRemove);
  15744. h -= amountToRemove;
  15745. return r;
  15746. }
  15747. /** Returns true if the two rectangles are identical. */
  15748. bool operator== (const Rectangle& other) const throw()
  15749. {
  15750. return x == other.x && y == other.y
  15751. && w == other.w && h == other.h;
  15752. }
  15753. /** Returns true if the two rectangles are not identical. */
  15754. bool operator!= (const Rectangle& other) const throw()
  15755. {
  15756. return x != other.x || y != other.y
  15757. || w != other.w || h != other.h;
  15758. }
  15759. /** Returns true if this co-ordinate is inside the rectangle. */
  15760. bool contains (const ValueType xCoord, const ValueType yCoord) const throw()
  15761. {
  15762. return xCoord >= x && yCoord >= y && xCoord < x + w && yCoord < y + h;
  15763. }
  15764. /** Returns true if this co-ordinate is inside the rectangle. */
  15765. bool contains (const Point<ValueType>& point) const throw()
  15766. {
  15767. return point.getX() >= x && point.getY() >= y && point.getX() < x + w && point.getY() < y + h;
  15768. }
  15769. /** Returns true if this other rectangle is completely inside this one. */
  15770. bool contains (const Rectangle& other) const throw()
  15771. {
  15772. return x <= other.x && y <= other.y
  15773. && x + w >= other.x + other.w && y + h >= other.y + other.h;
  15774. }
  15775. /** Returns the nearest point to the specified point that lies within this rectangle. */
  15776. const Point<ValueType> getConstrainedPoint (const Point<ValueType>& point) const throw()
  15777. {
  15778. return Point<ValueType> (jlimit (x, x + w, point.getX()),
  15779. jlimit (y, y + h, point.getY()));
  15780. }
  15781. /** Returns true if any part of another rectangle overlaps this one. */
  15782. bool intersects (const Rectangle& other) const throw()
  15783. {
  15784. return x + w > other.x
  15785. && y + h > other.y
  15786. && x < other.x + other.w
  15787. && y < other.y + other.h
  15788. && w > ValueType() && h > ValueType();
  15789. }
  15790. /** Returns the region that is the overlap between this and another rectangle.
  15791. If the two rectangles don't overlap, the rectangle returned will be empty.
  15792. */
  15793. const Rectangle getIntersection (const Rectangle& other) const throw()
  15794. {
  15795. const ValueType nx = jmax (x, other.x);
  15796. const ValueType ny = jmax (y, other.y);
  15797. const ValueType nw = jmin (x + w, other.x + other.w) - nx;
  15798. const ValueType nh = jmin (y + h, other.y + other.h) - ny;
  15799. if (nw >= ValueType() && nh >= ValueType())
  15800. return Rectangle (nx, ny, nw, nh);
  15801. return Rectangle();
  15802. }
  15803. /** Clips a rectangle so that it lies only within this one.
  15804. This is a non-static version of intersectRectangles().
  15805. Returns false if the two regions didn't overlap.
  15806. */
  15807. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const throw()
  15808. {
  15809. const int maxX = jmax (otherX, x);
  15810. otherW = jmin (otherX + otherW, x + w) - maxX;
  15811. if (otherW > 0)
  15812. {
  15813. const int maxY = jmax (otherY, y);
  15814. otherH = jmin (otherY + otherH, y + h) - maxY;
  15815. if (otherH > 0)
  15816. {
  15817. otherX = maxX; otherY = maxY;
  15818. return true;
  15819. }
  15820. }
  15821. return false;
  15822. }
  15823. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  15824. If either this or the other rectangle are empty, they will not be counted as
  15825. part of the resulting region.
  15826. */
  15827. const Rectangle getUnion (const Rectangle& other) const throw()
  15828. {
  15829. if (other.isEmpty()) return *this;
  15830. if (isEmpty()) return other;
  15831. const ValueType newX = jmin (x, other.x);
  15832. const ValueType newY = jmin (y, other.y);
  15833. return Rectangle (newX, newY,
  15834. jmax (x + w, other.x + other.w) - newX,
  15835. jmax (y + h, other.y + other.h) - newY);
  15836. }
  15837. /** If this rectangle merged with another one results in a simple rectangle, this
  15838. will set this rectangle to the result, and return true.
  15839. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15840. or if they form a complex region.
  15841. */
  15842. bool enlargeIfAdjacent (const Rectangle& other) throw()
  15843. {
  15844. if (x == other.x && getRight() == other.getRight()
  15845. && (other.getBottom() >= y && other.y <= getBottom()))
  15846. {
  15847. const ValueType newY = jmin (y, other.y);
  15848. h = jmax (getBottom(), other.getBottom()) - newY;
  15849. y = newY;
  15850. return true;
  15851. }
  15852. else if (y == other.y && getBottom() == other.getBottom()
  15853. && (other.getRight() >= x && other.x <= getRight()))
  15854. {
  15855. const ValueType newX = jmin (x, other.x);
  15856. w = jmax (getRight(), other.getRight()) - newX;
  15857. x = newX;
  15858. return true;
  15859. }
  15860. return false;
  15861. }
  15862. /** If after removing another rectangle from this one the result is a simple rectangle,
  15863. this will set this object's bounds to be the result, and return true.
  15864. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  15865. or if removing the other one would form a complex region.
  15866. */
  15867. bool reduceIfPartlyContainedIn (const Rectangle& other) throw()
  15868. {
  15869. int inside = 0;
  15870. const int otherR = other.getRight();
  15871. if (x >= other.x && x < otherR) inside = 1;
  15872. const int otherB = other.getBottom();
  15873. if (y >= other.y && y < otherB) inside |= 2;
  15874. const int r = x + w;
  15875. if (r >= other.x && r < otherR) inside |= 4;
  15876. const int b = y + h;
  15877. if (b >= other.y && b < otherB) inside |= 8;
  15878. switch (inside)
  15879. {
  15880. case 1 + 2 + 8: w = r - otherR; x = otherR; return true;
  15881. case 1 + 2 + 4: h = b - otherB; y = otherB; return true;
  15882. case 2 + 4 + 8: w = other.x - x; return true;
  15883. case 1 + 4 + 8: h = other.y - y; return true;
  15884. }
  15885. return false;
  15886. }
  15887. /** Returns the smallest rectangle that can contain the shape created by applying
  15888. a transform to this rectangle.
  15889. This should only be used on floating point rectangles.
  15890. */
  15891. const Rectangle<ValueType> transformed (const AffineTransform& transform) const throw()
  15892. {
  15893. float x1 = x, y1 = y;
  15894. float x2 = x + w, y2 = y;
  15895. float x3 = x, y3 = y + h;
  15896. float x4 = x2, y4 = y3;
  15897. transform.transformPoints (x1, y1, x2, y2);
  15898. transform.transformPoints (x3, y3, x4, y4);
  15899. const float rx = jmin (x1, x2, x3, x4);
  15900. const float ry = jmin (y1, y2, y3, y4);
  15901. return Rectangle (rx, ry,
  15902. jmax (x1, x2, x3, x4) - rx,
  15903. jmax (y1, y2, y3, y4) - ry);
  15904. }
  15905. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  15906. This is only relevent for floating-point rectangles, of course.
  15907. @see toFloat()
  15908. */
  15909. const Rectangle<int> getSmallestIntegerContainer() const throw()
  15910. {
  15911. const int x1 = (int) std::floor (static_cast<float> (x));
  15912. const int y1 = (int) std::floor (static_cast<float> (y));
  15913. const int x2 = (int) std::floor (static_cast<float> (x + w + 0.9999f));
  15914. const int y2 = (int) std::floor (static_cast<float> (y + h + 0.9999f));
  15915. return Rectangle<int> (x1, y1, x2 - x1, y2 - y1);
  15916. }
  15917. /** Returns the smallest Rectangle that can contain a set of points. */
  15918. static const Rectangle findAreaContainingPoints (const Point<ValueType>* const points, const int numPoints) throw()
  15919. {
  15920. if (numPoints == 0)
  15921. return Rectangle();
  15922. ValueType minX (points[0].getX());
  15923. ValueType maxX (minX);
  15924. ValueType minY (points[0].getY());
  15925. ValueType maxY (minY);
  15926. for (int i = 1; i < numPoints; ++i)
  15927. {
  15928. minX = jmin (minX, points[i].getX());
  15929. maxX = jmax (maxX, points[i].getX());
  15930. minY = jmin (minY, points[i].getY());
  15931. maxY = jmax (maxY, points[i].getY());
  15932. }
  15933. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  15934. }
  15935. /** Casts this rectangle to a Rectangle<float>.
  15936. Obviously this is mainly useful for rectangles that use integer types.
  15937. @see getSmallestIntegerContainer
  15938. */
  15939. const Rectangle<float> toFloat() const throw()
  15940. {
  15941. return Rectangle<float> (static_cast<float> (x), static_cast<float> (y),
  15942. static_cast<float> (w), static_cast<float> (h));
  15943. }
  15944. /** Static utility to intersect two sets of rectangular co-ordinates.
  15945. Returns false if the two regions didn't overlap.
  15946. @see intersectRectangle
  15947. */
  15948. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  15949. const ValueType x2, const ValueType y2, const ValueType w2, const ValueType h2) throw()
  15950. {
  15951. const ValueType x = jmax (x1, x2);
  15952. w1 = jmin (x1 + w1, x2 + w2) - x;
  15953. if (w1 > 0)
  15954. {
  15955. const ValueType y = jmax (y1, y2);
  15956. h1 = jmin (y1 + h1, y2 + h2) - y;
  15957. if (h1 > 0)
  15958. {
  15959. x1 = x; y1 = y;
  15960. return true;
  15961. }
  15962. }
  15963. return false;
  15964. }
  15965. /** Creates a string describing this rectangle.
  15966. The string will be of the form "x y width height", e.g. "100 100 400 200".
  15967. Coupled with the fromString() method, this is very handy for things like
  15968. storing rectangles (particularly component positions) in XML attributes.
  15969. @see fromString
  15970. */
  15971. const String toString() const
  15972. {
  15973. String s;
  15974. s.preallocateStorage (16);
  15975. s << x << ' ' << y << ' ' << w << ' ' << h;
  15976. return s;
  15977. }
  15978. /** Parses a string containing a rectangle's details.
  15979. The string should contain 4 integer tokens, in the form "x y width height". They
  15980. can be comma or whitespace separated.
  15981. This method is intended to go with the toString() method, to form an easy way
  15982. of saving/loading rectangles as strings.
  15983. @see toString
  15984. */
  15985. static const Rectangle fromString (const String& stringVersion)
  15986. {
  15987. StringArray toks;
  15988. toks.addTokens (stringVersion.trim(), ",; \t\r\n", String::empty);
  15989. return Rectangle (toks[0].trim().getIntValue(),
  15990. toks[1].trim().getIntValue(),
  15991. toks[2].trim().getIntValue(),
  15992. toks[3].trim().getIntValue());
  15993. }
  15994. juce_UseDebuggingNewOperator
  15995. private:
  15996. friend class RectangleList;
  15997. ValueType x, y, w, h;
  15998. };
  15999. #endif // __JUCE_RECTANGLE_JUCEHEADER__
  16000. /*** End of inlined file: juce_Rectangle.h ***/
  16001. /*** Start of inlined file: juce_Justification.h ***/
  16002. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  16003. #define __JUCE_JUSTIFICATION_JUCEHEADER__
  16004. /**
  16005. Represents a type of justification to be used when positioning graphical items.
  16006. e.g. it indicates whether something should be placed top-left, top-right,
  16007. centred, etc.
  16008. It is used in various places wherever this kind of information is needed.
  16009. */
  16010. class JUCE_API Justification
  16011. {
  16012. public:
  16013. /** Creates a Justification object using a combination of flags. */
  16014. inline Justification (int flags_) throw() : flags (flags_) {}
  16015. /** Creates a copy of another Justification object. */
  16016. Justification (const Justification& other) throw();
  16017. /** Copies another Justification object. */
  16018. Justification& operator= (const Justification& other) throw();
  16019. bool operator== (const Justification& other) const throw() { return flags == other.flags; }
  16020. bool operator!= (const Justification& other) const throw() { return flags != other.flags; }
  16021. /** Returns the raw flags that are set for this Justification object. */
  16022. inline int getFlags() const throw() { return flags; }
  16023. /** Tests a set of flags for this object.
  16024. @returns true if any of the flags passed in are set on this object.
  16025. */
  16026. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  16027. /** Returns just the flags from this object that deal with vertical layout. */
  16028. int getOnlyVerticalFlags() const throw();
  16029. /** Returns just the flags from this object that deal with horizontal layout. */
  16030. int getOnlyHorizontalFlags() const throw();
  16031. /** Adjusts the position of a rectangle to fit it into a space.
  16032. The (x, y) position of the rectangle will be updated to position it inside the
  16033. given space according to the justification flags.
  16034. */
  16035. void applyToRectangle (int& x, int& y, int w, int h,
  16036. int spaceX, int spaceY, int spaceW, int spaceH) const throw();
  16037. /** Flag values that can be combined and used in the constructor. */
  16038. enum
  16039. {
  16040. /** Indicates that the item should be aligned against the left edge of the available space. */
  16041. left = 1,
  16042. /** Indicates that the item should be aligned against the right edge of the available space. */
  16043. right = 2,
  16044. /** Indicates that the item should be placed in the centre between the left and right
  16045. sides of the available space. */
  16046. horizontallyCentred = 4,
  16047. /** Indicates that the item should be aligned against the top edge of the available space. */
  16048. top = 8,
  16049. /** Indicates that the item should be aligned against the bottom edge of the available space. */
  16050. bottom = 16,
  16051. /** Indicates that the item should be placed in the centre between the top and bottom
  16052. sides of the available space. */
  16053. verticallyCentred = 32,
  16054. /** Indicates that lines of text should be spread out to fill the maximum width
  16055. available, so that both margins are aligned vertically.
  16056. */
  16057. horizontallyJustified = 64,
  16058. /** Indicates that the item should be centred vertically and horizontally.
  16059. This is equivalent to (horizontallyCentred | verticallyCentred)
  16060. */
  16061. centred = 36,
  16062. /** Indicates that the item should be centred vertically but placed on the left hand side.
  16063. This is equivalent to (left | verticallyCentred)
  16064. */
  16065. centredLeft = 33,
  16066. /** Indicates that the item should be centred vertically but placed on the right hand side.
  16067. This is equivalent to (right | verticallyCentred)
  16068. */
  16069. centredRight = 34,
  16070. /** Indicates that the item should be centred horizontally and placed at the top.
  16071. This is equivalent to (horizontallyCentred | top)
  16072. */
  16073. centredTop = 12,
  16074. /** Indicates that the item should be centred horizontally and placed at the bottom.
  16075. This is equivalent to (horizontallyCentred | bottom)
  16076. */
  16077. centredBottom = 20,
  16078. /** Indicates that the item should be placed in the top-left corner.
  16079. This is equivalent to (left | top)
  16080. */
  16081. topLeft = 9,
  16082. /** Indicates that the item should be placed in the top-right corner.
  16083. This is equivalent to (right | top)
  16084. */
  16085. topRight = 10,
  16086. /** Indicates that the item should be placed in the bottom-left corner.
  16087. This is equivalent to (left | bottom)
  16088. */
  16089. bottomLeft = 17,
  16090. /** Indicates that the item should be placed in the bottom-left corner.
  16091. This is equivalent to (right | bottom)
  16092. */
  16093. bottomRight = 18
  16094. };
  16095. private:
  16096. int flags;
  16097. };
  16098. #endif // __JUCE_JUSTIFICATION_JUCEHEADER__
  16099. /*** End of inlined file: juce_Justification.h ***/
  16100. class Image;
  16101. /**
  16102. A path is a sequence of lines and curves that may either form a closed shape
  16103. or be open-ended.
  16104. To use a path, you can create an empty one, then add lines and curves to it
  16105. to create shapes, then it can be rendered by a Graphics context or used
  16106. for geometric operations.
  16107. e.g. @code
  16108. Path myPath;
  16109. myPath.startNewSubPath (10.0f, 10.0f); // move the current position to (10, 10)
  16110. myPath.lineTo (100.0f, 200.0f); // draw a line from here to (100, 200)
  16111. myPath.quadraticTo (0.0f, 150.0f, 5.0f, 50.0f); // draw a curve that ends at (5, 50)
  16112. myPath.closeSubPath(); // close the subpath with a line back to (10, 10)
  16113. // add an ellipse as well, which will form a second sub-path within the path..
  16114. myPath.addEllipse (50.0f, 50.0f, 40.0f, 30.0f);
  16115. // double the width of the whole thing..
  16116. myPath.applyTransform (AffineTransform::scale (2.0f, 1.0f));
  16117. // and draw it to a graphics context with a 5-pixel thick outline.
  16118. g.strokePath (myPath, PathStrokeType (5.0f));
  16119. @endcode
  16120. A path object can actually contain multiple sub-paths, which may themselves
  16121. be open or closed.
  16122. @see PathFlatteningIterator, PathStrokeType, Graphics
  16123. */
  16124. class JUCE_API Path
  16125. {
  16126. public:
  16127. /** Creates an empty path. */
  16128. Path();
  16129. /** Creates a copy of another path. */
  16130. Path (const Path& other);
  16131. /** Destructor. */
  16132. ~Path();
  16133. /** Copies this path from another one. */
  16134. Path& operator= (const Path& other);
  16135. bool operator== (const Path& other) const throw();
  16136. bool operator!= (const Path& other) const throw();
  16137. /** Returns true if the path doesn't contain any lines or curves. */
  16138. bool isEmpty() const throw();
  16139. /** Returns the smallest rectangle that contains all points within the path.
  16140. */
  16141. const Rectangle<float> getBounds() const throw();
  16142. /** Returns the smallest rectangle that contains all points within the path
  16143. after it's been transformed with the given tranasform matrix.
  16144. */
  16145. const Rectangle<float> getBoundsTransformed (const AffineTransform& transform) const throw();
  16146. /** Checks whether a point lies within the path.
  16147. This is only relevent for closed paths (see closeSubPath()), and
  16148. may produce false results if used on a path which has open sub-paths.
  16149. The path's winding rule is taken into account by this method.
  16150. The tolerence parameter is passed to the PathFlatteningIterator that
  16151. is used to trace the path - for more info about it, see the notes for
  16152. the PathFlatteningIterator constructor.
  16153. @see closeSubPath, setUsingNonZeroWinding
  16154. */
  16155. bool contains (float x, float y,
  16156. float tolerence = 10.0f) const;
  16157. /** Checks whether a point lies within the path.
  16158. This is only relevent for closed paths (see closeSubPath()), and
  16159. may produce false results if used on a path which has open sub-paths.
  16160. The path's winding rule is taken into account by this method.
  16161. The tolerence parameter is passed to the PathFlatteningIterator that
  16162. is used to trace the path - for more info about it, see the notes for
  16163. the PathFlatteningIterator constructor.
  16164. @see closeSubPath, setUsingNonZeroWinding
  16165. */
  16166. bool contains (const Point<float>& point,
  16167. float tolerence = 10.0f) const;
  16168. /** Checks whether a line crosses the path.
  16169. This will return positive if the line crosses any of the paths constituent
  16170. lines or curves. It doesn't take into account whether the line is inside
  16171. or outside the path, or whether the path is open or closed.
  16172. The tolerence parameter is passed to the PathFlatteningIterator that
  16173. is used to trace the path - for more info about it, see the notes for
  16174. the PathFlatteningIterator constructor.
  16175. */
  16176. bool intersectsLine (const Line<float>& line,
  16177. float tolerence = 10.0f);
  16178. /** Cuts off parts of a line to keep the parts that are either inside or
  16179. outside this path.
  16180. Note that this isn't smart enough to cope with situations where the
  16181. line would need to be cut into multiple pieces to correctly clip against
  16182. a re-entrant shape.
  16183. @param line the line to clip
  16184. @param keepSectionOutsidePath if true, it's the section outside the path
  16185. that will be kept; if false its the section inside
  16186. the path
  16187. */
  16188. const Line<float> getClippedLine (const Line<float>& line, bool keepSectionOutsidePath) const;
  16189. /** Returns the length of the path.
  16190. @see getPointAlongPath
  16191. */
  16192. float getLength (const AffineTransform& transform = AffineTransform::identity) const;
  16193. /** Returns a point that is the specified distance along the path.
  16194. If the distance is greater than the total length of the path, this will return the
  16195. end point.
  16196. @see getLength
  16197. */
  16198. const Point<float> getPointAlongPath (float distanceFromStart,
  16199. const AffineTransform& transform = AffineTransform::identity) const;
  16200. /** Finds the point along the path which is nearest to a given position.
  16201. This sets pointOnPath to the nearest point, and returns the distance of this point from the start
  16202. of the path.
  16203. */
  16204. float getNearestPoint (const Point<float>& targetPoint,
  16205. Point<float>& pointOnPath,
  16206. const AffineTransform& transform = AffineTransform::identity) const;
  16207. /** Removes all lines and curves, resetting the path completely. */
  16208. void clear() throw();
  16209. /** Begins a new subpath with a given starting position.
  16210. This will move the path's current position to the co-ordinates passed in and
  16211. make it ready to draw lines or curves starting from this position.
  16212. After adding whatever lines and curves are needed, you can either
  16213. close the current sub-path using closeSubPath() or call startNewSubPath()
  16214. to move to a new sub-path, leaving the old one open-ended.
  16215. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16216. */
  16217. void startNewSubPath (float startX, float startY);
  16218. /** Begins a new subpath with a given starting position.
  16219. This will move the path's current position to the co-ordinates passed in and
  16220. make it ready to draw lines or curves starting from this position.
  16221. After adding whatever lines and curves are needed, you can either
  16222. close the current sub-path using closeSubPath() or call startNewSubPath()
  16223. to move to a new sub-path, leaving the old one open-ended.
  16224. @see lineTo, quadraticTo, cubicTo, closeSubPath
  16225. */
  16226. void startNewSubPath (const Point<float>& start);
  16227. /** Closes a the current sub-path with a line back to its start-point.
  16228. When creating a closed shape such as a triangle, don't use 3 lineTo()
  16229. calls - instead use two lineTo() calls, followed by a closeSubPath()
  16230. to join the final point back to the start.
  16231. This ensures that closes shapes are recognised as such, and this is
  16232. important for tasks like drawing strokes, which needs to know whether to
  16233. draw end-caps or not.
  16234. @see startNewSubPath, lineTo, quadraticTo, cubicTo, closeSubPath
  16235. */
  16236. void closeSubPath();
  16237. /** Adds a line from the shape's last position to a new end-point.
  16238. This will connect the end-point of the last line or curve that was added
  16239. to a new point, using a straight line.
  16240. See the class description for an example of how to add lines and curves to a path.
  16241. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16242. */
  16243. void lineTo (float endX, float endY);
  16244. /** Adds a line from the shape's last position to a new end-point.
  16245. This will connect the end-point of the last line or curve that was added
  16246. to a new point, using a straight line.
  16247. See the class description for an example of how to add lines and curves to a path.
  16248. @see startNewSubPath, quadraticTo, cubicTo, closeSubPath
  16249. */
  16250. void lineTo (const Point<float>& end);
  16251. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16252. This will connect the end-point of the last line or curve that was added
  16253. to a new point, using a quadratic spline with one control-point.
  16254. See the class description for an example of how to add lines and curves to a path.
  16255. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16256. */
  16257. void quadraticTo (float controlPointX,
  16258. float controlPointY,
  16259. float endPointX,
  16260. float endPointY);
  16261. /** Adds a quadratic bezier curve from the shape's last position to a new position.
  16262. This will connect the end-point of the last line or curve that was added
  16263. to a new point, using a quadratic spline with one control-point.
  16264. See the class description for an example of how to add lines and curves to a path.
  16265. @see startNewSubPath, lineTo, cubicTo, closeSubPath
  16266. */
  16267. void quadraticTo (const Point<float>& controlPoint,
  16268. const Point<float>& endPoint);
  16269. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16270. This will connect the end-point of the last line or curve that was added
  16271. to a new point, using a cubic spline with two control-points.
  16272. See the class description for an example of how to add lines and curves to a path.
  16273. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16274. */
  16275. void cubicTo (float controlPoint1X,
  16276. float controlPoint1Y,
  16277. float controlPoint2X,
  16278. float controlPoint2Y,
  16279. float endPointX,
  16280. float endPointY);
  16281. /** Adds a cubic bezier curve from the shape's last position to a new position.
  16282. This will connect the end-point of the last line or curve that was added
  16283. to a new point, using a cubic spline with two control-points.
  16284. See the class description for an example of how to add lines and curves to a path.
  16285. @see startNewSubPath, lineTo, quadraticTo, closeSubPath
  16286. */
  16287. void cubicTo (const Point<float>& controlPoint1,
  16288. const Point<float>& controlPoint2,
  16289. const Point<float>& endPoint);
  16290. /** Returns the last point that was added to the path by one of the drawing methods.
  16291. */
  16292. const Point<float> getCurrentPosition() const;
  16293. /** Adds a rectangle to the path.
  16294. The rectangle is added as a new sub-path. (Any currently open paths will be
  16295. left open).
  16296. @see addRoundedRectangle, addTriangle
  16297. */
  16298. void addRectangle (float x, float y, float width, float height);
  16299. /** Adds a rectangle to the path.
  16300. The rectangle is added as a new sub-path. (Any currently open paths will be
  16301. left open).
  16302. @see addRoundedRectangle, addTriangle
  16303. */
  16304. void addRectangle (const Rectangle<int>& rectangle);
  16305. /** Adds a rectangle with rounded corners to the path.
  16306. The rectangle is added as a new sub-path. (Any currently open paths will be
  16307. left open).
  16308. @see addRectangle, addTriangle
  16309. */
  16310. void addRoundedRectangle (float x, float y, float width, float height,
  16311. float cornerSize);
  16312. /** Adds a rectangle with rounded corners to the path.
  16313. The rectangle is added as a new sub-path. (Any currently open paths will be
  16314. left open).
  16315. @see addRectangle, addTriangle
  16316. */
  16317. void addRoundedRectangle (float x, float y, float width, float height,
  16318. float cornerSizeX,
  16319. float cornerSizeY);
  16320. /** Adds a triangle to the path.
  16321. The triangle is added as a new closed sub-path. (Any currently open paths will be
  16322. left open).
  16323. Note that whether the vertices are specified in clockwise or anticlockwise
  16324. order will affect how the triangle is filled when it overlaps other
  16325. shapes (the winding order setting will affect this of course).
  16326. */
  16327. void addTriangle (float x1, float y1,
  16328. float x2, float y2,
  16329. float x3, float y3);
  16330. /** Adds a quadrilateral to the path.
  16331. The quad is added as a new closed sub-path. (Any currently open paths will be
  16332. left open).
  16333. Note that whether the vertices are specified in clockwise or anticlockwise
  16334. order will affect how the quad is filled when it overlaps other
  16335. shapes (the winding order setting will affect this of course).
  16336. */
  16337. void addQuadrilateral (float x1, float y1,
  16338. float x2, float y2,
  16339. float x3, float y3,
  16340. float x4, float y4);
  16341. /** Adds an ellipse to the path.
  16342. The shape is added as a new sub-path. (Any currently open paths will be
  16343. left open).
  16344. @see addArc
  16345. */
  16346. void addEllipse (float x, float y, float width, float height);
  16347. /** Adds an elliptical arc to the current path.
  16348. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16349. or anti-clockwise according to whether the end angle is greater than the start. This means
  16350. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16351. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16352. @param y the top edge of the rectangle in which the elliptical outline fits
  16353. @param width the width of the rectangle in which the elliptical outline fits
  16354. @param height the height of the rectangle in which the elliptical outline fits
  16355. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16356. top-centre of the ellipse)
  16357. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16358. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16359. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16360. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16361. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16362. it will be added to the current sub-path, continuing from the current postition
  16363. @see addCentredArc, arcTo, addPieSegment, addEllipse
  16364. */
  16365. void addArc (float x, float y, float width, float height,
  16366. float fromRadians,
  16367. float toRadians,
  16368. bool startAsNewSubPath = false);
  16369. /** Adds an arc which is centred at a given point, and can have a rotation specified.
  16370. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16371. or anti-clockwise according to whether the end angle is greater than the start. This means
  16372. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16373. @param centreX the centre x of the ellipse
  16374. @param centreY the centre y of the ellipse
  16375. @param radiusX the horizontal radius of the ellipse
  16376. @param radiusY the vertical radius of the ellipse
  16377. @param rotationOfEllipse an angle by which the whole ellipse should be rotated about its centre, in radians (clockwise)
  16378. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16379. top-centre of the ellipse)
  16380. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16381. top-centre of the ellipse). This angle can be greater than 2*Pi, so for example to
  16382. draw a curve clockwise from the 9 o'clock position to the 3 o'clock position via
  16383. 12 o'clock, you'd use 1.5*Pi and 2.5*Pi as the start and finish points.
  16384. @param startAsNewSubPath if true, the arc will begin a new subpath from its starting point; if false,
  16385. it will be added to the current sub-path, continuing from the current postition
  16386. @see addArc, arcTo
  16387. */
  16388. void addCentredArc (float centreX, float centreY,
  16389. float radiusX, float radiusY,
  16390. float rotationOfEllipse,
  16391. float fromRadians,
  16392. float toRadians,
  16393. bool startAsNewSubPath = false);
  16394. /** Adds a "pie-chart" shape to the path.
  16395. The shape is added as a new sub-path. (Any currently open paths will be
  16396. left open).
  16397. Note that when specifying the start and end angles, the curve will be drawn either clockwise
  16398. or anti-clockwise according to whether the end angle is greater than the start. This means
  16399. that sometimes you may need to use values greater than 2*Pi for the end angle.
  16400. @param x the left-hand edge of the rectangle in which the elliptical outline fits
  16401. @param y the top edge of the rectangle in which the elliptical outline fits
  16402. @param width the width of the rectangle in which the elliptical outline fits
  16403. @param height the height of the rectangle in which the elliptical outline fits
  16404. @param fromRadians the angle (clockwise) in radians at which to start the arc segment (where 0 is the
  16405. top-centre of the ellipse)
  16406. @param toRadians the angle (clockwise) in radians at which to end the arc segment (where 0 is the
  16407. top-centre of the ellipse)
  16408. @param innerCircleProportionalSize if this is > 0, then the pie will be drawn as a curved band around a hollow
  16409. ellipse at its centre, where this value indicates the inner ellipse's size with
  16410. respect to the outer one.
  16411. @see addArc
  16412. */
  16413. void addPieSegment (float x, float y,
  16414. float width, float height,
  16415. float fromRadians,
  16416. float toRadians,
  16417. float innerCircleProportionalSize);
  16418. /** Adds a line with a specified thickness.
  16419. The line is added as a new closed sub-path. (Any currently open paths will be
  16420. left open).
  16421. @see addArrow
  16422. */
  16423. void addLineSegment (const Line<float>& line, float lineThickness);
  16424. /** Adds a line with an arrowhead on the end.
  16425. The arrow is added as a new closed sub-path. (Any currently open paths will be left open).
  16426. @see PathStrokeType::createStrokeWithArrowheads
  16427. */
  16428. void addArrow (const Line<float>& line,
  16429. float lineThickness,
  16430. float arrowheadWidth,
  16431. float arrowheadLength);
  16432. /** Adds a polygon shape to the path.
  16433. @see addStar
  16434. */
  16435. void addPolygon (const Point<float>& centre,
  16436. int numberOfSides,
  16437. float radius,
  16438. float startAngle = 0.0f);
  16439. /** Adds a star shape to the path.
  16440. @see addPolygon
  16441. */
  16442. void addStar (const Point<float>& centre,
  16443. int numberOfPoints,
  16444. float innerRadius,
  16445. float outerRadius,
  16446. float startAngle = 0.0f);
  16447. /** Adds a speech-bubble shape to the path.
  16448. @param bodyX the left of the main body area of the bubble
  16449. @param bodyY the top of the main body area of the bubble
  16450. @param bodyW the width of the main body area of the bubble
  16451. @param bodyH the height of the main body area of the bubble
  16452. @param cornerSize the amount by which to round off the corners of the main body rectangle
  16453. @param arrowTipX the x position that the tip of the arrow should connect to
  16454. @param arrowTipY the y position that the tip of the arrow should connect to
  16455. @param whichSide the side to connect the arrow to: 0 = top, 1 = left, 2 = bottom, 3 = right
  16456. @param arrowPositionAlongEdgeProportional how far along the edge of the main rectangle the
  16457. arrow's base should be - this is a proportional distance between 0 and 1.0
  16458. @param arrowWidth how wide the base of the arrow should be where it joins the main rectangle
  16459. */
  16460. void addBubble (float bodyX, float bodyY,
  16461. float bodyW, float bodyH,
  16462. float cornerSize,
  16463. float arrowTipX,
  16464. float arrowTipY,
  16465. int whichSide,
  16466. float arrowPositionAlongEdgeProportional,
  16467. float arrowWidth);
  16468. /** Adds another path to this one.
  16469. The new path is added as a new sub-path. (Any currently open paths in this
  16470. path will be left open).
  16471. @param pathToAppend the path to add
  16472. */
  16473. void addPath (const Path& pathToAppend);
  16474. /** Adds another path to this one, transforming it on the way in.
  16475. The new path is added as a new sub-path, its points being transformed by the given
  16476. matrix before being added.
  16477. @param pathToAppend the path to add
  16478. @param transformToApply an optional transform to apply to the incoming vertices
  16479. */
  16480. void addPath (const Path& pathToAppend,
  16481. const AffineTransform& transformToApply);
  16482. /** Swaps the contents of this path with another one.
  16483. The internal data of the two paths is swapped over, so this is much faster than
  16484. copying it to a temp variable and back.
  16485. */
  16486. void swapWithPath (Path& other) throw();
  16487. /** Applies a 2D transform to all the vertices in the path.
  16488. @see AffineTransform, scaleToFit, getTransformToScaleToFit
  16489. */
  16490. void applyTransform (const AffineTransform& transform) throw();
  16491. /** Rescales this path to make it fit neatly into a given space.
  16492. This is effectively a quick way of calling
  16493. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions))
  16494. @param x the x position of the rectangle to fit the path inside
  16495. @param y the y position of the rectangle to fit the path inside
  16496. @param width the width of the rectangle to fit the path inside
  16497. @param height the height of the rectangle to fit the path inside
  16498. @param preserveProportions if true, it will fit the path into the space without altering its
  16499. horizontal/vertical scale ratio; if false, it will distort the
  16500. path to fill the specified ratio both horizontally and vertically
  16501. @see applyTransform, getTransformToScaleToFit
  16502. */
  16503. void scaleToFit (float x, float y, float width, float height,
  16504. bool preserveProportions) throw();
  16505. /** Returns a transform that can be used to rescale the path to fit into a given space.
  16506. @param x the x position of the rectangle to fit the path inside
  16507. @param y the y position of the rectangle to fit the path inside
  16508. @param width the width of the rectangle to fit the path inside
  16509. @param height the height of the rectangle to fit the path inside
  16510. @param preserveProportions if true, it will fit the path into the space without altering its
  16511. horizontal/vertical scale ratio; if false, it will distort the
  16512. path to fill the specified ratio both horizontally and vertically
  16513. @param justificationType if the proportions are preseved, the resultant path may be smaller
  16514. than the available rectangle, so this describes how it should be
  16515. positioned within the space.
  16516. @returns an appropriate transformation
  16517. @see applyTransform, scaleToFit
  16518. */
  16519. const AffineTransform getTransformToScaleToFit (float x, float y, float width, float height,
  16520. bool preserveProportions,
  16521. const Justification& justificationType = Justification::centred) const;
  16522. /** Creates a version of this path where all sharp corners have been replaced by curves.
  16523. Wherever two lines meet at an angle, this will replace the corner with a curve
  16524. of the given radius.
  16525. */
  16526. const Path createPathWithRoundedCorners (float cornerRadius) const;
  16527. /** Changes the winding-rule to be used when filling the path.
  16528. If set to true (which is the default), then the path uses a non-zero-winding rule
  16529. to determine which points are inside the path. If set to false, it uses an
  16530. alternate-winding rule.
  16531. The winding-rule comes into play when areas of the shape overlap other
  16532. areas, and determines whether the overlapping regions are considered to be
  16533. inside or outside.
  16534. Changing this value just sets a flag - it doesn't affect the contents of the
  16535. path.
  16536. @see isUsingNonZeroWinding
  16537. */
  16538. void setUsingNonZeroWinding (bool isNonZeroWinding) throw();
  16539. /** Returns the flag that indicates whether the path should use a non-zero winding rule.
  16540. The default for a new path is true.
  16541. @see setUsingNonZeroWinding
  16542. */
  16543. bool isUsingNonZeroWinding() const { return useNonZeroWinding; }
  16544. /** Iterates the lines and curves that a path contains.
  16545. @see Path, PathFlatteningIterator
  16546. */
  16547. class JUCE_API Iterator
  16548. {
  16549. public:
  16550. Iterator (const Path& path);
  16551. ~Iterator();
  16552. /** Moves onto the next element in the path.
  16553. If this returns false, there are no more elements. If it returns true,
  16554. the elementType variable will be set to the type of the current element,
  16555. and some of the x and y variables will be filled in with values.
  16556. */
  16557. bool next();
  16558. enum PathElementType
  16559. {
  16560. startNewSubPath, /**< For this type, x1 and y1 will be set to indicate the first point in the subpath. */
  16561. lineTo, /**< For this type, x1 and y1 indicate the end point of the line. */
  16562. quadraticTo, /**< For this type, x1, y1, x2, y2 indicate the control point and endpoint of a quadratic curve. */
  16563. cubicTo, /**< For this type, x1, y1, x2, y2, x3, y3 indicate the two control points and the endpoint of a cubic curve. */
  16564. closePath /**< Indicates that the sub-path is being closed. None of the x or y values are valid in this case. */
  16565. };
  16566. PathElementType elementType;
  16567. float x1, y1, x2, y2, x3, y3;
  16568. private:
  16569. const Path& path;
  16570. size_t index;
  16571. Iterator (const Iterator&);
  16572. Iterator& operator= (const Iterator&);
  16573. };
  16574. /** Loads a stored path from a data stream.
  16575. The data in the stream must have been written using writePathToStream().
  16576. Note that this will append the stored path to whatever is currently in
  16577. this path, so you might need to call clear() beforehand.
  16578. @see loadPathFromData, writePathToStream
  16579. */
  16580. void loadPathFromStream (InputStream& source);
  16581. /** Loads a stored path from a block of data.
  16582. This is similar to loadPathFromStream(), but just reads from a block
  16583. of data. Useful if you're including stored shapes in your code as a
  16584. block of static data.
  16585. @see loadPathFromStream, writePathToStream
  16586. */
  16587. void loadPathFromData (const void* data, int numberOfBytes);
  16588. /** Stores the path by writing it out to a stream.
  16589. After writing out a path, you can reload it using loadPathFromStream().
  16590. @see loadPathFromStream, loadPathFromData
  16591. */
  16592. void writePathToStream (OutputStream& destination) const;
  16593. /** Creates a string containing a textual representation of this path.
  16594. @see restoreFromString
  16595. */
  16596. const String toString() const;
  16597. /** Restores this path from a string that was created with the toString() method.
  16598. @see toString()
  16599. */
  16600. void restoreFromString (const String& stringVersion);
  16601. juce_UseDebuggingNewOperator
  16602. private:
  16603. friend class PathFlatteningIterator;
  16604. friend class Path::Iterator;
  16605. ArrayAllocationBase <float, DummyCriticalSection> data;
  16606. size_t numElements;
  16607. float pathXMin, pathXMax, pathYMin, pathYMax;
  16608. bool useNonZeroWinding;
  16609. static const float lineMarker;
  16610. static const float moveMarker;
  16611. static const float quadMarker;
  16612. static const float cubicMarker;
  16613. static const float closeSubPathMarker;
  16614. };
  16615. #endif // __JUCE_PATH_JUCEHEADER__
  16616. /*** End of inlined file: juce_Path.h ***/
  16617. class Font;
  16618. /** A typeface represents a size-independent font.
  16619. This base class is abstract, but calling createSystemTypefaceFor() will return
  16620. a platform-specific subclass that can be used.
  16621. The CustomTypeface subclass allow you to build your own typeface, and to
  16622. load and save it in the Juce typeface format.
  16623. Normally you should never need to deal directly with Typeface objects - the Font
  16624. class does everything you typically need for rendering text.
  16625. @see CustomTypeface, Font
  16626. */
  16627. class JUCE_API Typeface : public ReferenceCountedObject
  16628. {
  16629. public:
  16630. /** A handy typedef for a pointer to a typeface. */
  16631. typedef ReferenceCountedObjectPtr <Typeface> Ptr;
  16632. /** Returns the name of the typeface.
  16633. @see Font::getTypefaceName
  16634. */
  16635. const String getName() const throw() { return name; }
  16636. /** Creates a new system typeface. */
  16637. static const Ptr createSystemTypefaceFor (const Font& font);
  16638. /** Destructor. */
  16639. virtual ~Typeface();
  16640. /** Returns the ascent of the font, as a proportion of its height.
  16641. The height is considered to always be normalised as 1.0, so this will be a
  16642. value less that 1.0, indicating the proportion of the font that lies above
  16643. its baseline.
  16644. */
  16645. virtual float getAscent() const = 0;
  16646. /** Returns the descent of the font, as a proportion of its height.
  16647. The height is considered to always be normalised as 1.0, so this will be a
  16648. value less that 1.0, indicating the proportion of the font that lies below
  16649. its baseline.
  16650. */
  16651. virtual float getDescent() const = 0;
  16652. /** Measures the width of a line of text.
  16653. The distance returned is based on the font having an normalised height of 1.0.
  16654. You should never need to call this directly! Use Font::getStringWidth() instead!
  16655. */
  16656. virtual float getStringWidth (const String& text) = 0;
  16657. /** Converts a line of text into its glyph numbers and their positions.
  16658. The distances returned are based on the font having an normalised height of 1.0.
  16659. You should never need to call this directly! Use Font::getGlyphPositions() instead!
  16660. */
  16661. virtual void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets) = 0;
  16662. /** Returns the outline for a glyph.
  16663. The path returned will be normalised to a font height of 1.0.
  16664. */
  16665. virtual bool getOutlineForGlyph (int glyphNumber, Path& path) = 0;
  16666. juce_UseDebuggingNewOperator
  16667. protected:
  16668. String name;
  16669. explicit Typeface (const String& name) throw();
  16670. private:
  16671. Typeface (const Typeface&);
  16672. Typeface& operator= (const Typeface&);
  16673. };
  16674. /** A typeface that can be populated with custom glyphs.
  16675. You can create a CustomTypeface if you need one that contains your own glyphs,
  16676. or if you need to load a typeface from a Juce-formatted binary stream.
  16677. If you want to create a copy of a native face, you can use addGlyphsFromOtherTypeface()
  16678. to copy glyphs into this face.
  16679. @see Typeface, Font
  16680. */
  16681. class JUCE_API CustomTypeface : public Typeface
  16682. {
  16683. public:
  16684. /** Creates a new, empty typeface. */
  16685. CustomTypeface();
  16686. /** Loads a typeface from a previously saved stream.
  16687. The stream must have been created by writeToStream().
  16688. @see writeToStream
  16689. */
  16690. explicit CustomTypeface (InputStream& serialisedTypefaceStream);
  16691. /** Destructor. */
  16692. ~CustomTypeface();
  16693. /** Resets this typeface, deleting all its glyphs and settings. */
  16694. void clear();
  16695. /** Sets the vital statistics for the typeface.
  16696. @param name the typeface's name
  16697. @param ascent the ascent - this is normalised to a height of 1.0 and this is
  16698. the value that will be returned by Typeface::getAscent(). The
  16699. descent is assumed to be (1.0 - ascent)
  16700. @param isBold should be true if the typeface is bold
  16701. @param isItalic should be true if the typeface is italic
  16702. @param defaultCharacter the character to be used as a replacement if there's
  16703. no glyph available for the character that's being drawn
  16704. */
  16705. void setCharacteristics (const String& name, float ascent,
  16706. bool isBold, bool isItalic,
  16707. juce_wchar defaultCharacter) throw();
  16708. /** Adds a glyph to the typeface.
  16709. The path that is passed in is normalised so that the font height is 1.0, and its
  16710. origin is the anchor point of the character on its baseline.
  16711. The width is the nominal width of the character, and any extra kerning values that
  16712. are specified will be added to this width.
  16713. */
  16714. void addGlyph (juce_wchar character, const Path& path, float width) throw();
  16715. /** Specifies an extra kerning amount to be used between a pair of characters.
  16716. The amount will be added to the nominal width of the first character when laying out a string.
  16717. */
  16718. void addKerningPair (juce_wchar char1, juce_wchar char2, float extraAmount) throw();
  16719. /** Adds a range of glyphs from another typeface.
  16720. This will attempt to pull in the paths and kerning information from another typeface and
  16721. add it to this one.
  16722. */
  16723. void addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw();
  16724. /** Saves this typeface as a Juce-formatted font file.
  16725. A CustomTypeface can be created to reload the data that is written - see the CustomTypeface
  16726. constructor.
  16727. */
  16728. bool writeToStream (OutputStream& outputStream);
  16729. // The following methods implement the basic Typeface behaviour.
  16730. float getAscent() const;
  16731. float getDescent() const;
  16732. float getStringWidth (const String& text);
  16733. void getGlyphPositions (const String& text, Array <int>& glyphs, Array<float>& xOffsets);
  16734. bool getOutlineForGlyph (int glyphNumber, Path& path);
  16735. int getGlyphForCharacter (juce_wchar character);
  16736. juce_UseDebuggingNewOperator
  16737. protected:
  16738. juce_wchar defaultCharacter;
  16739. float ascent;
  16740. bool isBold, isItalic;
  16741. /** If a subclass overrides this, it can load glyphs into the font on-demand.
  16742. When methods such as getGlyphPositions() or getOutlineForGlyph() are asked for a
  16743. particular character and there's no corresponding glyph, they'll call this
  16744. method so that a subclass can try to add that glyph, returning true if it
  16745. manages to do so.
  16746. */
  16747. virtual bool loadGlyphIfPossible (juce_wchar characterNeeded);
  16748. private:
  16749. class GlyphInfo;
  16750. friend class OwnedArray<GlyphInfo>;
  16751. OwnedArray <GlyphInfo> glyphs;
  16752. short lookupTable [128];
  16753. CustomTypeface (const CustomTypeface&);
  16754. CustomTypeface& operator= (const CustomTypeface&);
  16755. GlyphInfo* findGlyph (const juce_wchar character, bool loadIfNeeded) throw();
  16756. GlyphInfo* findGlyphSubstituting (juce_wchar character) throw();
  16757. };
  16758. #endif // __JUCE_TYPEFACE_JUCEHEADER__
  16759. /*** End of inlined file: juce_Typeface.h ***/
  16760. class LowLevelGraphicsContext;
  16761. /**
  16762. Represents a particular font, including its size, style, etc.
  16763. Apart from the typeface to be used, a Font object also dictates whether
  16764. the font is bold, italic, underlined, how big it is, and its kerning and
  16765. horizontal scale factor.
  16766. @see Typeface
  16767. */
  16768. class JUCE_API Font
  16769. {
  16770. public:
  16771. /** A combination of these values is used by the constructor to specify the
  16772. style of font to use.
  16773. */
  16774. enum FontStyleFlags
  16775. {
  16776. plain = 0, /**< indicates a plain, non-bold, non-italic version of the font. @see setStyleFlags */
  16777. bold = 1, /**< boldens the font. @see setStyleFlags */
  16778. italic = 2, /**< finds an italic version of the font. @see setStyleFlags */
  16779. underlined = 4 /**< underlines the font. @see setStyleFlags */
  16780. };
  16781. /** Creates a sans-serif font in a given size.
  16782. @param fontHeight the height in pixels (can be fractional)
  16783. @param styleFlags the style to use - this can be a combination of the
  16784. Font::bold, Font::italic and Font::underlined, or
  16785. just Font::plain for the normal style.
  16786. @see FontStyleFlags, getDefaultSansSerifFontName
  16787. */
  16788. Font (float fontHeight,
  16789. int styleFlags = plain) throw();
  16790. /** Creates a font with a given typeface and parameters.
  16791. @param typefaceName the name of the typeface to use
  16792. @param fontHeight the height in pixels (can be fractional)
  16793. @param styleFlags the style to use - this can be a combination of the
  16794. Font::bold, Font::italic and Font::underlined, or
  16795. just Font::plain for the normal style.
  16796. @see FontStyleFlags, getDefaultSansSerifFontName
  16797. */
  16798. Font (const String& typefaceName,
  16799. float fontHeight,
  16800. int styleFlags) throw();
  16801. /** Creates a copy of another Font object. */
  16802. Font (const Font& other) throw();
  16803. /** Creates a font for a typeface. */
  16804. Font (const Typeface::Ptr& typeface) throw();
  16805. /** Creates a basic sans-serif font at a default height.
  16806. You should use one of the other constructors for creating a font that you're planning
  16807. on drawing with - this constructor is here to help initialise objects before changing
  16808. the font's settings later.
  16809. */
  16810. Font() throw();
  16811. /** Copies this font from another one. */
  16812. Font& operator= (const Font& other) throw();
  16813. bool operator== (const Font& other) const throw();
  16814. bool operator!= (const Font& other) const throw();
  16815. /** Destructor. */
  16816. ~Font() throw();
  16817. /** Changes the name of the typeface family.
  16818. e.g. "Arial", "Courier", etc.
  16819. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16820. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16821. but are generic names that are used to represent the various default fonts.
  16822. If you need to know the exact typeface name being used, you can call
  16823. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16824. If a suitable font isn't found on the machine, it'll just use a default instead.
  16825. */
  16826. void setTypefaceName (const String& faceName) throw();
  16827. /** Returns the name of the typeface family that this font uses.
  16828. e.g. "Arial", "Courier", etc.
  16829. This may also be set to Font::getDefaultSansSerifFontName(), Font::getDefaultSerifFontName(),
  16830. or Font::getDefaultMonospacedFontName(), which are not actual platform-specific font names,
  16831. but are generic names that are used to represent the various default fonts.
  16832. If you need to know the exact typeface name being used, you can call
  16833. Font::getTypeface()->getTypefaceName(), which will give you the platform-specific name.
  16834. */
  16835. const String& getTypefaceName() const throw() { return font->typefaceName; }
  16836. /** Returns a typeface name that represents the default sans-serif font.
  16837. This is also the typeface that will be used when a font is created without
  16838. specifying any typeface details.
  16839. Note that this method just returns a generic placeholder string that means "the default
  16840. sans-serif font" - it's not the actual name of this font. To get the actual name, use
  16841. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16842. @see setTypefaceName, getDefaultSerifFontName, getDefaultMonospacedFontName
  16843. */
  16844. static const String getDefaultSansSerifFontName() throw();
  16845. /** Returns a typeface name that represents the default sans-serif font.
  16846. Note that this method just returns a generic placeholder string that means "the default
  16847. serif font" - it's not the actual name of this font. To get the actual name, use
  16848. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16849. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultMonospacedFontName
  16850. */
  16851. static const String getDefaultSerifFontName() throw();
  16852. /** Returns a typeface name that represents the default sans-serif font.
  16853. Note that this method just returns a generic placeholder string that means "the default
  16854. monospaced font" - it's not the actual name of this font. To get the actual name, use
  16855. getPlatformDefaultFontNames() or LookAndFeel::getTypefaceForFont().
  16856. @see setTypefaceName, getDefaultSansSerifFontName, getDefaultSerifFontName
  16857. */
  16858. static const String getDefaultMonospacedFontName() throw();
  16859. /** Returns the typeface names of the default fonts on the current platform. */
  16860. static void getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed);
  16861. /** Returns the total height of this font.
  16862. This is the maximum height, from the top of the ascent to the bottom of the
  16863. descenders.
  16864. @see setHeight, setHeightWithoutChangingWidth, getAscent
  16865. */
  16866. float getHeight() const throw() { return font->height; }
  16867. /** Changes the font's height.
  16868. @see getHeight, setHeightWithoutChangingWidth
  16869. */
  16870. void setHeight (float newHeight) throw();
  16871. /** Changes the font's height without changing its width.
  16872. This alters the horizontal scale to compensate for the change in height.
  16873. */
  16874. void setHeightWithoutChangingWidth (float newHeight) throw();
  16875. /** Returns the height of the font above its baseline.
  16876. This is the maximum height from the baseline to the top.
  16877. @see getHeight, getDescent
  16878. */
  16879. float getAscent() const throw();
  16880. /** Returns the amount that the font descends below its baseline.
  16881. This is calculated as (getHeight() - getAscent()).
  16882. @see getAscent, getHeight
  16883. */
  16884. float getDescent() const throw();
  16885. /** Returns the font's style flags.
  16886. This will return a bitwise-or'ed combination of values from the FontStyleFlags
  16887. enum, to describe whether the font is bold, italic, etc.
  16888. @see FontStyleFlags
  16889. */
  16890. int getStyleFlags() const throw() { return font->styleFlags; }
  16891. /** Changes the font's style.
  16892. @param newFlags a bitwise-or'ed combination of values from the FontStyleFlags
  16893. enum, to set the font's properties
  16894. @see FontStyleFlags
  16895. */
  16896. void setStyleFlags (int newFlags) throw();
  16897. /** Makes the font bold or non-bold. */
  16898. void setBold (bool shouldBeBold) throw();
  16899. /** Returns true if the font is bold. */
  16900. bool isBold() const throw();
  16901. /** Makes the font italic or non-italic. */
  16902. void setItalic (bool shouldBeItalic) throw();
  16903. /** Returns true if the font is italic. */
  16904. bool isItalic() const throw();
  16905. /** Makes the font underlined or non-underlined. */
  16906. void setUnderline (bool shouldBeUnderlined) throw();
  16907. /** Returns true if the font is underlined. */
  16908. bool isUnderlined() const throw();
  16909. /** Changes the font's horizontal scale factor.
  16910. @param scaleFactor a value of 1.0 is the normal scale, less than this will be
  16911. narrower, greater than 1.0 will be stretched out.
  16912. */
  16913. void setHorizontalScale (float scaleFactor) throw();
  16914. /** Returns the font's horizontal scale.
  16915. A value of 1.0 is the normal scale, less than this will be narrower, greater
  16916. than 1.0 will be stretched out.
  16917. @see setHorizontalScale
  16918. */
  16919. float getHorizontalScale() const throw() { return font->horizontalScale; }
  16920. /** Changes the font's kerning.
  16921. @param extraKerning a multiple of the font's height that will be added
  16922. to space between the characters. So a value of zero is
  16923. normal spacing, positive values spread the letters out,
  16924. negative values make them closer together.
  16925. */
  16926. void setExtraKerningFactor (float extraKerning) throw();
  16927. /** Returns the font's kerning.
  16928. This is the extra space added between adjacent characters, as a proportion
  16929. of the font's height.
  16930. A value of zero is normal spacing, positive values will spread the letters
  16931. out more, and negative values make them closer together.
  16932. */
  16933. float getExtraKerningFactor() const throw() { return font->kerning; }
  16934. /** Changes all the font's characteristics with one call. */
  16935. void setSizeAndStyle (float newHeight,
  16936. int newStyleFlags,
  16937. float newHorizontalScale,
  16938. float newKerningAmount) throw();
  16939. /** Returns the total width of a string as it would be drawn using this font.
  16940. For a more accurate floating-point result, use getStringWidthFloat().
  16941. */
  16942. int getStringWidth (const String& text) const throw();
  16943. /** Returns the total width of a string as it would be drawn using this font.
  16944. @see getStringWidth
  16945. */
  16946. float getStringWidthFloat (const String& text) const throw();
  16947. /** Returns the series of glyph numbers and their x offsets needed to represent a string.
  16948. An extra x offset is added at the end of the run, to indicate where the right hand
  16949. edge of the last character is.
  16950. */
  16951. void getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const throw();
  16952. /** Returns the typeface used by this font.
  16953. Note that the object returned may go out of scope if this font is deleted
  16954. or has its style changed.
  16955. */
  16956. Typeface* getTypeface() const throw();
  16957. /** Creates an array of Font objects to represent all the fonts on the system.
  16958. If you just need the names of the typefaces, you can also use
  16959. findAllTypefaceNames() instead.
  16960. @param results the array to which new Font objects will be added.
  16961. */
  16962. static void findFonts (Array<Font>& results) throw();
  16963. /** Returns a list of all the available typeface names.
  16964. The names returned can be passed into setTypefaceName().
  16965. You can use this instead of findFonts() if you only need their names, and not
  16966. font objects.
  16967. */
  16968. static const StringArray findAllTypefaceNames();
  16969. /** Returns the name of the typeface to be used for rendering glyphs that aren't found
  16970. in the requested typeface.
  16971. */
  16972. static const String getFallbackFontName() throw();
  16973. /** Sets the (platform-specific) name of the typeface to use to find glyphs that aren't
  16974. available in whatever font you're trying to use.
  16975. */
  16976. static void setFallbackFontName (const String& name) throw();
  16977. /** Creates a string to describe this font.
  16978. The string will contain information to describe the font's typeface, size, and
  16979. style. To recreate the font from this string, use fromString().
  16980. */
  16981. const String toString() const;
  16982. /** Recreates a font from its stringified encoding.
  16983. This method takes a string that was created by toString(), and recreates the
  16984. original font.
  16985. */
  16986. static const Font fromString (const String& fontDescription);
  16987. juce_UseDebuggingNewOperator
  16988. private:
  16989. friend class FontGlyphAlphaMap;
  16990. friend class TypefaceCache;
  16991. class SharedFontInternal : public ReferenceCountedObject
  16992. {
  16993. public:
  16994. SharedFontInternal (const String& typefaceName, float height, float horizontalScale,
  16995. float kerning, float ascent, int styleFlags,
  16996. Typeface* typeface) throw();
  16997. SharedFontInternal (const SharedFontInternal& other) throw();
  16998. String typefaceName;
  16999. float height, horizontalScale, kerning, ascent;
  17000. int styleFlags;
  17001. Typeface::Ptr typeface;
  17002. };
  17003. ReferenceCountedObjectPtr <SharedFontInternal> font;
  17004. void dupeInternalIfShared() throw();
  17005. };
  17006. #endif // __JUCE_FONT_JUCEHEADER__
  17007. /*** End of inlined file: juce_Font.h ***/
  17008. /*** Start of inlined file: juce_PathStrokeType.h ***/
  17009. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  17010. #define __JUCE_PATHSTROKETYPE_JUCEHEADER__
  17011. /**
  17012. Describes a type of stroke used to render a solid outline along a path.
  17013. A PathStrokeType object can be used directly to create the shape of an outline
  17014. around a path, and is used by Graphics::strokePath to specify the type of
  17015. stroke to draw.
  17016. @see Path, Graphics::strokePath
  17017. */
  17018. class JUCE_API PathStrokeType
  17019. {
  17020. public:
  17021. /** The type of shape to use for the corners between two adjacent line segments. */
  17022. enum JointStyle
  17023. {
  17024. mitered, /**< Indicates that corners should be drawn with sharp joints.
  17025. Note that for angles that curve back on themselves, drawing a
  17026. mitre could require extending the point too far away from the
  17027. path, so a mitre limit is imposed and any corners that exceed it
  17028. are drawn as bevelled instead. */
  17029. curved, /**< Indicates that corners should be drawn as rounded-off. */
  17030. beveled /**< Indicates that corners should be drawn with a line flattening their
  17031. outside edge. */
  17032. };
  17033. /** The type shape to use for the ends of lines. */
  17034. enum EndCapStyle
  17035. {
  17036. butt, /**< Ends of lines are flat and don't extend beyond the end point. */
  17037. square, /**< Ends of lines are flat, but stick out beyond the end point for half
  17038. the thickness of the stroke. */
  17039. rounded /**< Ends of lines are rounded-off with a circular shape. */
  17040. };
  17041. /** Creates a stroke type.
  17042. @param strokeThickness the width of the line to use
  17043. @param jointStyle the type of joints to use for corners
  17044. @param endStyle the type of end-caps to use for the ends of open paths.
  17045. */
  17046. PathStrokeType (float strokeThickness,
  17047. JointStyle jointStyle = mitered,
  17048. EndCapStyle endStyle = butt) throw();
  17049. /** Createes a copy of another stroke type. */
  17050. PathStrokeType (const PathStrokeType& other) throw();
  17051. /** Copies another stroke onto this one. */
  17052. PathStrokeType& operator= (const PathStrokeType& other) throw();
  17053. /** Destructor. */
  17054. ~PathStrokeType() throw();
  17055. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  17056. @param destPath the resultant stroked outline shape will be copied into this path.
  17057. Note that it's ok for the source and destination Paths to be
  17058. the same object, so you can easily turn a path into a stroked version
  17059. of itself.
  17060. @param sourcePath the path to use as the source
  17061. @param transform an optional transform to apply to the points from the source path
  17062. as they are being used
  17063. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17064. a higher resolution, which improved the quality if you'll later want
  17065. to enlarge the stroked path
  17066. @see createDashedStroke
  17067. */
  17068. void createStrokedPath (Path& destPath,
  17069. const Path& sourcePath,
  17070. const AffineTransform& transform = AffineTransform::identity,
  17071. float extraAccuracy = 1.0f) const;
  17072. /** Applies this stroke type to a path, creating a dashed line.
  17073. This is similar to createStrokedPath, but uses the array passed in to
  17074. break the stroke up into a series of dashes.
  17075. @param destPath the resultant stroked outline shape will be copied into this path.
  17076. Note that it's ok for the source and destination Paths to be
  17077. the same object, so you can easily turn a path into a stroked version
  17078. of itself.
  17079. @param sourcePath the path to use as the source
  17080. @param dashLengths An array of alternating on/off lengths. E.g. { 2, 3, 4, 5 } will create
  17081. a line of length 2, then skip a length of 3, then add a line of length 4,
  17082. skip 5, and keep repeating this pattern.
  17083. @param numDashLengths The number of lengths in the dashLengths array. This should really be
  17084. an even number, otherwise the pattern will get out of step as it
  17085. repeats.
  17086. @param transform an optional transform to apply to the points from the source path
  17087. as they are being used
  17088. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17089. a higher resolution, which improved the quality if you'll later want
  17090. to enlarge the stroked path
  17091. */
  17092. void createDashedStroke (Path& destPath,
  17093. const Path& sourcePath,
  17094. const float* dashLengths,
  17095. int numDashLengths,
  17096. const AffineTransform& transform = AffineTransform::identity,
  17097. float extraAccuracy = 1.0f) const;
  17098. /** Applies this stroke type to a path and returns the resultant stroke as another Path.
  17099. @param destPath the resultant stroked outline shape will be copied into this path.
  17100. Note that it's ok for the source and destination Paths to be
  17101. the same object, so you can easily turn a path into a stroked version
  17102. of itself.
  17103. @param sourcePath the path to use as the source
  17104. @param arrowheadStartWidth the width of the arrowhead at the start of the path
  17105. @param arrowheadStartLength the length of the arrowhead at the start of the path
  17106. @param arrowheadEndWidth the width of the arrowhead at the end of the path
  17107. @param arrowheadEndLength the length of the arrowhead at the end of the path
  17108. @param transform an optional transform to apply to the points from the source path
  17109. as they are being used
  17110. @param extraAccuracy if this is greater than 1.0, it will subdivide the path to
  17111. a higher resolution, which improved the quality if you'll later want
  17112. to enlarge the stroked path
  17113. @see createDashedStroke
  17114. */
  17115. void createStrokeWithArrowheads (Path& destPath,
  17116. const Path& sourcePath,
  17117. float arrowheadStartWidth, float arrowheadStartLength,
  17118. float arrowheadEndWidth, float arrowheadEndLength,
  17119. const AffineTransform& transform = AffineTransform::identity,
  17120. float extraAccuracy = 1.0f) const;
  17121. /** Returns the stroke thickness. */
  17122. float getStrokeThickness() const throw() { return thickness; }
  17123. /** Sets the stroke thickness. */
  17124. void setStrokeThickness (float newThickness) throw() { thickness = newThickness; }
  17125. /** Returns the joint style. */
  17126. JointStyle getJointStyle() const throw() { return jointStyle; }
  17127. /** Sets the joint style. */
  17128. void setJointStyle (JointStyle newStyle) throw() { jointStyle = newStyle; }
  17129. /** Returns the end-cap style. */
  17130. EndCapStyle getEndStyle() const throw() { return endStyle; }
  17131. /** Sets the end-cap style. */
  17132. void setEndStyle (EndCapStyle newStyle) throw() { endStyle = newStyle; }
  17133. juce_UseDebuggingNewOperator
  17134. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  17135. bool operator== (const PathStrokeType& other) const throw();
  17136. /** Compares the stroke thickness, joint and end styles of two stroke types. */
  17137. bool operator!= (const PathStrokeType& other) const throw();
  17138. private:
  17139. float thickness;
  17140. JointStyle jointStyle;
  17141. EndCapStyle endStyle;
  17142. };
  17143. #endif // __JUCE_PATHSTROKETYPE_JUCEHEADER__
  17144. /*** End of inlined file: juce_PathStrokeType.h ***/
  17145. /*** Start of inlined file: juce_Colours.h ***/
  17146. #ifndef __JUCE_COLOURS_JUCEHEADER__
  17147. #define __JUCE_COLOURS_JUCEHEADER__
  17148. /*** Start of inlined file: juce_Colour.h ***/
  17149. #ifndef __JUCE_COLOUR_JUCEHEADER__
  17150. #define __JUCE_COLOUR_JUCEHEADER__
  17151. /*** Start of inlined file: juce_PixelFormats.h ***/
  17152. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  17153. #define __JUCE_PIXELFORMATS_JUCEHEADER__
  17154. #if JUCE_MSVC
  17155. #pragma pack (push, 1)
  17156. #define PACKED
  17157. #elif JUCE_GCC
  17158. #define PACKED __attribute__((packed))
  17159. #else
  17160. #define PACKED
  17161. #endif
  17162. class PixelRGB;
  17163. class PixelAlpha;
  17164. /**
  17165. Represents a 32-bit ARGB pixel with premultiplied alpha, and can perform compositing
  17166. operations with it.
  17167. This is used internally by the imaging classes.
  17168. @see PixelRGB
  17169. */
  17170. class JUCE_API PixelARGB
  17171. {
  17172. public:
  17173. /** Creates a pixel without defining its colour. */
  17174. PixelARGB() throw() {}
  17175. ~PixelARGB() throw() {}
  17176. /** Creates a pixel from a 32-bit argb value.
  17177. */
  17178. PixelARGB (const uint32 argb_) throw()
  17179. : argb (argb_)
  17180. {
  17181. }
  17182. forcedinline uint32 getARGB() const throw() { return argb; }
  17183. forcedinline uint32 getRB() const throw() { return 0x00ff00ff & argb; }
  17184. forcedinline uint32 getAG() const throw() { return 0x00ff00ff & (argb >> 8); }
  17185. forcedinline uint8 getAlpha() const throw() { return components.a; }
  17186. forcedinline uint8 getRed() const throw() { return components.r; }
  17187. forcedinline uint8 getGreen() const throw() { return components.g; }
  17188. forcedinline uint8 getBlue() const throw() { return components.b; }
  17189. /** Blends another pixel onto this one.
  17190. This takes into account the opacity of the pixel being overlaid, and blends
  17191. it accordingly.
  17192. */
  17193. forcedinline void blend (const PixelARGB& src) throw()
  17194. {
  17195. uint32 sargb = src.getARGB();
  17196. const uint32 alpha = 0x100 - (sargb >> 24);
  17197. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17198. sargb += 0xff00ff00 & (getAG() * alpha);
  17199. argb = sargb;
  17200. }
  17201. /** Blends another pixel onto this one.
  17202. This takes into account the opacity of the pixel being overlaid, and blends
  17203. it accordingly.
  17204. */
  17205. forcedinline void blend (const PixelAlpha& src) throw();
  17206. /** Blends another pixel onto this one.
  17207. This takes into account the opacity of the pixel being overlaid, and blends
  17208. it accordingly.
  17209. */
  17210. forcedinline void blend (const PixelRGB& src) throw();
  17211. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17212. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17213. being used, so this can blend semi-transparently from a PixelRGB argument.
  17214. */
  17215. template <class Pixel>
  17216. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17217. {
  17218. ++extraAlpha;
  17219. uint32 sargb = ((extraAlpha * src.getAG()) & 0xff00ff00)
  17220. | (((extraAlpha * src.getRB()) >> 8) & 0x00ff00ff);
  17221. const uint32 alpha = 0x100 - (sargb >> 24);
  17222. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17223. sargb += 0xff00ff00 & (getAG() * alpha);
  17224. argb = sargb;
  17225. }
  17226. /** Blends another pixel with this one, creating a colour that is somewhere
  17227. between the two, as specified by the amount.
  17228. */
  17229. template <class Pixel>
  17230. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17231. {
  17232. uint32 drb = getRB();
  17233. drb += (((src.getRB() - drb) * amount) >> 8);
  17234. drb &= 0x00ff00ff;
  17235. uint32 dag = getAG();
  17236. dag += (((src.getAG() - dag) * amount) >> 8);
  17237. dag &= 0x00ff00ff;
  17238. dag <<= 8;
  17239. dag |= drb;
  17240. argb = dag;
  17241. }
  17242. /** Copies another pixel colour over this one.
  17243. This doesn't blend it - this colour is simply replaced by the other one.
  17244. */
  17245. template <class Pixel>
  17246. forcedinline void set (const Pixel& src) throw()
  17247. {
  17248. argb = src.getARGB();
  17249. }
  17250. /** Replaces the colour's alpha value with another one. */
  17251. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17252. {
  17253. components.a = newAlpha;
  17254. }
  17255. /** Multiplies the colour's alpha value with another one. */
  17256. forcedinline void multiplyAlpha (int multiplier) throw()
  17257. {
  17258. ++multiplier;
  17259. argb = ((multiplier * getAG()) & 0xff00ff00)
  17260. | (((multiplier * getRB()) >> 8) & 0x00ff00ff);
  17261. }
  17262. forcedinline void multiplyAlpha (const float multiplier) throw()
  17263. {
  17264. multiplyAlpha ((int) (multiplier * 256.0f));
  17265. }
  17266. /** Sets the pixel's colour from individual components. */
  17267. void setARGB (const uint8 a, const uint8 r, const uint8 g, const uint8 b) throw()
  17268. {
  17269. components.b = b;
  17270. components.g = g;
  17271. components.r = r;
  17272. components.a = a;
  17273. }
  17274. /** Premultiplies the pixel's RGB values by its alpha. */
  17275. forcedinline void premultiply() throw()
  17276. {
  17277. const uint32 alpha = components.a;
  17278. if (alpha < 0xff)
  17279. {
  17280. if (alpha == 0)
  17281. {
  17282. components.b = 0;
  17283. components.g = 0;
  17284. components.r = 0;
  17285. }
  17286. else
  17287. {
  17288. components.b = (uint8) ((components.b * alpha + 0x7f) >> 8);
  17289. components.g = (uint8) ((components.g * alpha + 0x7f) >> 8);
  17290. components.r = (uint8) ((components.r * alpha + 0x7f) >> 8);
  17291. }
  17292. }
  17293. }
  17294. /** Unpremultiplies the pixel's RGB values. */
  17295. forcedinline void unpremultiply() throw()
  17296. {
  17297. const uint32 alpha = components.a;
  17298. if (alpha < 0xff)
  17299. {
  17300. if (alpha == 0)
  17301. {
  17302. components.b = 0;
  17303. components.g = 0;
  17304. components.r = 0;
  17305. }
  17306. else
  17307. {
  17308. components.b = (uint8) jmin ((uint32) 0xff, (components.b * 0xff) / alpha);
  17309. components.g = (uint8) jmin ((uint32) 0xff, (components.g * 0xff) / alpha);
  17310. components.r = (uint8) jmin ((uint32) 0xff, (components.r * 0xff) / alpha);
  17311. }
  17312. }
  17313. }
  17314. forcedinline void desaturate() throw()
  17315. {
  17316. if (components.a < 0xff && components.a > 0)
  17317. {
  17318. const int newUnpremultipliedLevel = (0xff * ((int) components.r + (int) components.g + (int) components.b) / (3 * components.a));
  17319. components.r = components.g = components.b
  17320. = (uint8) ((newUnpremultipliedLevel * components.a + 0x7f) >> 8);
  17321. }
  17322. else
  17323. {
  17324. components.r = components.g = components.b
  17325. = (uint8) (((int) components.r + (int) components.g + (int) components.b) / 3);
  17326. }
  17327. }
  17328. /** The indexes of the different components in the byte layout of this type of colour. */
  17329. #if JUCE_BIG_ENDIAN
  17330. enum { indexA = 0, indexR = 1, indexG = 2, indexB = 3 };
  17331. #else
  17332. enum { indexA = 3, indexR = 2, indexG = 1, indexB = 0 };
  17333. #endif
  17334. private:
  17335. union
  17336. {
  17337. uint32 argb;
  17338. struct
  17339. {
  17340. #if JUCE_BIG_ENDIAN
  17341. uint8 a : 8, r : 8, g : 8, b : 8;
  17342. #else
  17343. uint8 b, g, r, a;
  17344. #endif
  17345. } PACKED components;
  17346. };
  17347. } PACKED;
  17348. /**
  17349. Represents a 24-bit RGB pixel, and can perform compositing operations on it.
  17350. This is used internally by the imaging classes.
  17351. @see PixelARGB
  17352. */
  17353. class JUCE_API PixelRGB
  17354. {
  17355. public:
  17356. /** Creates a pixel without defining its colour. */
  17357. PixelRGB() throw() {}
  17358. ~PixelRGB() throw() {}
  17359. /** Creates a pixel from a 32-bit argb value.
  17360. (The argb format is that used by PixelARGB)
  17361. */
  17362. PixelRGB (const uint32 argb) throw()
  17363. {
  17364. r = (uint8) (argb >> 16);
  17365. g = (uint8) (argb >> 8);
  17366. b = (uint8) (argb);
  17367. }
  17368. forcedinline uint32 getARGB() const throw() { return 0xff000000 | b | (g << 8) | (r << 16); }
  17369. forcedinline uint32 getRB() const throw() { return b | (uint32) (r << 16); }
  17370. forcedinline uint32 getAG() const throw() { return 0xff0000 | g; }
  17371. forcedinline uint8 getAlpha() const throw() { return 0xff; }
  17372. forcedinline uint8 getRed() const throw() { return r; }
  17373. forcedinline uint8 getGreen() const throw() { return g; }
  17374. forcedinline uint8 getBlue() const throw() { return b; }
  17375. /** Blends another pixel onto this one.
  17376. This takes into account the opacity of the pixel being overlaid, and blends
  17377. it accordingly.
  17378. */
  17379. forcedinline void blend (const PixelARGB& src) throw()
  17380. {
  17381. uint32 sargb = src.getARGB();
  17382. const uint32 alpha = 0x100 - (sargb >> 24);
  17383. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17384. sargb += 0x0000ff00 & (g * alpha);
  17385. r = (uint8) (sargb >> 16);
  17386. g = (uint8) (sargb >> 8);
  17387. b = (uint8) sargb;
  17388. }
  17389. forcedinline void blend (const PixelRGB& src) throw()
  17390. {
  17391. set (src);
  17392. }
  17393. forcedinline void blend (const PixelAlpha& src) throw();
  17394. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17395. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17396. being used, so this can blend semi-transparently from a PixelRGB argument.
  17397. */
  17398. template <class Pixel>
  17399. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17400. {
  17401. ++extraAlpha;
  17402. const uint32 srb = (extraAlpha * src.getRB()) >> 8;
  17403. const uint32 sag = extraAlpha * src.getAG();
  17404. uint32 sargb = (sag & 0xff00ff00) | (srb & 0x00ff00ff);
  17405. const uint32 alpha = 0x100 - (sargb >> 24);
  17406. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17407. sargb += 0x0000ff00 & (g * alpha);
  17408. b = (uint8) sargb;
  17409. g = (uint8) (sargb >> 8);
  17410. r = (uint8) (sargb >> 16);
  17411. }
  17412. /** Blends another pixel with this one, creating a colour that is somewhere
  17413. between the two, as specified by the amount.
  17414. */
  17415. template <class Pixel>
  17416. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17417. {
  17418. uint32 drb = getRB();
  17419. drb += (((src.getRB() - drb) * amount) >> 8);
  17420. uint32 dag = getAG();
  17421. dag += (((src.getAG() - dag) * amount) >> 8);
  17422. b = (uint8) drb;
  17423. g = (uint8) dag;
  17424. r = (uint8) (drb >> 16);
  17425. }
  17426. /** Copies another pixel colour over this one.
  17427. This doesn't blend it - this colour is simply replaced by the other one.
  17428. Because PixelRGB has no alpha channel, any alpha value in the source pixel
  17429. is thrown away.
  17430. */
  17431. template <class Pixel>
  17432. forcedinline void set (const Pixel& src) throw()
  17433. {
  17434. b = src.getBlue();
  17435. g = src.getGreen();
  17436. r = src.getRed();
  17437. }
  17438. /** This method is included for compatibility with the PixelARGB class. */
  17439. forcedinline void setAlpha (const uint8) throw() {}
  17440. /** Multiplies the colour's alpha value with another one. */
  17441. forcedinline void multiplyAlpha (int) throw() {}
  17442. /** Sets the pixel's colour from individual components. */
  17443. void setARGB (const uint8, const uint8 r_, const uint8 g_, const uint8 b_) throw()
  17444. {
  17445. r = r_;
  17446. g = g_;
  17447. b = b_;
  17448. }
  17449. /** Premultiplies the pixel's RGB values by its alpha. */
  17450. forcedinline void premultiply() throw() {}
  17451. /** Unpremultiplies the pixel's RGB values. */
  17452. forcedinline void unpremultiply() throw() {}
  17453. forcedinline void desaturate() throw()
  17454. {
  17455. r = g = b = (uint8) (((int) r + (int) g + (int) b) / 3);
  17456. }
  17457. /** The indexes of the different components in the byte layout of this type of colour. */
  17458. #if JUCE_MAC
  17459. enum { indexR = 0, indexG = 1, indexB = 2 };
  17460. #else
  17461. enum { indexR = 2, indexG = 1, indexB = 0 };
  17462. #endif
  17463. private:
  17464. #if JUCE_MAC
  17465. uint8 r, g, b;
  17466. #else
  17467. uint8 b, g, r;
  17468. #endif
  17469. } PACKED;
  17470. forcedinline void PixelARGB::blend (const PixelRGB& src) throw()
  17471. {
  17472. set (src);
  17473. }
  17474. /**
  17475. Represents an 8-bit single-channel pixel, and can perform compositing operations on it.
  17476. This is used internally by the imaging classes.
  17477. @see PixelARGB, PixelRGB
  17478. */
  17479. class JUCE_API PixelAlpha
  17480. {
  17481. public:
  17482. /** Creates a pixel without defining its colour. */
  17483. PixelAlpha() throw() {}
  17484. ~PixelAlpha() throw() {}
  17485. /** Creates a pixel from a 32-bit argb value.
  17486. (The argb format is that used by PixelARGB)
  17487. */
  17488. PixelAlpha (const uint32 argb) throw()
  17489. {
  17490. a = (uint8) (argb >> 24);
  17491. }
  17492. forcedinline uint32 getARGB() const throw() { return (((uint32) a) << 24) | (((uint32) a) << 16) | (((uint32) a) << 8) | a; }
  17493. forcedinline uint32 getRB() const throw() { return (((uint32) a) << 16) | a; }
  17494. forcedinline uint32 getAG() const throw() { return (((uint32) a) << 16) | a; }
  17495. forcedinline uint8 getAlpha() const throw() { return a; }
  17496. forcedinline uint8 getRed() const throw() { return 0; }
  17497. forcedinline uint8 getGreen() const throw() { return 0; }
  17498. forcedinline uint8 getBlue() const throw() { return 0; }
  17499. /** Blends another pixel onto this one.
  17500. This takes into account the opacity of the pixel being overlaid, and blends
  17501. it accordingly.
  17502. */
  17503. template <class Pixel>
  17504. forcedinline void blend (const Pixel& src) throw()
  17505. {
  17506. const int srcA = src.getAlpha();
  17507. a = (uint8) ((a * (0x100 - srcA) >> 8) + srcA);
  17508. }
  17509. /** Blends another pixel onto this one, applying an extra multiplier to its opacity.
  17510. The opacity of the pixel being overlaid is scaled by the extraAlpha factor before
  17511. being used, so this can blend semi-transparently from a PixelRGB argument.
  17512. */
  17513. template <class Pixel>
  17514. forcedinline void blend (const Pixel& src, uint32 extraAlpha) throw()
  17515. {
  17516. ++extraAlpha;
  17517. const int srcAlpha = (extraAlpha * src.getAlpha()) >> 8;
  17518. a = (uint8) ((a * (0x100 - srcAlpha) >> 8) + srcAlpha);
  17519. }
  17520. /** Blends another pixel with this one, creating a colour that is somewhere
  17521. between the two, as specified by the amount.
  17522. */
  17523. template <class Pixel>
  17524. forcedinline void tween (const Pixel& src, const uint32 amount) throw()
  17525. {
  17526. a += ((src,getAlpha() - a) * amount) >> 8;
  17527. }
  17528. /** Copies another pixel colour over this one.
  17529. This doesn't blend it - this colour is simply replaced by the other one.
  17530. */
  17531. template <class Pixel>
  17532. forcedinline void set (const Pixel& src) throw()
  17533. {
  17534. a = src.getAlpha();
  17535. }
  17536. /** Replaces the colour's alpha value with another one. */
  17537. forcedinline void setAlpha (const uint8 newAlpha) throw()
  17538. {
  17539. a = newAlpha;
  17540. }
  17541. /** Multiplies the colour's alpha value with another one. */
  17542. forcedinline void multiplyAlpha (int multiplier) throw()
  17543. {
  17544. ++multiplier;
  17545. a = (uint8) ((a * multiplier) >> 8);
  17546. }
  17547. forcedinline void multiplyAlpha (const float multiplier) throw()
  17548. {
  17549. a = (uint8) (a * multiplier);
  17550. }
  17551. /** Sets the pixel's colour from individual components. */
  17552. forcedinline void setARGB (const uint8 a_, const uint8 /*r*/, const uint8 /*g*/, const uint8 /*b*/) throw()
  17553. {
  17554. a = a_;
  17555. }
  17556. /** Premultiplies the pixel's RGB values by its alpha. */
  17557. forcedinline void premultiply() throw()
  17558. {
  17559. }
  17560. /** Unpremultiplies the pixel's RGB values. */
  17561. forcedinline void unpremultiply() throw()
  17562. {
  17563. }
  17564. forcedinline void desaturate() throw()
  17565. {
  17566. }
  17567. /** The indexes of the different components in the byte layout of this type of colour. */
  17568. enum { indexA = 0 };
  17569. private:
  17570. uint8 a : 8;
  17571. } PACKED;
  17572. forcedinline void PixelRGB::blend (const PixelAlpha& src) throw()
  17573. {
  17574. blend (PixelARGB (src.getARGB()));
  17575. }
  17576. forcedinline void PixelARGB::blend (const PixelAlpha& src) throw()
  17577. {
  17578. uint32 sargb = src.getARGB();
  17579. const uint32 alpha = 0x100 - (sargb >> 24);
  17580. sargb += 0x00ff00ff & ((getRB() * alpha) >> 8);
  17581. sargb += 0xff00ff00 & (getAG() * alpha);
  17582. argb = sargb;
  17583. }
  17584. #if JUCE_MSVC
  17585. #pragma pack (pop)
  17586. #endif
  17587. #undef PACKED
  17588. #endif // __JUCE_PIXELFORMATS_JUCEHEADER__
  17589. /*** End of inlined file: juce_PixelFormats.h ***/
  17590. /**
  17591. Represents a colour, also including a transparency value.
  17592. The colour is stored internally as unsigned 8-bit red, green, blue and alpha values.
  17593. */
  17594. class JUCE_API Colour
  17595. {
  17596. public:
  17597. /** Creates a transparent black colour. */
  17598. Colour() throw();
  17599. /** Creates a copy of another Colour object. */
  17600. Colour (const Colour& other) throw();
  17601. /** Creates a colour from a 32-bit ARGB value.
  17602. The format of this number is:
  17603. ((alpha << 24) | (red << 16) | (green << 8) | blue).
  17604. All components in the range 0x00 to 0xff.
  17605. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17606. @see getPixelARGB
  17607. */
  17608. explicit Colour (uint32 argb) throw();
  17609. /** Creates an opaque colour using 8-bit red, green and blue values */
  17610. Colour (uint8 red,
  17611. uint8 green,
  17612. uint8 blue) throw();
  17613. /** Creates an opaque colour using 8-bit red, green and blue values */
  17614. static const Colour fromRGB (uint8 red,
  17615. uint8 green,
  17616. uint8 blue) throw();
  17617. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17618. Colour (uint8 red,
  17619. uint8 green,
  17620. uint8 blue,
  17621. uint8 alpha) throw();
  17622. /** Creates a colour using 8-bit red, green, blue and alpha values. */
  17623. static const Colour fromRGBA (uint8 red,
  17624. uint8 green,
  17625. uint8 blue,
  17626. uint8 alpha) throw();
  17627. /** Creates a colour from 8-bit red, green, and blue values, and a floating-point alpha.
  17628. Alpha of 0.0 is transparent, alpha of 1.0f is opaque.
  17629. Values outside the valid range will be clipped.
  17630. */
  17631. Colour (uint8 red,
  17632. uint8 green,
  17633. uint8 blue,
  17634. float alpha) throw();
  17635. /** Creates a colour using 8-bit red, green, blue and float alpha values. */
  17636. static const Colour fromRGBAFloat (uint8 red,
  17637. uint8 green,
  17638. uint8 blue,
  17639. float alpha) throw();
  17640. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17641. The floating point values must be between 0.0 and 1.0.
  17642. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17643. Values outside the valid range will be clipped.
  17644. */
  17645. Colour (float hue,
  17646. float saturation,
  17647. float brightness,
  17648. uint8 alpha) throw();
  17649. /** Creates a colour using floating point hue, saturation, brightness and alpha values.
  17650. All values must be between 0.0 and 1.0.
  17651. Numbers outside the valid range will be clipped.
  17652. */
  17653. Colour (float hue,
  17654. float saturation,
  17655. float brightness,
  17656. float alpha) throw();
  17657. /** Creates a colour using floating point hue, saturation and brightness values, and an 8-bit alpha.
  17658. The floating point values must be between 0.0 and 1.0.
  17659. An alpha of 0x00 is completely transparent, alpha of 0xff is opaque.
  17660. Values outside the valid range will be clipped.
  17661. */
  17662. static const Colour fromHSV (float hue,
  17663. float saturation,
  17664. float brightness,
  17665. float alpha) throw();
  17666. /** Destructor. */
  17667. ~Colour() throw();
  17668. /** Copies another Colour object. */
  17669. Colour& operator= (const Colour& other) throw();
  17670. /** Compares two colours. */
  17671. bool operator== (const Colour& other) const throw();
  17672. /** Compares two colours. */
  17673. bool operator!= (const Colour& other) const throw();
  17674. /** Returns the red component of this colour.
  17675. @returns a value between 0x00 and 0xff.
  17676. */
  17677. uint8 getRed() const throw() { return argb.getRed(); }
  17678. /** Returns the green component of this colour.
  17679. @returns a value between 0x00 and 0xff.
  17680. */
  17681. uint8 getGreen() const throw() { return argb.getGreen(); }
  17682. /** Returns the blue component of this colour.
  17683. @returns a value between 0x00 and 0xff.
  17684. */
  17685. uint8 getBlue() const throw() { return argb.getBlue(); }
  17686. /** Returns the red component of this colour as a floating point value.
  17687. @returns a value between 0.0 and 1.0
  17688. */
  17689. float getFloatRed() const throw();
  17690. /** Returns the green component of this colour as a floating point value.
  17691. @returns a value between 0.0 and 1.0
  17692. */
  17693. float getFloatGreen() const throw();
  17694. /** Returns the blue component of this colour as a floating point value.
  17695. @returns a value between 0.0 and 1.0
  17696. */
  17697. float getFloatBlue() const throw();
  17698. /** Returns a premultiplied ARGB pixel object that represents this colour.
  17699. */
  17700. const PixelARGB getPixelARGB() const throw();
  17701. /** Returns a 32-bit integer that represents this colour.
  17702. The format of this number is:
  17703. ((alpha << 24) | (red << 16) | (green << 16) | blue).
  17704. */
  17705. uint32 getARGB() const throw();
  17706. /** Returns the colour's alpha (opacity).
  17707. Alpha of 0x00 is completely transparent, 0xff is completely opaque.
  17708. */
  17709. uint8 getAlpha() const throw() { return argb.getAlpha(); }
  17710. /** Returns the colour's alpha (opacity) as a floating point value.
  17711. Alpha of 0.0 is completely transparent, 1.0 is completely opaque.
  17712. */
  17713. float getFloatAlpha() const throw();
  17714. /** Returns true if this colour is completely opaque.
  17715. Equivalent to (getAlpha() == 0xff).
  17716. */
  17717. bool isOpaque() const throw();
  17718. /** Returns true if this colour is completely transparent.
  17719. Equivalent to (getAlpha() == 0x00).
  17720. */
  17721. bool isTransparent() const throw();
  17722. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17723. const Colour withAlpha (uint8 newAlpha) const throw();
  17724. /** Returns a colour that's the same colour as this one, but with a new alpha value. */
  17725. const Colour withAlpha (float newAlpha) const throw();
  17726. /** Returns a colour that's the same colour as this one, but with a modified alpha value.
  17727. The new colour's alpha will be this object's alpha multiplied by the value passed-in.
  17728. */
  17729. const Colour withMultipliedAlpha (float alphaMultiplier) const throw();
  17730. /** Returns a colour that is the result of alpha-compositing a new colour over this one.
  17731. If the foreground colour is semi-transparent, it is blended onto this colour
  17732. accordingly.
  17733. */
  17734. const Colour overlaidWith (const Colour& foregroundColour) const throw();
  17735. /** Returns a colour that lies somewhere between this one and another.
  17736. If amountOfOther is zero, the result is 100% this colour, if amountOfOther
  17737. is 1.0, the result is 100% of the other colour.
  17738. */
  17739. const Colour interpolatedWith (const Colour& other, float proportionOfOther) const throw();
  17740. /** Returns the colour's hue component.
  17741. The value returned is in the range 0.0 to 1.0
  17742. */
  17743. float getHue() const throw();
  17744. /** Returns the colour's saturation component.
  17745. The value returned is in the range 0.0 to 1.0
  17746. */
  17747. float getSaturation() const throw();
  17748. /** Returns the colour's brightness component.
  17749. The value returned is in the range 0.0 to 1.0
  17750. */
  17751. float getBrightness() const throw();
  17752. /** Returns the colour's hue, saturation and brightness components all at once.
  17753. The values returned are in the range 0.0 to 1.0
  17754. */
  17755. void getHSB (float& hue,
  17756. float& saturation,
  17757. float& brightness) const throw();
  17758. /** Returns a copy of this colour with a different hue. */
  17759. const Colour withHue (float newHue) const throw();
  17760. /** Returns a copy of this colour with a different saturation. */
  17761. const Colour withSaturation (float newSaturation) const throw();
  17762. /** Returns a copy of this colour with a different brightness.
  17763. @see brighter, darker, withMultipliedBrightness
  17764. */
  17765. const Colour withBrightness (float newBrightness) const throw();
  17766. /** Returns a copy of this colour with it hue rotated.
  17767. The new colour's hue is ((this->getHue() + amountToRotate) % 1.0)
  17768. @see brighter, darker, withMultipliedBrightness
  17769. */
  17770. const Colour withRotatedHue (float amountToRotate) const throw();
  17771. /** Returns a copy of this colour with its saturation multiplied by the given value.
  17772. The new colour's saturation is (this->getSaturation() * multiplier)
  17773. (the result is clipped to legal limits).
  17774. */
  17775. const Colour withMultipliedSaturation (float multiplier) const throw();
  17776. /** Returns a copy of this colour with its brightness multiplied by the given value.
  17777. The new colour's saturation is (this->getBrightness() * multiplier)
  17778. (the result is clipped to legal limits).
  17779. */
  17780. const Colour withMultipliedBrightness (float amount) const throw();
  17781. /** Returns a brighter version of this colour.
  17782. @param amountBrighter how much brighter to make it - a value from 0 to 1.0 where 0 is
  17783. unchanged, and higher values make it brighter
  17784. @see withMultipliedBrightness
  17785. */
  17786. const Colour brighter (float amountBrighter = 0.4f) const throw();
  17787. /** Returns a darker version of this colour.
  17788. @param amountDarker how much darker to make it - a value from 0 to 1.0 where 0 is
  17789. unchanged, and higher values make it darker
  17790. @see withMultipliedBrightness
  17791. */
  17792. const Colour darker (float amountDarker = 0.4f) const throw();
  17793. /** Returns a colour that will be clearly visible against this colour.
  17794. The amount parameter indicates how contrasting the new colour should
  17795. be, so e.g. Colours::black.contrasting (0.1f) will return a colour
  17796. that's just a little bit lighter; Colours::black.contrasting (1.0f) will
  17797. return white; Colours::white.contrasting (1.0f) will return black, etc.
  17798. */
  17799. const Colour contrasting (float amount = 1.0f) const throw();
  17800. /** Returns a colour that contrasts against two colours.
  17801. Looks for a colour that contrasts with both of the colours passed-in.
  17802. Handy for things like choosing a highlight colour in text editors, etc.
  17803. */
  17804. static const Colour contrasting (const Colour& colour1,
  17805. const Colour& colour2) throw();
  17806. /** Returns an opaque shade of grey.
  17807. @param brightness the level of grey to return - 0 is black, 1.0 is white
  17808. */
  17809. static const Colour greyLevel (float brightness) throw();
  17810. /** Returns a stringified version of this colour.
  17811. The string can be turned back into a colour using the fromString() method.
  17812. */
  17813. const String toString() const;
  17814. /** Reads the colour from a string that was created with toString().
  17815. */
  17816. static const Colour fromString (const String& encodedColourString);
  17817. /** Returns the colour as a hex string in the form RRGGBB or AARRGGBB. */
  17818. const String toDisplayString (bool includeAlphaValue) const;
  17819. juce_UseDebuggingNewOperator
  17820. private:
  17821. PixelARGB argb;
  17822. };
  17823. #endif // __JUCE_COLOUR_JUCEHEADER__
  17824. /*** End of inlined file: juce_Colour.h ***/
  17825. /**
  17826. Contains a set of predefined named colours (mostly standard HTML colours)
  17827. @see Colour, Colours::greyLevel
  17828. */
  17829. class Colours
  17830. {
  17831. public:
  17832. static JUCE_API const Colour
  17833. transparentBlack, /**< ARGB = 0x00000000 */
  17834. transparentWhite, /**< ARGB = 0x00ffffff */
  17835. black, /**< ARGB = 0xff000000 */
  17836. white, /**< ARGB = 0xffffffff */
  17837. blue, /**< ARGB = 0xff0000ff */
  17838. grey, /**< ARGB = 0xff808080 */
  17839. green, /**< ARGB = 0xff008000 */
  17840. red, /**< ARGB = 0xffff0000 */
  17841. yellow, /**< ARGB = 0xffffff00 */
  17842. aliceblue, antiquewhite, aqua, aquamarine,
  17843. azure, beige, bisque, blanchedalmond,
  17844. blueviolet, brown, burlywood, cadetblue,
  17845. chartreuse, chocolate, coral, cornflowerblue,
  17846. cornsilk, crimson, cyan, darkblue,
  17847. darkcyan, darkgoldenrod, darkgrey, darkgreen,
  17848. darkkhaki, darkmagenta, darkolivegreen, darkorange,
  17849. darkorchid, darkred, darksalmon, darkseagreen,
  17850. darkslateblue, darkslategrey, darkturquoise, darkviolet,
  17851. deeppink, deepskyblue, dimgrey, dodgerblue,
  17852. firebrick, floralwhite, forestgreen, fuchsia,
  17853. gainsboro, gold, goldenrod, greenyellow,
  17854. honeydew, hotpink, indianred, indigo,
  17855. ivory, khaki, lavender, lavenderblush,
  17856. lemonchiffon, lightblue, lightcoral, lightcyan,
  17857. lightgoldenrodyellow, lightgreen, lightgrey, lightpink,
  17858. lightsalmon, lightseagreen, lightskyblue, lightslategrey,
  17859. lightsteelblue, lightyellow, lime, limegreen,
  17860. linen, magenta, maroon, mediumaquamarine,
  17861. mediumblue, mediumorchid, mediumpurple, mediumseagreen,
  17862. mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred,
  17863. midnightblue, mintcream, mistyrose, navajowhite,
  17864. navy, oldlace, olive, olivedrab,
  17865. orange, orangered, orchid, palegoldenrod,
  17866. palegreen, paleturquoise, palevioletred, papayawhip,
  17867. peachpuff, peru, pink, plum,
  17868. powderblue, purple, rosybrown, royalblue,
  17869. saddlebrown, salmon, sandybrown, seagreen,
  17870. seashell, sienna, silver, skyblue,
  17871. slateblue, slategrey, snow, springgreen,
  17872. steelblue, tan, teal, thistle,
  17873. tomato, turquoise, violet, wheat,
  17874. whitesmoke, yellowgreen;
  17875. /** Attempts to look up a string in the list of known colour names, and return
  17876. the appropriate colour.
  17877. A non-case-sensitive search is made of the list of predefined colours, and
  17878. if a match is found, that colour is returned. If no match is found, the
  17879. colour passed in as the defaultColour parameter is returned.
  17880. */
  17881. static JUCE_API const Colour findColourForName (const String& colourName,
  17882. const Colour& defaultColour);
  17883. private:
  17884. // this isn't a class you should ever instantiate - it's just here for the
  17885. // static values in it.
  17886. Colours();
  17887. Colours (const Colours&);
  17888. Colours& operator= (const Colours&);
  17889. };
  17890. #endif // __JUCE_COLOURS_JUCEHEADER__
  17891. /*** End of inlined file: juce_Colours.h ***/
  17892. /*** Start of inlined file: juce_ColourGradient.h ***/
  17893. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  17894. #define __JUCE_COLOURGRADIENT_JUCEHEADER__
  17895. /**
  17896. Describes the layout and colours that should be used to paint a colour gradient.
  17897. @see Graphics::setGradientFill
  17898. */
  17899. class JUCE_API ColourGradient
  17900. {
  17901. public:
  17902. /** Creates a gradient object.
  17903. (x1, y1) is the location to draw with colour1. Likewise (x2, y2) is where
  17904. colour2 should be. In between them there's a gradient.
  17905. If isRadial is true, the colours form a circular gradient with (x1, y1) at
  17906. its centre.
  17907. The alpha transparencies of the colours are used, so note that
  17908. if you blend from transparent to a solid colour, the RGB of the transparent
  17909. colour will become visible in parts of the gradient. e.g. blending
  17910. from Colour::transparentBlack to Colours::white will produce a
  17911. muddy grey colour midway, but Colour::transparentWhite to Colours::white
  17912. will be white all the way across.
  17913. @see ColourGradient
  17914. */
  17915. ColourGradient (const Colour& colour1, float x1, float y1,
  17916. const Colour& colour2, float x2, float y2,
  17917. bool isRadial);
  17918. /** Creates an uninitialised gradient.
  17919. If you use this constructor instead of the other one, be sure to set all the
  17920. object's public member variables before using it!
  17921. */
  17922. ColourGradient() throw();
  17923. /** Destructor */
  17924. ~ColourGradient();
  17925. /** Removes any colours that have been added.
  17926. This will also remove any start and end colours, so the gradient won't work. You'll
  17927. need to add more colours with addColour().
  17928. */
  17929. void clearColours();
  17930. /** Adds a colour at a point along the length of the gradient.
  17931. This allows the gradient to go through a spectrum of colours, instead of just a
  17932. start and end colour.
  17933. @param proportionAlongGradient a value between 0 and 1.0, which is the proportion
  17934. of the distance along the line between the two points
  17935. at which the colour should occur.
  17936. @param colour the colour that should be used at this point
  17937. @returns the index at which the new point was added
  17938. */
  17939. int addColour (double proportionAlongGradient,
  17940. const Colour& colour);
  17941. /** Removes one of the colours from the gradient. */
  17942. void removeColour (int index);
  17943. /** Multiplies the alpha value of all the colours by the given scale factor */
  17944. void multiplyOpacity (float multiplier) throw();
  17945. /** Returns the number of colour-stops that have been added. */
  17946. int getNumColours() const throw();
  17947. /** Returns the position along the length of the gradient of the colour with this index.
  17948. The index is from 0 to getNumColours() - 1. The return value will be between 0.0 and 1.0
  17949. */
  17950. double getColourPosition (int index) const throw();
  17951. /** Returns the colour that was added with a given index.
  17952. The index is from 0 to getNumColours() - 1.
  17953. */
  17954. const Colour getColour (int index) const throw();
  17955. /** Changes the colour at a given index.
  17956. The index is from 0 to getNumColours() - 1.
  17957. */
  17958. void setColour (int index, const Colour& newColour) throw();
  17959. /** Returns the an interpolated colour at any position along the gradient.
  17960. @param position the position along the gradient, between 0 and 1
  17961. */
  17962. const Colour getColourAtPosition (double position) const throw();
  17963. /** Creates a set of interpolated premultiplied ARGB values.
  17964. This will resize the HeapBlock, fill it with the colours, and will return the number of
  17965. colours that it added.
  17966. */
  17967. int createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& resultLookupTable) const;
  17968. /** Returns true if all colours are opaque. */
  17969. bool isOpaque() const throw();
  17970. /** Returns true if all colours are completely transparent. */
  17971. bool isInvisible() const throw();
  17972. Point<float> point1, point2;
  17973. /** If true, the gradient should be filled circularly, centred around
  17974. point1, with point2 defining a point on the circumference.
  17975. If false, the gradient is linear between the two points.
  17976. */
  17977. bool isRadial;
  17978. bool operator== (const ColourGradient& other) const throw();
  17979. bool operator!= (const ColourGradient& other) const throw();
  17980. juce_UseDebuggingNewOperator
  17981. private:
  17982. struct ColourPoint
  17983. {
  17984. ColourPoint() throw() {}
  17985. ColourPoint (const double position_, const Colour& colour_) throw()
  17986. : position (position_), colour (colour_)
  17987. {}
  17988. bool operator== (const ColourPoint& other) const throw() { return position == other.position && colour == other.colour; }
  17989. bool operator!= (const ColourPoint& other) const throw() { return position != other.position || colour != other.colour; }
  17990. double position;
  17991. Colour colour;
  17992. };
  17993. Array <ColourPoint> colours;
  17994. };
  17995. #endif // __JUCE_COLOURGRADIENT_JUCEHEADER__
  17996. /*** End of inlined file: juce_ColourGradient.h ***/
  17997. /*** Start of inlined file: juce_RectanglePlacement.h ***/
  17998. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  17999. #define __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  18000. /**
  18001. Defines the method used to postion some kind of rectangular object within
  18002. a rectangular viewport.
  18003. Although similar to Justification, this is more specific, and has some extra
  18004. options.
  18005. */
  18006. class JUCE_API RectanglePlacement
  18007. {
  18008. public:
  18009. /** Creates a RectanglePlacement object using a combination of flags. */
  18010. inline RectanglePlacement (int flags_) throw() : flags (flags_) {}
  18011. /** Creates a copy of another RectanglePlacement object. */
  18012. RectanglePlacement (const RectanglePlacement& other) throw();
  18013. /** Copies another RectanglePlacement object. */
  18014. RectanglePlacement& operator= (const RectanglePlacement& other) throw();
  18015. /** Flag values that can be combined and used in the constructor. */
  18016. enum
  18017. {
  18018. /** Indicates that the source rectangle's left edge should be aligned with the left edge of the target rectangle. */
  18019. xLeft = 1,
  18020. /** Indicates that the source rectangle's right edge should be aligned with the right edge of the target rectangle. */
  18021. xRight = 2,
  18022. /** Indicates that the source should be placed in the centre between the left and right
  18023. sides of the available space. */
  18024. xMid = 4,
  18025. /** Indicates that the source's top edge should be aligned with the top edge of the
  18026. destination rectangle. */
  18027. yTop = 8,
  18028. /** Indicates that the source's bottom edge should be aligned with the bottom edge of the
  18029. destination rectangle. */
  18030. yBottom = 16,
  18031. /** Indicates that the source should be placed in the centre between the top and bottom
  18032. sides of the available space. */
  18033. yMid = 32,
  18034. /** If this flag is set, then the source rectangle will be resized to completely fill
  18035. the destination rectangle, and all other flags are ignored.
  18036. */
  18037. stretchToFit = 64,
  18038. /** If this flag is set, then the source rectangle will be resized so that it is the
  18039. minimum size to completely fill the destination rectangle, without changing its
  18040. aspect ratio. This means that some of the source rectangle may fall outside
  18041. the destination.
  18042. If this flag is not set, the source will be given the maximum size at which none
  18043. of it falls outside the destination rectangle.
  18044. */
  18045. fillDestination = 128,
  18046. /** Indicates that the source rectangle can be reduced in size if required, but should
  18047. never be made larger than its original size.
  18048. */
  18049. onlyReduceInSize = 256,
  18050. /** Indicates that the source rectangle can be enlarged if required, but should
  18051. never be made smaller than its original size.
  18052. */
  18053. onlyIncreaseInSize = 512,
  18054. /** Indicates that the source rectangle's size should be left unchanged.
  18055. */
  18056. doNotResize = (onlyIncreaseInSize | onlyReduceInSize),
  18057. /** A shorthand value that is equivalent to (xMid | yMid). */
  18058. centred = 4 + 32
  18059. };
  18060. /** Returns the raw flags that are set for this object. */
  18061. inline int getFlags() const throw() { return flags; }
  18062. /** Tests a set of flags for this object.
  18063. @returns true if any of the flags passed in are set on this object.
  18064. */
  18065. inline bool testFlags (int flagsToTest) const throw() { return (flags & flagsToTest) != 0; }
  18066. /** Adjusts the position and size of a rectangle to fit it into a space.
  18067. The source rectangle co-ordinates will be adjusted so that they fit into
  18068. the destination rectangle based on this object's flags.
  18069. */
  18070. void applyTo (double& sourceX,
  18071. double& sourceY,
  18072. double& sourceW,
  18073. double& sourceH,
  18074. double destinationX,
  18075. double destinationY,
  18076. double destinationW,
  18077. double destinationH) const throw();
  18078. /** Returns the transform that should be applied to these source co-ordinates to fit them
  18079. into the destination rectangle using the current flags.
  18080. */
  18081. const AffineTransform getTransformToFit (float sourceX,
  18082. float sourceY,
  18083. float sourceW,
  18084. float sourceH,
  18085. float destinationX,
  18086. float destinationY,
  18087. float destinationW,
  18088. float destinationH) const throw();
  18089. private:
  18090. int flags;
  18091. };
  18092. #endif // __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  18093. /*** End of inlined file: juce_RectanglePlacement.h ***/
  18094. class LowLevelGraphicsContext;
  18095. class Image;
  18096. class FillType;
  18097. class RectangleList;
  18098. /**
  18099. A graphics context, used for drawing a component or image.
  18100. When a Component needs painting, a Graphics context is passed to its
  18101. Component::paint() method, and this you then call methods within this
  18102. object to actually draw the component's content.
  18103. A Graphics can also be created from an image, to allow drawing directly onto
  18104. that image.
  18105. @see Component::paint
  18106. */
  18107. class JUCE_API Graphics
  18108. {
  18109. public:
  18110. /** Creates a Graphics object to draw directly onto the given image.
  18111. The graphics object that is created will be set up to draw onto the image,
  18112. with the context's clipping area being the entire size of the image, and its
  18113. origin being the image's origin. To draw into a subsection of an image, use the
  18114. reduceClipRegion() and setOrigin() methods.
  18115. Obviously you shouldn't delete the image before this context is deleted.
  18116. */
  18117. explicit Graphics (const Image& imageToDrawOnto);
  18118. /** Destructor. */
  18119. ~Graphics();
  18120. /** Changes the current drawing colour.
  18121. This sets the colour that will now be used for drawing operations - it also
  18122. sets the opacity to that of the colour passed-in.
  18123. If a brush is being used when this method is called, the brush will be deselected,
  18124. and any subsequent drawing will be done with a solid colour brush instead.
  18125. @see setOpacity
  18126. */
  18127. void setColour (const Colour& newColour);
  18128. /** Changes the opacity to use with the current colour.
  18129. If a solid colour is being used for drawing, this changes its opacity
  18130. to this new value (i.e. it doesn't multiply the colour's opacity by this amount).
  18131. If a gradient is being used, this will have no effect on it.
  18132. A value of 0.0 is completely transparent, 1.0 is completely opaque.
  18133. */
  18134. void setOpacity (const float newOpacity);
  18135. /** Sets the context to use a gradient for its fill pattern.
  18136. */
  18137. void setGradientFill (const ColourGradient& gradient);
  18138. /** Sets the context to use a tiled image pattern for filling.
  18139. Make sure that you don't delete this image while it's still being used by
  18140. this context!
  18141. */
  18142. void setTiledImageFill (const Image& imageToUse,
  18143. int anchorX, int anchorY,
  18144. float opacity);
  18145. /** Changes the current fill settings.
  18146. @see setColour, setGradientFill, setTiledImageFill
  18147. */
  18148. void setFillType (const FillType& newFill);
  18149. /** Changes the font to use for subsequent text-drawing functions.
  18150. Note there's also a setFont (float, int) method to quickly change the size and
  18151. style of the current font.
  18152. @see drawSingleLineText, drawMultiLineText, drawTextAsPath, drawText, drawFittedText
  18153. */
  18154. void setFont (const Font& newFont);
  18155. /** Changes the size and style of the currently-selected font.
  18156. This is a convenient shortcut that changes the context's current font to a
  18157. different size or style. The typeface won't be changed.
  18158. @see Font
  18159. */
  18160. void setFont (float newFontHeight, int fontStyleFlags = Font::plain);
  18161. /** Returns the currently selected font. */
  18162. const Font getCurrentFont() const;
  18163. /** Draws a one-line text string.
  18164. This will use the current colour (or brush) to fill the text. The font is the last
  18165. one specified by setFont().
  18166. @param text the string to draw
  18167. @param startX the position to draw the left-hand edge of the text
  18168. @param baselineY the position of the text's baseline
  18169. @see drawMultiLineText, drawText, drawFittedText, GlyphArrangement::addLineOfText
  18170. */
  18171. void drawSingleLineText (const String& text,
  18172. int startX, int baselineY) const;
  18173. /** Draws text across multiple lines.
  18174. This will break the text onto a new line where there's a new-line or
  18175. carriage-return character, or at a word-boundary when the text becomes wider
  18176. than the size specified by the maximumLineWidth parameter.
  18177. @see setFont, drawSingleLineText, drawFittedText, GlyphArrangement::addJustifiedText
  18178. */
  18179. void drawMultiLineText (const String& text,
  18180. int startX, int baselineY,
  18181. int maximumLineWidth) const;
  18182. /** Renders a string of text as a vector path.
  18183. This allows a string to be transformed with an arbitrary AffineTransform and
  18184. rendered using the current colour/brush. It's much slower than the normal text methods
  18185. but more accurate.
  18186. @see setFont
  18187. */
  18188. void drawTextAsPath (const String& text,
  18189. const AffineTransform& transform) const;
  18190. /** Draws a line of text within a specified rectangle.
  18191. The text will be positioned within the rectangle based on the justification
  18192. flags passed-in. If the string is too long to fit inside the rectangle, it will
  18193. either be truncated or will have ellipsis added to its end (if the useEllipsesIfTooBig
  18194. flag is true).
  18195. @see drawSingleLineText, drawFittedText, drawMultiLineText, GlyphArrangement::addJustifiedText
  18196. */
  18197. void drawText (const String& text,
  18198. int x, int y, int width, int height,
  18199. const Justification& justificationType,
  18200. bool useEllipsesIfTooBig) const;
  18201. /** Tries to draw a text string inside a given space.
  18202. This does its best to make the given text readable within the specified rectangle,
  18203. so it useful for labelling things.
  18204. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  18205. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  18206. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  18207. it's been truncated.
  18208. A Justification parameter lets you specify how the text is laid out within the rectangle,
  18209. both horizontally and vertically.
  18210. The minimumHorizontalScale parameter specifies how much the text can be squashed horizontally
  18211. to try to squeeze it into the space. If you don't want any horizontal scaling to occur, you
  18212. can set this value to 1.0f.
  18213. @see GlyphArrangement::addFittedText
  18214. */
  18215. void drawFittedText (const String& text,
  18216. int x, int y, int width, int height,
  18217. const Justification& justificationFlags,
  18218. int maximumNumberOfLines,
  18219. float minimumHorizontalScale = 0.7f) const;
  18220. /** Fills the context's entire clip region with the current colour or brush.
  18221. (See also the fillAll (const Colour&) method which is a quick way of filling
  18222. it with a given colour).
  18223. */
  18224. void fillAll() const;
  18225. /** Fills the context's entire clip region with a given colour.
  18226. This leaves the context's current colour and brush unchanged, it just
  18227. uses the specified colour temporarily.
  18228. */
  18229. void fillAll (const Colour& colourToUse) const;
  18230. /** Fills a rectangle with the current colour or brush.
  18231. @see drawRect, fillRoundedRectangle
  18232. */
  18233. void fillRect (int x, int y, int width, int height) const;
  18234. /** Fills a rectangle with the current colour or brush. */
  18235. void fillRect (const Rectangle<int>& rectangle) const;
  18236. /** Fills a rectangle with the current colour or brush.
  18237. This uses sub-pixel positioning so is slower than the fillRect method which
  18238. takes integer co-ordinates.
  18239. */
  18240. void fillRect (float x, float y, float width, float height) const;
  18241. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18242. @see drawRoundedRectangle, Path::addRoundedRectangle
  18243. */
  18244. void fillRoundedRectangle (float x, float y, float width, float height,
  18245. float cornerSize) const;
  18246. /** Uses the current colour or brush to fill a rectangle with rounded corners.
  18247. @see drawRoundedRectangle, Path::addRoundedRectangle
  18248. */
  18249. void fillRoundedRectangle (const Rectangle<float>& rectangle,
  18250. float cornerSize) const;
  18251. /** Fills a rectangle with a checkerboard pattern, alternating between two colours.
  18252. */
  18253. void fillCheckerBoard (const Rectangle<int>& area,
  18254. int checkWidth, int checkHeight,
  18255. const Colour& colour1, const Colour& colour2) const;
  18256. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18257. The lines are drawn inside the given rectangle, and greater line thicknesses
  18258. extend inwards.
  18259. @see fillRect
  18260. */
  18261. void drawRect (int x, int y, int width, int height,
  18262. int lineThickness = 1) const;
  18263. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18264. The lines are drawn inside the given rectangle, and greater line thicknesses
  18265. extend inwards.
  18266. @see fillRect
  18267. */
  18268. void drawRect (float x, float y, float width, float height,
  18269. float lineThickness = 1.0f) const;
  18270. /** Draws four lines to form a rectangular outline, using the current colour or brush.
  18271. The lines are drawn inside the given rectangle, and greater line thicknesses
  18272. extend inwards.
  18273. @see fillRect
  18274. */
  18275. void drawRect (const Rectangle<int>& rectangle,
  18276. int lineThickness = 1) const;
  18277. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18278. @see fillRoundedRectangle, Path::addRoundedRectangle
  18279. */
  18280. void drawRoundedRectangle (float x, float y, float width, float height,
  18281. float cornerSize, float lineThickness) const;
  18282. /** Uses the current colour or brush to draw the outline of a rectangle with rounded corners.
  18283. @see fillRoundedRectangle, Path::addRoundedRectangle
  18284. */
  18285. void drawRoundedRectangle (const Rectangle<float>& rectangle,
  18286. float cornerSize, float lineThickness) const;
  18287. /** Draws a 3D raised (or indented) bevel using two colours.
  18288. The bevel is drawn inside the given rectangle, and greater bevel thicknesses
  18289. extend inwards.
  18290. The top-left colour is used for the top- and left-hand edges of the
  18291. bevel; the bottom-right colour is used for the bottom- and right-hand
  18292. edges.
  18293. If useGradient is true, then the bevel fades out to make it look more curved
  18294. and less angular. If sharpEdgeOnOutside is true, the outside of the bevel is
  18295. sharp, and it fades towards the centre; if sharpEdgeOnOutside is false, then
  18296. the centre edges are sharp and it fades towards the outside.
  18297. */
  18298. void drawBevel (int x, int y, int width, int height,
  18299. int bevelThickness,
  18300. const Colour& topLeftColour = Colours::white,
  18301. const Colour& bottomRightColour = Colours::black,
  18302. bool useGradient = true,
  18303. bool sharpEdgeOnOutside = true) const;
  18304. /** Draws a pixel using the current colour or brush.
  18305. */
  18306. void setPixel (int x, int y) const;
  18307. /** Fills an ellipse with the current colour or brush.
  18308. The ellipse is drawn to fit inside the given rectangle.
  18309. @see drawEllipse, Path::addEllipse
  18310. */
  18311. void fillEllipse (float x, float y, float width, float height) const;
  18312. /** Draws an elliptical stroke using the current colour or brush.
  18313. @see fillEllipse, Path::addEllipse
  18314. */
  18315. void drawEllipse (float x, float y, float width, float height,
  18316. float lineThickness) const;
  18317. /** Draws a line between two points.
  18318. The line is 1 pixel wide and drawn with the current colour or brush.
  18319. */
  18320. void drawLine (float startX, float startY, float endX, float endY) const;
  18321. /** Draws a line between two points with a given thickness.
  18322. @see Path::addLineSegment
  18323. */
  18324. void drawLine (float startX, float startY, float endX, float endY,
  18325. float lineThickness) const;
  18326. /** Draws a line between two points.
  18327. The line is 1 pixel wide and drawn with the current colour or brush.
  18328. */
  18329. void drawLine (const Line<float>& line) const;
  18330. /** Draws a line between two points with a given thickness.
  18331. @see Path::addLineSegment
  18332. */
  18333. void drawLine (const Line<float>& line, float lineThickness) const;
  18334. /** Draws a dashed line using a custom set of dash-lengths.
  18335. @param startX the line's start x co-ordinate
  18336. @param startY the line's start y co-ordinate
  18337. @param endX the line's end x co-ordinate
  18338. @param endY the line's end y co-ordinate
  18339. @param dashLengths a series of lengths to specify the on/off lengths - e.g.
  18340. { 4, 5, 6, 7 } will draw a line of 4 pixels, skip 5 pixels,
  18341. draw 6 pixels, skip 7 pixels, and then repeat.
  18342. @param numDashLengths the number of elements in the array (this must be an even number).
  18343. @param lineThickness the thickness of the line to draw
  18344. @see PathStrokeType::createDashedStroke
  18345. */
  18346. void drawDashedLine (float startX, float startY,
  18347. float endX, float endY,
  18348. const float* dashLengths, int numDashLengths,
  18349. float lineThickness = 1.0f) const;
  18350. /** Draws a vertical line of pixels at a given x position.
  18351. The x position is an integer, but the top and bottom of the line can be sub-pixel
  18352. positions, and these will be anti-aliased if necessary.
  18353. */
  18354. void drawVerticalLine (int x, float top, float bottom) const;
  18355. /** Draws a horizontal line of pixels at a given y position.
  18356. The y position is an integer, but the left and right ends of the line can be sub-pixel
  18357. positions, and these will be anti-aliased if necessary.
  18358. */
  18359. void drawHorizontalLine (int y, float left, float right) const;
  18360. /** Fills a path using the currently selected colour or brush.
  18361. */
  18362. void fillPath (const Path& path,
  18363. const AffineTransform& transform = AffineTransform::identity) const;
  18364. /** Draws a path's outline using the currently selected colour or brush.
  18365. */
  18366. void strokePath (const Path& path,
  18367. const PathStrokeType& strokeType,
  18368. const AffineTransform& transform = AffineTransform::identity) const;
  18369. /** Draws a line with an arrowhead at its end.
  18370. @param line the line to draw
  18371. @param lineThickness the thickness of the line
  18372. @param arrowheadWidth the width of the arrow head (perpendicular to the line)
  18373. @param arrowheadLength the length of the arrow head (along the length of the line)
  18374. */
  18375. void drawArrow (const Line<float>& line,
  18376. float lineThickness,
  18377. float arrowheadWidth,
  18378. float arrowheadLength) const;
  18379. /** Types of rendering quality that can be specified when drawing images.
  18380. @see blendImage, Graphics::setImageResamplingQuality
  18381. */
  18382. enum ResamplingQuality
  18383. {
  18384. lowResamplingQuality = 0, /**< Just uses a nearest-neighbour algorithm for resampling. */
  18385. mediumResamplingQuality = 1, /**< Uses bilinear interpolation for upsampling and area-averaging for downsampling. */
  18386. highResamplingQuality = 2 /**< Uses bicubic interpolation for upsampling and area-averaging for downsampling. */
  18387. };
  18388. /** Changes the quality that will be used when resampling images.
  18389. By default a Graphics object will be set to mediumRenderingQuality.
  18390. @see Graphics::drawImage, Graphics::drawImageTransformed, Graphics::drawImageWithin
  18391. */
  18392. void setImageResamplingQuality (const ResamplingQuality newQuality);
  18393. /** Draws an image.
  18394. This will draw the whole of an image, positioning its top-left corner at the
  18395. given co-ordinates, and keeping its size the same. This is the simplest image
  18396. drawing method - the others give more control over the scaling and clipping
  18397. of the images.
  18398. Images are composited using the context's current opacity, so if you
  18399. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18400. (or setColour() with an opaque colour) before drawing images.
  18401. */
  18402. void drawImageAt (const Image& imageToDraw, int topLeftX, int topLeftY,
  18403. bool fillAlphaChannelWithCurrentBrush = false) const;
  18404. /** Draws part of an image, rescaling it to fit in a given target region.
  18405. The specified area of the source image is rescaled and drawn to fill the
  18406. specifed destination rectangle.
  18407. Images are composited using the context's current opacity, so if you
  18408. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18409. (or setColour() with an opaque colour) before drawing images.
  18410. @param imageToDraw the image to overlay
  18411. @param destX the left of the destination rectangle
  18412. @param destY the top of the destination rectangle
  18413. @param destWidth the width of the destination rectangle
  18414. @param destHeight the height of the destination rectangle
  18415. @param sourceX the left of the rectangle to copy from the source image
  18416. @param sourceY the top of the rectangle to copy from the source image
  18417. @param sourceWidth the width of the rectangle to copy from the source image
  18418. @param sourceHeight the height of the rectangle to copy from the source image
  18419. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the source image's pixels,
  18420. the source image's alpha channel is used as a mask with
  18421. which to fill the destination using the current colour
  18422. or brush. (If the source is has no alpha channel, then
  18423. it will just fill the target with a solid rectangle)
  18424. @see setImageResamplingQuality, drawImageAt, drawImageWithin, fillAlphaMap
  18425. */
  18426. void drawImage (const Image& imageToDraw,
  18427. int destX, int destY, int destWidth, int destHeight,
  18428. int sourceX, int sourceY, int sourceWidth, int sourceHeight,
  18429. bool fillAlphaChannelWithCurrentBrush = false) const;
  18430. /** Draws part of an image, having applied an affine transform to it.
  18431. This lets you throw the image around in some wacky ways, rotate it, shear,
  18432. scale it, etc.
  18433. A subregion is specified within the source image, and all transformations
  18434. will be treated as relative to the origin of this sub-region. So, for example if
  18435. your subregion is (50, 50, 100, 100), and your transform is a translation of (20, 20),
  18436. the resulting pixel drawn at (20, 20) in the destination context is from (50, 50) in
  18437. your image. If you want to use the whole image, then Image::getBounds() returns a
  18438. suitable rectangle to use as the imageSubRegion parameter.
  18439. Images are composited using the context's current opacity, so if you
  18440. don't want it to be drawn semi-transparently, be sure to call setOpacity (1.0f)
  18441. (or setColour() with an opaque colour) before drawing images.
  18442. If fillAlphaChannelWithCurrentBrush is set to true, then the image's RGB channels
  18443. are ignored and it is filled with the current brush, masked by its alpha channel.
  18444. @see setImageResamplingQuality, drawImage
  18445. */
  18446. void drawImageTransformed (const Image& imageToDraw,
  18447. const Rectangle<int>& imageSubRegion,
  18448. const AffineTransform& transform,
  18449. bool fillAlphaChannelWithCurrentBrush = false) const;
  18450. /** Draws an image to fit within a designated rectangle.
  18451. If the image is too big or too small for the space, it will be rescaled
  18452. to fit as nicely as it can do without affecting its aspect ratio. It will
  18453. then be placed within the target rectangle according to the justification flags
  18454. specified.
  18455. @param imageToDraw the source image to draw
  18456. @param destX top-left of the target rectangle to fit it into
  18457. @param destY top-left of the target rectangle to fit it into
  18458. @param destWidth size of the target rectangle to fit the image into
  18459. @param destHeight size of the target rectangle to fit the image into
  18460. @param placementWithinTarget this specifies how the image should be positioned
  18461. within the target rectangle - see the RectanglePlacement
  18462. class for more details about this.
  18463. @param fillAlphaChannelWithCurrentBrush if true, then instead of drawing the image, just its
  18464. alpha channel will be used as a mask with which to
  18465. draw with the current brush or colour. This is
  18466. similar to fillAlphaMap(), and see also drawImage()
  18467. @see setImageResamplingQuality, drawImage, drawImageTransformed, drawImageAt, RectanglePlacement
  18468. */
  18469. void drawImageWithin (const Image& imageToDraw,
  18470. int destX, int destY, int destWidth, int destHeight,
  18471. const RectanglePlacement& placementWithinTarget,
  18472. bool fillAlphaChannelWithCurrentBrush = false) const;
  18473. /** Returns the position of the bounding box for the current clipping region.
  18474. @see getClipRegion, clipRegionIntersects
  18475. */
  18476. const Rectangle<int> getClipBounds() const;
  18477. /** Checks whether a rectangle overlaps the context's clipping region.
  18478. If this returns false, no part of the given area can be drawn onto, so this
  18479. method can be used to optimise a component's paint() method, by letting it
  18480. avoid drawing complex objects that aren't within the region being repainted.
  18481. */
  18482. bool clipRegionIntersects (const Rectangle<int>& area) const;
  18483. /** Intersects the current clipping region with another region.
  18484. @returns true if the resulting clipping region is non-zero in size
  18485. @see setOrigin, clipRegionIntersects
  18486. */
  18487. bool reduceClipRegion (int x, int y, int width, int height);
  18488. /** Intersects the current clipping region with a rectangle list region.
  18489. @returns true if the resulting clipping region is non-zero in size
  18490. @see setOrigin, clipRegionIntersects
  18491. */
  18492. bool reduceClipRegion (const RectangleList& clipRegion);
  18493. /** Intersects the current clipping region with a path.
  18494. @returns true if the resulting clipping region is non-zero in size
  18495. @see reduceClipRegion
  18496. */
  18497. bool reduceClipRegion (const Path& path, const AffineTransform& transform = AffineTransform::identity);
  18498. /** Intersects the current clipping region with an image's alpha-channel.
  18499. The current clipping path is intersected with the area covered by this image's
  18500. alpha-channel, after the image has been transformed by the specified matrix.
  18501. @param image the image whose alpha-channel should be used. If the image doesn't
  18502. have an alpha-channel, it is treated as entirely opaque.
  18503. @param sourceClipRegion a subsection of the image that should be used. To use the
  18504. entire image, just pass a rectangle of bounds
  18505. (0, 0, image.getWidth(), image.getHeight()).
  18506. @param transform a matrix to apply to the image
  18507. @returns true if the resulting clipping region is non-zero in size
  18508. @see reduceClipRegion
  18509. */
  18510. bool reduceClipRegion (const Image& image, const Rectangle<int>& sourceClipRegion,
  18511. const AffineTransform& transform);
  18512. /** Excludes a rectangle to stop it being drawn into. */
  18513. void excludeClipRegion (const Rectangle<int>& rectangleToExclude);
  18514. /** Returns true if no drawing can be done because the clip region is zero. */
  18515. bool isClipEmpty() const;
  18516. /** Saves the current graphics state on an internal stack.
  18517. To restore the state, use restoreState().
  18518. */
  18519. void saveState();
  18520. /** Restores a graphics state that was previously saved with saveState().
  18521. */
  18522. void restoreState();
  18523. /** Moves the position of the context's origin.
  18524. This changes the position that the context considers to be (0, 0) to
  18525. the specified position.
  18526. So if you call setOrigin (100, 100), then the position that was previously
  18527. referred to as (100, 100) will subsequently be considered to be (0, 0).
  18528. @see reduceClipRegion
  18529. */
  18530. void setOrigin (int newOriginX, int newOriginY);
  18531. /** Resets the current colour, brush, and font to default settings. */
  18532. void resetToDefaultState();
  18533. /** Returns true if this context is drawing to a vector-based device, such as a printer. */
  18534. bool isVectorDevice() const;
  18535. juce_UseDebuggingNewOperator
  18536. /** Create a graphics that uses a given low-level renderer.
  18537. For internal use only.
  18538. NB. The context will NOT be deleted by this object when it is deleted.
  18539. */
  18540. Graphics (LowLevelGraphicsContext* const internalContext) throw();
  18541. /** @internal */
  18542. LowLevelGraphicsContext* getInternalContext() const throw() { return context; }
  18543. private:
  18544. LowLevelGraphicsContext* const context;
  18545. ScopedPointer <LowLevelGraphicsContext> contextToDelete;
  18546. bool saveStatePending;
  18547. void saveStateIfPending();
  18548. Graphics (const Graphics&);
  18549. Graphics& operator= (const Graphics& other);
  18550. };
  18551. #endif // __JUCE_GRAPHICS_JUCEHEADER__
  18552. /*** End of inlined file: juce_Graphics.h ***/
  18553. /**
  18554. A graphical effect filter that can be applied to components.
  18555. An ImageEffectFilter can be applied to the image that a component
  18556. paints before it hits the screen.
  18557. This is used for adding effects like shadows, blurs, etc.
  18558. @see Component::setComponentEffect
  18559. */
  18560. class JUCE_API ImageEffectFilter
  18561. {
  18562. public:
  18563. /** Overridden to render the effect.
  18564. The implementation of this method must use the image that is passed in
  18565. as its source, and should render its output to the graphics context passed in.
  18566. @param sourceImage the image that the source component has just rendered with
  18567. its paint() method. The image may or may not have an alpha
  18568. channel, depending on whether the component is opaque.
  18569. @param destContext the graphics context to use to draw the resultant image.
  18570. */
  18571. virtual void applyEffect (Image& sourceImage,
  18572. Graphics& destContext) = 0;
  18573. /** Destructor. */
  18574. virtual ~ImageEffectFilter() {}
  18575. };
  18576. #endif // __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  18577. /*** End of inlined file: juce_ImageEffectFilter.h ***/
  18578. /*** Start of inlined file: juce_Image.h ***/
  18579. #ifndef __JUCE_IMAGE_JUCEHEADER__
  18580. #define __JUCE_IMAGE_JUCEHEADER__
  18581. /**
  18582. Holds a fixed-size bitmap.
  18583. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  18584. To draw into an image, create a Graphics object for it.
  18585. e.g. @code
  18586. // create a transparent 500x500 image..
  18587. Image myImage (Image::RGB, 500, 500, true);
  18588. Graphics g (myImage);
  18589. g.setColour (Colours::red);
  18590. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  18591. @endcode
  18592. Other useful ways to create an image are with the ImageCache class, or the
  18593. ImageFileFormat, which provides a way to load common image files.
  18594. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  18595. */
  18596. class JUCE_API Image
  18597. {
  18598. public:
  18599. /**
  18600. */
  18601. enum PixelFormat
  18602. {
  18603. UnknownFormat,
  18604. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  18605. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  18606. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  18607. };
  18608. /**
  18609. */
  18610. enum ImageType
  18611. {
  18612. SoftwareImage = 0,
  18613. NativeImage
  18614. };
  18615. /** Creates a null image. */
  18616. Image();
  18617. /** Creates an image with a specified size and format.
  18618. @param format the number of colour channels in the image
  18619. @param imageWidth the desired width of the image, in pixels - this value must be
  18620. greater than zero (otherwise a width of 1 will be used)
  18621. @param imageHeight the desired width of the image, in pixels - this value must be
  18622. greater than zero (otherwise a height of 1 will be used)
  18623. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  18624. or transparent black (if it's ARGB). If false, the image may contain
  18625. junk initially, so you need to make sure you overwrite it thoroughly.
  18626. @param type the type of image - this lets you specify whether you want a purely
  18627. memory-based image, or one that may be managed by the OS if possible.
  18628. */
  18629. Image (PixelFormat format,
  18630. int imageWidth,
  18631. int imageHeight,
  18632. bool clearImage,
  18633. ImageType type = NativeImage);
  18634. /** Creates a shared reference to another image.
  18635. This won't create a duplicate of the image - when Image objects are copied, they simply
  18636. point to the same shared image data. To make sure that an Image object has its own unique,
  18637. unshared internal data, call duplicateIfShared().
  18638. */
  18639. Image (const Image& other);
  18640. /** Makes this image refer to the same underlying image as another object.
  18641. This won't create a duplicate of the image - when Image objects are copied, they simply
  18642. point to the same shared image data. To make sure that an Image object has its own unique,
  18643. unshared internal data, call duplicateIfShared().
  18644. */
  18645. Image& operator= (const Image&);
  18646. /** Destructor. */
  18647. ~Image();
  18648. /** Returns true if the two images are referring to the same internal, shared image. */
  18649. bool operator== (const Image& other) const throw() { return image == other.image; }
  18650. /** Returns true if the two images are not referring to the same internal, shared image. */
  18651. bool operator!= (const Image& other) const throw() { return image != other.image; }
  18652. /** Returns true if this image isn't null.
  18653. If you create an Image with the default constructor, it has no size or content, and is null
  18654. until you reassign it to an Image which contains some actual data.
  18655. The isNull() method is the opposite of isValid().
  18656. @see isNull
  18657. */
  18658. inline bool isValid() const throw() { return image != 0; }
  18659. /** Returns true if this image is not valid.
  18660. If you create an Image with the default constructor, it has no size or content, and is null
  18661. until you reassign it to an Image which contains some actual data.
  18662. The isNull() method is the opposite of isValid().
  18663. @see isValid
  18664. */
  18665. inline bool isNull() const throw() { return image == 0; }
  18666. /** Returns the image's width (in pixels). */
  18667. int getWidth() const throw() { return image == 0 ? 0 : image->width; }
  18668. /** Returns the image's height (in pixels). */
  18669. int getHeight() const throw() { return image == 0 ? 0 : image->height; }
  18670. /** Returns a rectangle with the same size as this image.
  18671. The rectangle's origin is always (0, 0).
  18672. */
  18673. const Rectangle<int> getBounds() const throw() { return image == 0 ? Rectangle<int>() : Rectangle<int> (image->width, image->height); }
  18674. /** Returns the image's pixel format. */
  18675. PixelFormat getFormat() const throw() { return image == 0 ? UnknownFormat : image->format; }
  18676. /** True if the image's format is ARGB. */
  18677. bool isARGB() const throw() { return getFormat() == ARGB; }
  18678. /** True if the image's format is RGB. */
  18679. bool isRGB() const throw() { return getFormat() == RGB; }
  18680. /** True if the image's format is a single-channel alpha map. */
  18681. bool isSingleChannel() const throw() { return getFormat() == SingleChannel; }
  18682. /** True if the image contains an alpha-channel. */
  18683. bool hasAlphaChannel() const throw() { return getFormat() != RGB; }
  18684. /** Clears a section of the image with a given colour.
  18685. This won't do any alpha-blending - it just sets all pixels in the image to
  18686. the given colour (which may be non-opaque if the image has an alpha channel).
  18687. */
  18688. void clear (const Rectangle<int>& area, const Colour& colourToClearTo = Colour (0x00000000));
  18689. /** Returns a rescaled version of this image.
  18690. A new image is returned which is a copy of this one, rescaled to the given size.
  18691. Note that if the new size is identical to the existing image, this will just return
  18692. a reference to the original image, and won't actually create a duplicate.
  18693. */
  18694. const Image rescaled (int newWidth, int newHeight,
  18695. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  18696. /** Returns a version of this image with a different image format.
  18697. A new image is returned which has been converted to the specified format.
  18698. Note that if the new format is no different to the current one, this will just return
  18699. a reference to the original image, and won't actually create a copy.
  18700. */
  18701. const Image convertedToFormat (PixelFormat newFormat) const;
  18702. /** Makes sure that no other Image objects share the same underlying data as this one.
  18703. If no other Image objects refer to the same shared data as this one, this method has no
  18704. effect. But if there are other references to the data, this will create a new copy of
  18705. the data internally.
  18706. Call this if you want to draw onto the image, but want to make sure that this doesn't
  18707. affect any other code that may be sharing the same data.
  18708. @see getReferenceCount
  18709. */
  18710. void duplicateIfShared();
  18711. /** Returns the colour of one of the pixels in the image.
  18712. If the co-ordinates given are beyond the image's boundaries, this will
  18713. return Colours::transparentBlack.
  18714. @see setPixelAt, Image::BitmapData::getPixelColour
  18715. */
  18716. const Colour getPixelAt (int x, int y) const;
  18717. /** Sets the colour of one of the image's pixels.
  18718. If the co-ordinates are beyond the image's boundaries, then nothing will happen.
  18719. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  18720. with the given one. The colour's opacity will be ignored if this image doesn't have
  18721. an alpha-channel.
  18722. @see getPixelAt, Image::BitmapData::setPixelColour
  18723. */
  18724. void setPixelAt (int x, int y, const Colour& colour);
  18725. /** Changes the opacity of a pixel.
  18726. This only has an effect if the image has an alpha channel and if the
  18727. given co-ordinates are inside the image's boundary.
  18728. The multiplier must be in the range 0 to 1.0, and the current alpha
  18729. at the given co-ordinates will be multiplied by this value.
  18730. @see setPixelAt
  18731. */
  18732. void multiplyAlphaAt (int x, int y, float multiplier);
  18733. /** Changes the overall opacity of the image.
  18734. This will multiply the alpha value of each pixel in the image by the given
  18735. amount (limiting the resulting alpha values between 0 and 255). This allows
  18736. you to make an image more or less transparent.
  18737. If the image doesn't have an alpha channel, this won't have any effect.
  18738. */
  18739. void multiplyAllAlphas (float amountToMultiplyBy);
  18740. /** Changes all the colours to be shades of grey, based on their current luminosity.
  18741. */
  18742. void desaturate();
  18743. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  18744. You should only use this class as a last resort - messing about with the internals of
  18745. an image is only recommended for people who really know what they're doing!
  18746. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  18747. hanging around while the image is being used elsewhere.
  18748. Depending on the way the image class is implemented, this may create a temporary buffer
  18749. which is copied back to the image when the object is deleted, or it may just get a pointer
  18750. directly into the image's raw data.
  18751. You can use the stride and data values in this class directly, but don't alter them!
  18752. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  18753. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  18754. */
  18755. class BitmapData
  18756. {
  18757. public:
  18758. BitmapData (Image& image, int x, int y, int w, int h, bool needsToBeWritable);
  18759. BitmapData (const Image& image, int x, int y, int w, int h);
  18760. ~BitmapData();
  18761. /** Returns a pointer to the start of a line in the image.
  18762. The co-ordinate you provide here isn't checked, so it's the caller's responsibility to make
  18763. sure it's not out-of-range.
  18764. */
  18765. inline uint8* getLinePointer (int y) const throw() { return data + y * lineStride; }
  18766. /** Returns a pointer to a pixel in the image.
  18767. The co-ordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  18768. not out-of-range.
  18769. */
  18770. inline uint8* getPixelPointer (int x, int y) const throw() { return data + y * lineStride + x * pixelStride; }
  18771. /** Returns the colour of a given pixel.
  18772. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18773. repsonsibility to make sure they're within the image's size.
  18774. */
  18775. const Colour getPixelColour (int x, int y) const throw();
  18776. /** Sets the colour of a given pixel.
  18777. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  18778. repsonsibility to make sure they're within the image's size.
  18779. */
  18780. void setPixelColour (int x, int y, const Colour& colour) const throw();
  18781. uint8* data;
  18782. const PixelFormat pixelFormat;
  18783. int lineStride, pixelStride, width, height;
  18784. private:
  18785. BitmapData (const BitmapData&);
  18786. BitmapData& operator= (const BitmapData&);
  18787. };
  18788. /** Copies some pixel values to a rectangle of the image.
  18789. The format of the pixel data must match that of the image itself, and the
  18790. rectangle supplied must be within the image's bounds.
  18791. */
  18792. void setPixelData (int destX, int destY, int destW, int destH,
  18793. const uint8* sourcePixelData, int sourceLineStride);
  18794. /** Copies a section of the image to somewhere else within itself. */
  18795. void moveImageSection (int destX, int destY,
  18796. int sourceX, int sourceY,
  18797. int width, int height);
  18798. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  18799. of the image.
  18800. @param result the list that will have the area added to it
  18801. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  18802. above this level will be considered opaque
  18803. */
  18804. void createSolidAreaMask (RectangleList& result,
  18805. float alphaThreshold = 0.5f) const;
  18806. /** Returns a user-specified data item that was set with setTag().
  18807. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18808. image. The value is shared between all Image object that are referring to the
  18809. same underlying image data object.
  18810. */
  18811. const var getTag() const;
  18812. /** Attaches a user-specified data item to this image, which can be retrieved using getTag().
  18813. setTag() and getTag() allow you to attach an arbitrary identifier value to an
  18814. image. The value is shared between all Image object that are referring to the
  18815. same underlying image data object.
  18816. Note that if this Image is null, this method will fail to store the data.
  18817. */
  18818. void setTag (const var& newTag);
  18819. /** Creates a context suitable for drawing onto this image.
  18820. Don't call this method directly! It's used internally by the Graphics class.
  18821. */
  18822. LowLevelGraphicsContext* createLowLevelContext() const;
  18823. /** Returns the number of Image objects which are currently referring to the same internal
  18824. shared image data.
  18825. @see duplicateIfShared
  18826. */
  18827. int getReferenceCount() const throw() { return image == 0 ? 0 : image->getReferenceCount(); }
  18828. /** This is a base class for task-specific types of image.
  18829. Don't use this class directly! It's used internally by the Image class.
  18830. */
  18831. class SharedImage : public ReferenceCountedObject
  18832. {
  18833. public:
  18834. SharedImage (PixelFormat format, int width, int height);
  18835. ~SharedImage();
  18836. virtual LowLevelGraphicsContext* createLowLevelContext() = 0;
  18837. virtual SharedImage* clone() = 0;
  18838. virtual ImageType getType() const = 0;
  18839. static SharedImage* createNativeImage (PixelFormat format, int width, int height, bool clearImage);
  18840. static SharedImage* createSoftwareImage (PixelFormat format, int width, int height, bool clearImage);
  18841. protected:
  18842. friend class Image;
  18843. friend class Image::BitmapData;
  18844. const PixelFormat format;
  18845. const int width, height;
  18846. int pixelStride, lineStride;
  18847. uint8* imageData;
  18848. var userTag;
  18849. uint8* getPixelData (int x, int y) const throw();
  18850. SharedImage (const SharedImage&);
  18851. SharedImage& operator= (const SharedImage&);
  18852. };
  18853. /** @internal */
  18854. SharedImage* getSharedImage() const throw() { return image; }
  18855. /** @internal */
  18856. explicit Image (SharedImage* instance);
  18857. juce_UseDebuggingNewOperator
  18858. private:
  18859. ReferenceCountedObjectPtr<SharedImage> image;
  18860. };
  18861. #endif // __JUCE_IMAGE_JUCEHEADER__
  18862. /*** End of inlined file: juce_Image.h ***/
  18863. /*** Start of inlined file: juce_RectangleList.h ***/
  18864. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  18865. #define __JUCE_RECTANGLELIST_JUCEHEADER__
  18866. /**
  18867. Maintains a set of rectangles as a complex region.
  18868. This class allows a set of rectangles to be treated as a solid shape, and can
  18869. add and remove rectangular sections of it, and simplify overlapping or
  18870. adjacent rectangles.
  18871. @see Rectangle
  18872. */
  18873. class JUCE_API RectangleList
  18874. {
  18875. public:
  18876. /** Creates an empty RectangleList */
  18877. RectangleList() throw();
  18878. /** Creates a copy of another list */
  18879. RectangleList (const RectangleList& other);
  18880. /** Creates a list containing just one rectangle. */
  18881. RectangleList (const Rectangle<int>& rect);
  18882. /** Copies this list from another one. */
  18883. RectangleList& operator= (const RectangleList& other);
  18884. /** Destructor. */
  18885. ~RectangleList();
  18886. /** Returns true if the region is empty. */
  18887. bool isEmpty() const throw();
  18888. /** Returns the number of rectangles in the list. */
  18889. int getNumRectangles() const throw() { return rects.size(); }
  18890. /** Returns one of the rectangles at a particular index.
  18891. @returns the rectangle at the index, or an empty rectangle if the
  18892. index is out-of-range.
  18893. */
  18894. const Rectangle<int> getRectangle (int index) const throw();
  18895. /** Removes all rectangles to leave an empty region. */
  18896. void clear();
  18897. /** Merges a new rectangle into the list.
  18898. The rectangle being added will first be clipped to remove any parts of it
  18899. that overlap existing rectangles in the list.
  18900. */
  18901. void add (int x, int y, int width, int height);
  18902. /** Merges a new rectangle into the list.
  18903. The rectangle being added will first be clipped to remove any parts of it
  18904. that overlap existing rectangles in the list, and adjacent rectangles will be
  18905. merged into it.
  18906. */
  18907. void add (const Rectangle<int>& rect);
  18908. /** Dumbly adds a rectangle to the list without checking for overlaps.
  18909. This simply adds the rectangle to the end, it doesn't merge it or remove
  18910. any overlapping bits.
  18911. */
  18912. void addWithoutMerging (const Rectangle<int>& rect);
  18913. /** Merges another rectangle list into this one.
  18914. Any overlaps between the two lists will be clipped, so that the result is
  18915. the union of both lists.
  18916. */
  18917. void add (const RectangleList& other);
  18918. /** Removes a rectangular region from the list.
  18919. Any rectangles in the list which overlap this will be clipped and subdivided
  18920. if necessary.
  18921. */
  18922. void subtract (const Rectangle<int>& rect);
  18923. /** Removes all areas in another RectangleList from this one.
  18924. Any rectangles in the list which overlap this will be clipped and subdivided
  18925. if necessary.
  18926. @returns true if the resulting list is non-empty.
  18927. */
  18928. bool subtract (const RectangleList& otherList);
  18929. /** Removes any areas of the region that lie outside a given rectangle.
  18930. Any rectangles in the list which overlap this will be clipped and subdivided
  18931. if necessary.
  18932. Returns true if the resulting region is not empty, false if it is empty.
  18933. @see getIntersectionWith
  18934. */
  18935. bool clipTo (const Rectangle<int>& rect);
  18936. /** Removes any areas of the region that lie outside a given rectangle list.
  18937. Any rectangles in this object which overlap the specified list will be clipped
  18938. and subdivided if necessary.
  18939. Returns true if the resulting region is not empty, false if it is empty.
  18940. @see getIntersectionWith
  18941. */
  18942. bool clipTo (const RectangleList& other);
  18943. /** Creates a region which is the result of clipping this one to a given rectangle.
  18944. Unlike the other clipTo method, this one doesn't affect this object - it puts the
  18945. resulting region into the list whose reference is passed-in.
  18946. Returns true if the resulting region is not empty, false if it is empty.
  18947. @see clipTo
  18948. */
  18949. bool getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const;
  18950. /** Swaps the contents of this and another list.
  18951. This swaps their internal pointers, so is hugely faster than using copy-by-value
  18952. to swap them.
  18953. */
  18954. void swapWith (RectangleList& otherList) throw();
  18955. /** Checks whether the region contains a given point.
  18956. @returns true if the point lies within one of the rectangles in the list
  18957. */
  18958. bool containsPoint (int x, int y) const throw();
  18959. /** Checks whether the region contains the whole of a given rectangle.
  18960. @returns true all parts of the rectangle passed in lie within the region
  18961. defined by this object
  18962. @see intersectsRectangle, containsPoint
  18963. */
  18964. bool containsRectangle (const Rectangle<int>& rectangleToCheck) const;
  18965. /** Checks whether the region contains any part of a given rectangle.
  18966. @returns true if any part of the rectangle passed in lies within the region
  18967. defined by this object
  18968. @see containsRectangle
  18969. */
  18970. bool intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw();
  18971. /** Checks whether this region intersects any part of another one.
  18972. @see intersectsRectangle
  18973. */
  18974. bool intersects (const RectangleList& other) const throw();
  18975. /** Returns the smallest rectangle that can enclose the whole of this region. */
  18976. const Rectangle<int> getBounds() const throw();
  18977. /** Optimises the list into a minimum number of constituent rectangles.
  18978. This will try to combine any adjacent rectangles into larger ones where
  18979. possible, to simplify lists that might have been fragmented by repeated
  18980. add/subtract calls.
  18981. */
  18982. void consolidate();
  18983. /** Adds an x and y value to all the co-ordinates. */
  18984. void offsetAll (int dx, int dy) throw();
  18985. /** Creates a Path object to represent this region. */
  18986. const Path toPath() const;
  18987. /** An iterator for accessing all the rectangles in a RectangleList. */
  18988. class Iterator
  18989. {
  18990. public:
  18991. Iterator (const RectangleList& list) throw();
  18992. ~Iterator();
  18993. /** Advances to the next rectangle, and returns true if it's not finished.
  18994. Call this before using getRectangle() to find the rectangle that was returned.
  18995. */
  18996. bool next() throw();
  18997. /** Returns the current rectangle. */
  18998. const Rectangle<int>* getRectangle() const throw() { return current; }
  18999. juce_UseDebuggingNewOperator
  19000. private:
  19001. const Rectangle<int>* current;
  19002. const RectangleList& owner;
  19003. int index;
  19004. Iterator (const Iterator&);
  19005. Iterator& operator= (const Iterator&);
  19006. };
  19007. juce_UseDebuggingNewOperator
  19008. private:
  19009. friend class Iterator;
  19010. Array <Rectangle<int> > rects;
  19011. };
  19012. #endif // __JUCE_RECTANGLELIST_JUCEHEADER__
  19013. /*** End of inlined file: juce_RectangleList.h ***/
  19014. /*** Start of inlined file: juce_BorderSize.h ***/
  19015. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  19016. #define __JUCE_BORDERSIZE_JUCEHEADER__
  19017. /**
  19018. Specifies a set of gaps to be left around the sides of a rectangle.
  19019. This is basically the size of the spaces at the top, bottom, left and right of
  19020. a rectangle. It's used by various component classes to specify borders.
  19021. @see Rectangle
  19022. */
  19023. class JUCE_API BorderSize
  19024. {
  19025. public:
  19026. /** Creates a null border.
  19027. All sizes are left as 0.
  19028. */
  19029. BorderSize() throw();
  19030. /** Creates a copy of another border. */
  19031. BorderSize (const BorderSize& other) throw();
  19032. /** Creates a border with the given gaps. */
  19033. BorderSize (int topGap,
  19034. int leftGap,
  19035. int bottomGap,
  19036. int rightGap) throw();
  19037. /** Creates a border with the given gap on all sides. */
  19038. explicit BorderSize (int allGaps) throw();
  19039. /** Destructor. */
  19040. ~BorderSize() throw();
  19041. /** Returns the gap that should be left at the top of the region. */
  19042. int getTop() const throw() { return top; }
  19043. /** Returns the gap that should be left at the top of the region. */
  19044. int getLeft() const throw() { return left; }
  19045. /** Returns the gap that should be left at the top of the region. */
  19046. int getBottom() const throw() { return bottom; }
  19047. /** Returns the gap that should be left at the top of the region. */
  19048. int getRight() const throw() { return right; }
  19049. /** Returns the sum of the top and bottom gaps. */
  19050. int getTopAndBottom() const throw() { return top + bottom; }
  19051. /** Returns the sum of the left and right gaps. */
  19052. int getLeftAndRight() const throw() { return left + right; }
  19053. /** Changes the top gap. */
  19054. void setTop (int newTopGap) throw();
  19055. /** Changes the left gap. */
  19056. void setLeft (int newLeftGap) throw();
  19057. /** Changes the bottom gap. */
  19058. void setBottom (int newBottomGap) throw();
  19059. /** Changes the right gap. */
  19060. void setRight (int newRightGap) throw();
  19061. /** Returns a rectangle with these borders removed from it. */
  19062. const Rectangle<int> subtractedFrom (const Rectangle<int>& original) const throw();
  19063. /** Removes this border from a given rectangle. */
  19064. void subtractFrom (Rectangle<int>& rectangle) const throw();
  19065. /** Returns a rectangle with these borders added around it. */
  19066. const Rectangle<int> addedTo (const Rectangle<int>& original) const throw();
  19067. /** Adds this border around a given rectangle. */
  19068. void addTo (Rectangle<int>& original) const throw();
  19069. bool operator== (const BorderSize& other) const throw();
  19070. bool operator!= (const BorderSize& other) const throw();
  19071. juce_UseDebuggingNewOperator
  19072. private:
  19073. int top, left, bottom, right;
  19074. };
  19075. #endif // __JUCE_BORDERSIZE_JUCEHEADER__
  19076. /*** End of inlined file: juce_BorderSize.h ***/
  19077. /*** Start of inlined file: juce_ModalComponentManager.h ***/
  19078. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19079. #define __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19080. /*** Start of inlined file: juce_DeletedAtShutdown.h ***/
  19081. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19082. #define __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19083. /**
  19084. Classes derived from this will be automatically deleted when the application exits.
  19085. After JUCEApplication::shutdown() has been called, any objects derived from
  19086. DeletedAtShutdown which are still in existence will be deleted in the reverse
  19087. order to that in which they were created.
  19088. So if you've got a singleton and don't want to have to explicitly delete it, just
  19089. inherit from this and it'll be taken care of.
  19090. */
  19091. class JUCE_API DeletedAtShutdown
  19092. {
  19093. protected:
  19094. /** Creates a DeletedAtShutdown object. */
  19095. DeletedAtShutdown();
  19096. /** Destructor.
  19097. It's ok to delete these objects explicitly - it's only the ones left
  19098. dangling at the end that will be deleted automatically.
  19099. */
  19100. virtual ~DeletedAtShutdown();
  19101. public:
  19102. /** Deletes all extant objects.
  19103. This shouldn't be used by applications, as it's called automatically
  19104. in the shutdown code of the JUCEApplication class.
  19105. */
  19106. static void deleteAll();
  19107. private:
  19108. DeletedAtShutdown (const DeletedAtShutdown&);
  19109. DeletedAtShutdown& operator= (const DeletedAtShutdown&);
  19110. static CriticalSection& getLock();
  19111. static Array <DeletedAtShutdown*>& getObjects();
  19112. };
  19113. #endif // __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  19114. /*** End of inlined file: juce_DeletedAtShutdown.h ***/
  19115. /**
  19116. Manages the system's stack of modal components.
  19117. Normally you'll just use the Component methods to invoke modal states in components,
  19118. and won't have to deal with this class directly, but this is the singleton object that's
  19119. used internally to manage the stack.
  19120. @see Component::enterModalState, Component::exitModalState, Component::isCurrentlyModal,
  19121. Component::getCurrentlyModalComponent, Component::isCurrentlyBlockedByAnotherModalComponent
  19122. */
  19123. class JUCE_API ModalComponentManager : public AsyncUpdater,
  19124. public DeletedAtShutdown
  19125. {
  19126. public:
  19127. /** Receives callbacks when a modal component is dismissed.
  19128. You can register a callback using Component::enterModalState() or
  19129. ModalComponentManager::attachCallback().
  19130. */
  19131. class Callback
  19132. {
  19133. public:
  19134. /** */
  19135. Callback() {}
  19136. /** Destructor. */
  19137. virtual ~Callback() {}
  19138. /** Called to indicate that a modal component has been dismissed.
  19139. You can register a callback using Component::enterModalState() or
  19140. ModalComponentManager::attachCallback().
  19141. The returnValue parameter is the value that was passed to Component::exitModalState()
  19142. when the component was dismissed.
  19143. The callback object will be deleted shortly after this method is called.
  19144. */
  19145. virtual void modalStateFinished (int returnValue) = 0;
  19146. };
  19147. /** Returns the number of components currently being shown modally.
  19148. @see getModalComponent
  19149. */
  19150. int getNumModalComponents() const;
  19151. /** Returns one of the components being shown modally.
  19152. An index of 0 is the most recently-shown, topmost component.
  19153. */
  19154. Component* getModalComponent (int index) const;
  19155. /** Returns true if the specified component is in a modal state. */
  19156. bool isModal (Component* component) const;
  19157. /** Returns true if the specified component is currently the topmost modal component. */
  19158. bool isFrontModalComponent (Component* component) const;
  19159. /** Adds a new callback that will be called when the specified modal component is dismissed.
  19160. If the component is modal, then when it is dismissed, either by being hidden, or by calling
  19161. Component::exitModalState(), then the Callback::modalStateFinished() method will be
  19162. called.
  19163. Each component can have any number of callbacks associated with it, and this one is added
  19164. to that list.
  19165. The object that is passed in will be deleted by the manager when it's no longer needed. If
  19166. the given component is not currently modal, the callback object is deleted immediately and
  19167. no action is taken.
  19168. */
  19169. void attachCallback (Component* component, Callback* callback);
  19170. /** Runs the event loop until the currently topmost modal component is dismissed, and
  19171. returns the exit code for that component.
  19172. */
  19173. int runEventLoopForCurrentComponent();
  19174. juce_DeclareSingleton_SingleThreaded_Minimal (ModalComponentManager);
  19175. protected:
  19176. /** Creates a ModalComponentManager.
  19177. You shouldn't ever call the constructor - it's a singleton, so use ModalComponentManager::getInstance()
  19178. */
  19179. ModalComponentManager();
  19180. /** Destructor. */
  19181. ~ModalComponentManager();
  19182. /** @internal */
  19183. void handleAsyncUpdate();
  19184. private:
  19185. class ModalItem;
  19186. class ReturnValueRetriever;
  19187. friend class Component;
  19188. friend class OwnedArray <ModalItem>;
  19189. OwnedArray <ModalItem> stack;
  19190. void startModal (Component* component, Callback* callback);
  19191. void endModal (Component* component, int returnValue);
  19192. void endModal (Component* component);
  19193. };
  19194. #endif // __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  19195. /*** End of inlined file: juce_ModalComponentManager.h ***/
  19196. class LookAndFeel;
  19197. class MouseInputSource;
  19198. class MouseInputSourceInternal;
  19199. class ComponentPeer;
  19200. /**
  19201. The base class for all JUCE user-interface objects.
  19202. */
  19203. class JUCE_API Component : public MouseListener,
  19204. public MessageListener
  19205. {
  19206. public:
  19207. /** Creates a component.
  19208. To get it to actually appear, you'll also need to:
  19209. - Either add it to a parent component or use the addToDesktop() method to
  19210. make it a desktop window
  19211. - Set its size and position to something sensible
  19212. - Use setVisible() to make it visible
  19213. And for it to serve any useful purpose, you'll need to write a
  19214. subclass of Component or use one of the other types of component from
  19215. the library.
  19216. */
  19217. Component();
  19218. /** Destructor.
  19219. Note that when a component is deleted, any child components it might
  19220. contain are NOT deleted unless you explicitly call deleteAllChildren() first.
  19221. */
  19222. virtual ~Component();
  19223. /** Creates a component, setting its name at the same time.
  19224. @see getName, setName
  19225. */
  19226. explicit Component (const String& componentName);
  19227. /** Returns the name of this component.
  19228. @see setName
  19229. */
  19230. const String& getName() const throw() { return componentName_; }
  19231. /** Sets the name of this component.
  19232. When the name changes, all registered ComponentListeners will receive a
  19233. ComponentListener::componentNameChanged() callback.
  19234. @see getName
  19235. */
  19236. virtual void setName (const String& newName);
  19237. /** Checks whether this Component object has been deleted.
  19238. This will check whether this object is still a valid component, or whether
  19239. it's been deleted.
  19240. It's safe to call this on null or dangling pointers, but note that there is a
  19241. small risk if another new (but different) component has been created at the
  19242. same memory address which this one occupied, this methods can return a
  19243. false positive.
  19244. */
  19245. bool isValidComponent() const;
  19246. /** Makes the component visible or invisible.
  19247. This method will show or hide the component.
  19248. Note that components default to being non-visible when first created.
  19249. Also note that visible components won't be seen unless all their parent components
  19250. are also visible.
  19251. This method will call visibilityChanged() and also componentVisibilityChanged()
  19252. for any component listeners that are interested in this component.
  19253. @param shouldBeVisible whether to show or hide the component
  19254. @see isVisible, isShowing, visibilityChanged, ComponentListener::componentVisibilityChanged
  19255. */
  19256. virtual void setVisible (bool shouldBeVisible);
  19257. /** Tests whether the component is visible or not.
  19258. this doesn't necessarily tell you whether this comp is actually on the screen
  19259. because this depends on whether all the parent components are also visible - use
  19260. isShowing() to find this out.
  19261. @see isShowing, setVisible
  19262. */
  19263. bool isVisible() const throw() { return flags.visibleFlag; }
  19264. /** Called when this component's visiblility changes.
  19265. @see setVisible, isVisible
  19266. */
  19267. virtual void visibilityChanged();
  19268. /** Tests whether this component and all its parents are visible.
  19269. @returns true only if this component and all its parents are visible.
  19270. @see isVisible
  19271. */
  19272. bool isShowing() const;
  19273. /** Makes a component invisible using a groovy fade-out and animated zoom effect.
  19274. To do this, this function will cunningly:
  19275. - take a snapshot of the component as it currently looks
  19276. - call setVisible(false) on the component
  19277. - replace it with a special component that will continue drawing the
  19278. snapshot, animating it and gradually making it more transparent
  19279. - when it's gone, the special component will also be deleted
  19280. As soon as this method returns, the component can be safely removed and deleted
  19281. leaving the proxy to do the fade-out, so it's even ok to call this in a
  19282. component's destructor.
  19283. Passing non-zero x and y values will cause the ghostly component image to
  19284. also whizz off by this distance while fading out. If the scale factor is
  19285. not 1.0, it will also zoom from the component's current size to this new size.
  19286. One thing to be careful about is that the parent component must be able to cope
  19287. with this unknown component type being added to it.
  19288. */
  19289. void fadeOutComponent (int lengthOfFadeOutInMilliseconds,
  19290. int deltaXToMove = 0,
  19291. int deltaYToMove = 0,
  19292. float scaleFactorAtEnd = 1.0f);
  19293. /** Makes this component appear as a window on the desktop.
  19294. Note that before calling this, you should make sure that the component's opacity is
  19295. set correctly using setOpaque(). If the component is non-opaque, the windowing
  19296. system will try to create a special transparent window for it, which will generally take
  19297. a lot more CPU to operate (and might not even be possible on some platforms).
  19298. If the component is inside a parent component at the time this method is called, it
  19299. will be first be removed from that parent. Likewise if a component on the desktop
  19300. is subsequently added to another component, it'll be removed from the desktop.
  19301. @param windowStyleFlags a combination of the flags specified in the
  19302. ComponentPeer::StyleFlags enum, which define the
  19303. window's characteristics.
  19304. @param nativeWindowToAttachTo this allows an OS object to be passed-in as the window
  19305. in which the juce component should place itself. On Windows,
  19306. this would be a HWND, a HIViewRef on the Mac. Not necessarily
  19307. supported on all platforms, and best left as 0 unless you know
  19308. what you're doing
  19309. @see removeFromDesktop, isOnDesktop, userTriedToCloseWindow,
  19310. getPeer, ComponentPeer::setMinimised, ComponentPeer::StyleFlags,
  19311. ComponentPeer::getStyleFlags, ComponentPeer::setFullScreen
  19312. */
  19313. virtual void addToDesktop (int windowStyleFlags,
  19314. void* nativeWindowToAttachTo = 0);
  19315. /** If the component is currently showing on the desktop, this will hide it.
  19316. You can also use setVisible() to hide a desktop window temporarily, but
  19317. removeFromDesktop() will free any system resources that are being used up.
  19318. @see addToDesktop, isOnDesktop
  19319. */
  19320. void removeFromDesktop();
  19321. /** Returns true if this component is currently showing on the desktop.
  19322. @see addToDesktop, removeFromDesktop
  19323. */
  19324. bool isOnDesktop() const throw();
  19325. /** Returns the heavyweight window that contains this component.
  19326. If this component is itself on the desktop, this will return the window
  19327. object that it is using. Otherwise, it will return the window of
  19328. its top-level parent component.
  19329. This may return 0 if there isn't a desktop component.
  19330. @see addToDesktop, isOnDesktop
  19331. */
  19332. ComponentPeer* getPeer() const;
  19333. /** For components on the desktop, this is called if the system wants to close the window.
  19334. This is a signal that either the user or the system wants the window to close. The
  19335. default implementation of this method will trigger an assertion to warn you that your
  19336. component should do something about it, but you can override this to ignore the event
  19337. if you want.
  19338. */
  19339. virtual void userTriedToCloseWindow();
  19340. /** Called for a desktop component which has just been minimised or un-minimised.
  19341. This will only be called for components on the desktop.
  19342. @see getPeer, ComponentPeer::setMinimised, ComponentPeer::isMinimised
  19343. */
  19344. virtual void minimisationStateChanged (bool isNowMinimised);
  19345. /** Brings the component to the front of its siblings.
  19346. If some of the component's siblings have had their 'always-on-top' flag set,
  19347. then they will still be kept in front of this one (unless of course this
  19348. one is also 'always-on-top').
  19349. @param shouldAlsoGainFocus if true, this will also try to assign keyboard focus
  19350. to the component (see grabKeyboardFocus() for more details)
  19351. @see toBack, toBehind, setAlwaysOnTop
  19352. */
  19353. void toFront (bool shouldAlsoGainFocus);
  19354. /** Changes this component's z-order to be at the back of all its siblings.
  19355. If the component is set to be 'always-on-top', it will only be moved to the
  19356. back of the other other 'always-on-top' components.
  19357. @see toFront, toBehind, setAlwaysOnTop
  19358. */
  19359. void toBack();
  19360. /** Changes this component's z-order so that it's just behind another component.
  19361. @see toFront, toBack
  19362. */
  19363. void toBehind (Component* other);
  19364. /** Sets whether the component should always be kept at the front of its siblings.
  19365. @see isAlwaysOnTop
  19366. */
  19367. void setAlwaysOnTop (bool shouldStayOnTop);
  19368. /** Returns true if this component is set to always stay in front of its siblings.
  19369. @see setAlwaysOnTop
  19370. */
  19371. bool isAlwaysOnTop() const throw();
  19372. /** Returns the x co-ordinate of the component's left edge.
  19373. This is a distance in pixels from the left edge of the component's parent.
  19374. @see getScreenX
  19375. */
  19376. inline int getX() const throw() { return bounds_.getX(); }
  19377. /** Returns the y co-ordinate of the top of this component.
  19378. This is a distance in pixels from the top edge of the component's parent.
  19379. @see getScreenY
  19380. */
  19381. inline int getY() const throw() { return bounds_.getY(); }
  19382. /** Returns the component's width in pixels. */
  19383. inline int getWidth() const throw() { return bounds_.getWidth(); }
  19384. /** Returns the component's height in pixels. */
  19385. inline int getHeight() const throw() { return bounds_.getHeight(); }
  19386. /** Returns the x co-ordinate of the component's right-hand edge.
  19387. This is a distance in pixels from the left edge of the component's parent.
  19388. */
  19389. int getRight() const throw() { return bounds_.getRight(); }
  19390. /** Returns the component's top-left position as a Point. */
  19391. const Point<int> getPosition() const throw() { return bounds_.getPosition(); }
  19392. /** Returns the y co-ordinate of the bottom edge of this component.
  19393. This is a distance in pixels from the top edge of the component's parent.
  19394. */
  19395. int getBottom() const throw() { return bounds_.getBottom(); }
  19396. /** Returns this component's bounding box.
  19397. The rectangle returned is relative to the top-left of the component's parent.
  19398. */
  19399. const Rectangle<int>& getBounds() const throw() { return bounds_; }
  19400. /** Returns the component's bounds, relative to its own origin.
  19401. This is like getBounds(), but returns the rectangle in local co-ordinates, In practice, it'll
  19402. return a rectangle with position (0, 0), and the same size as this component.
  19403. */
  19404. const Rectangle<int> getLocalBounds() const throw();
  19405. /** Returns the region of this component that's not obscured by other, opaque components.
  19406. The RectangleList that is returned represents the area of this component
  19407. which isn't covered by opaque child components.
  19408. If includeSiblings is true, it will also take into account any siblings
  19409. that may be overlapping the component.
  19410. */
  19411. void getVisibleArea (RectangleList& result,
  19412. bool includeSiblings) const;
  19413. /** Returns this component's x co-ordinate relative the the screen's top-left origin.
  19414. @see getX, relativePositionToGlobal
  19415. */
  19416. int getScreenX() const;
  19417. /** Returns this component's y co-ordinate relative the the screen's top-left origin.
  19418. @see getY, relativePositionToGlobal
  19419. */
  19420. int getScreenY() const;
  19421. /** Returns the position of this component's top-left corner relative to the screen's top-left.
  19422. @see getScreenBounds
  19423. */
  19424. const Point<int> getScreenPosition() const;
  19425. /** Returns the bounds of this component, relative to the screen's top-left.
  19426. @see getScreenPosition
  19427. */
  19428. const Rectangle<int> getScreenBounds() const;
  19429. /** Converts a position relative to this component's top-left into a screen co-ordinate.
  19430. @see globalPositionToRelative, relativePositionToOtherComponent
  19431. */
  19432. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) const;
  19433. /** Converts a screen co-ordinate into a position relative to this component's top-left.
  19434. @see relativePositionToGlobal, relativePositionToOtherComponent
  19435. */
  19436. const Point<int> globalPositionToRelative (const Point<int>& screenPosition) const;
  19437. /** Converts a position relative to this component's top-left into a position
  19438. relative to another component's top-left.
  19439. @see relativePositionToGlobal, globalPositionToRelative
  19440. */
  19441. const Point<int> relativePositionToOtherComponent (const Component* targetComponent,
  19442. const Point<int>& positionRelativeToThis) const;
  19443. /** Moves the component to a new position.
  19444. Changes the component's top-left position (without changing its size).
  19445. The position is relative to the top-left of the component's parent.
  19446. If the component actually moves, this method will make a synchronous call to moved().
  19447. @see setBounds, ComponentListener::componentMovedOrResized
  19448. */
  19449. void setTopLeftPosition (int x, int y);
  19450. /** Moves the component to a new position.
  19451. Changes the position of the component's top-right corner (keeping it the same size).
  19452. The position is relative to the top-left of the component's parent.
  19453. If the component actually moves, this method will make a synchronous call to moved().
  19454. */
  19455. void setTopRightPosition (int x, int y);
  19456. /** Changes the size of the component.
  19457. A synchronous call to resized() will be occur if the size actually changes.
  19458. */
  19459. void setSize (int newWidth, int newHeight);
  19460. /** Changes the component's position and size.
  19461. The co-ordinates are relative to the top-left of the component's parent, or relative
  19462. to the origin of the screen is the component is on the desktop.
  19463. If this method changes the component's top-left position, it will make a synchronous
  19464. call to moved(). If it changes the size, it will also make a call to resized().
  19465. @see setTopLeftPosition, setSize, ComponentListener::componentMovedOrResized
  19466. */
  19467. void setBounds (int x, int y, int width, int height);
  19468. /** Changes the component's position and size.
  19469. @see setBounds
  19470. */
  19471. void setBounds (const Rectangle<int>& newBounds);
  19472. /** Changes the component's position and size in terms of fractions of its parent's size.
  19473. The values are factors of the parent's size, so for example
  19474. setBoundsRelative (0.2f, 0.2f, 0.5f, 0.5f) would give it half the
  19475. width and height of the parent, with its top-left position 20% of
  19476. the way across and down the parent.
  19477. */
  19478. void setBoundsRelative (float proportionalX, float proportionalY,
  19479. float proportionalWidth, float proportionalHeight);
  19480. /** Changes the component's position and size based on the amount of space to leave around it.
  19481. This will position the component within its parent, leaving the specified number of
  19482. pixels around each edge.
  19483. */
  19484. void setBoundsInset (const BorderSize& borders);
  19485. /** Positions the component within a given rectangle, keeping its proportions
  19486. unchanged.
  19487. If onlyReduceInSize is false, the component will be resized to fill as much of the
  19488. rectangle as possible without changing its aspect ratio (the component's
  19489. current size is used to determine its aspect ratio, so a zero-size component
  19490. won't work here). If onlyReduceInSize is true, it will only be resized if it's
  19491. too big to fit inside the rectangle.
  19492. It will then be positioned within the rectangle according to the justification flags
  19493. specified.
  19494. */
  19495. void setBoundsToFit (int x, int y, int width, int height,
  19496. const Justification& justification,
  19497. bool onlyReduceInSize);
  19498. /** Changes the position of the component's centre.
  19499. Leaves the component's size unchanged, but sets the position of its centre
  19500. relative to its parent's top-left.
  19501. */
  19502. void setCentrePosition (int x, int y);
  19503. /** Changes the position of the component's centre.
  19504. Leaves the position unchanged, but positions its centre relative to its
  19505. parent's size. E.g. setCentreRelative (0.5f, 0.5f) would place it centrally in
  19506. its parent.
  19507. */
  19508. void setCentreRelative (float x, float y);
  19509. /** Changes the component's size and centres it within its parent.
  19510. After changing the size, the component will be moved so that it's
  19511. centred within its parent. If the component is on the desktop (or has no
  19512. parent component), then it'll be centred within the main monitor area.
  19513. */
  19514. void centreWithSize (int width, int height);
  19515. /** Returns a proportion of the component's width.
  19516. This is a handy equivalent of (getWidth() * proportion).
  19517. */
  19518. int proportionOfWidth (float proportion) const throw();
  19519. /** Returns a proportion of the component's height.
  19520. This is a handy equivalent of (getHeight() * proportion).
  19521. */
  19522. int proportionOfHeight (float proportion) const throw();
  19523. /** Returns the width of the component's parent.
  19524. If the component has no parent (i.e. if it's on the desktop), this will return
  19525. the width of the screen.
  19526. */
  19527. int getParentWidth() const throw();
  19528. /** Returns the height of the component's parent.
  19529. If the component has no parent (i.e. if it's on the desktop), this will return
  19530. the height of the screen.
  19531. */
  19532. int getParentHeight() const throw();
  19533. /** Returns the screen co-ordinates of the monitor that contains this component.
  19534. If there's only one monitor, this will return its size - if there are multiple
  19535. monitors, it will return the area of the monitor that contains the component's
  19536. centre.
  19537. */
  19538. const Rectangle<int> getParentMonitorArea() const;
  19539. /** Returns the number of child components that this component contains.
  19540. @see getChildComponent, getIndexOfChildComponent
  19541. */
  19542. int getNumChildComponents() const throw();
  19543. /** Returns one of this component's child components, by it index.
  19544. The component with index 0 is at the back of the z-order, the one at the
  19545. front will have index (getNumChildComponents() - 1).
  19546. If the index is out-of-range, this will return a null pointer.
  19547. @see getNumChildComponents, getIndexOfChildComponent
  19548. */
  19549. Component* getChildComponent (int index) const throw();
  19550. /** Returns the index of this component in the list of child components.
  19551. A value of 0 means it is first in the list (i.e. behind all other components). Higher
  19552. values are further towards the front.
  19553. Returns -1 if the component passed-in is not a child of this component.
  19554. @see getNumChildComponents, getChildComponent, addChildComponent, toFront, toBack, toBehind
  19555. */
  19556. int getIndexOfChildComponent (const Component* child) const throw();
  19557. /** Adds a child component to this one.
  19558. @param child the new component to add. If the component passed-in is already
  19559. the child of another component, it'll first be removed from that.
  19560. @param zOrder The index in the child-list at which this component should be inserted.
  19561. A value of -1 will insert it in front of the others, 0 is the back.
  19562. @see removeChildComponent, addAndMakeVisible, getChild,
  19563. ComponentListener::componentChildrenChanged
  19564. */
  19565. void addChildComponent (Component* child, int zOrder = -1);
  19566. /** Adds a child component to this one, and also makes the child visible if it isn't.
  19567. Quite a useful function, this is just the same as calling addChildComponent()
  19568. followed by setVisible (true) on the child.
  19569. */
  19570. void addAndMakeVisible (Component* child, int zOrder = -1);
  19571. /** Removes one of this component's child-components.
  19572. If the child passed-in isn't actually a child of this component (either because
  19573. it's invalid or is the child of a different parent), then nothing is done.
  19574. Note that removing a child will not delete it!
  19575. @see addChildComponent, ComponentListener::componentChildrenChanged
  19576. */
  19577. void removeChildComponent (Component* childToRemove);
  19578. /** Removes one of this component's child-components by index.
  19579. This will return a pointer to the component that was removed, or null if
  19580. the index was out-of-range.
  19581. Note that removing a child will not delete it!
  19582. @see addChildComponent, ComponentListener::componentChildrenChanged
  19583. */
  19584. Component* removeChildComponent (int childIndexToRemove);
  19585. /** Removes all this component's children.
  19586. Note that this won't delete them! To do that, use deleteAllChildren() instead.
  19587. */
  19588. void removeAllChildren();
  19589. /** Removes all this component's children, and deletes them.
  19590. @see removeAllChildren
  19591. */
  19592. void deleteAllChildren();
  19593. /** Returns the component which this component is inside.
  19594. If this is the highest-level component or hasn't yet been added to
  19595. a parent, this will return null.
  19596. */
  19597. Component* getParentComponent() const throw() { return parentComponent_; }
  19598. /** Searches the parent components for a component of a specified class.
  19599. For example findParentComponentOfClass \<MyComp\>() would return the first parent
  19600. component that can be dynamically cast to a MyComp, or will return 0 if none
  19601. of the parents are suitable.
  19602. N.B. The dummy parameter is needed to work around a VC6 compiler bug.
  19603. */
  19604. template <class TargetClass>
  19605. TargetClass* findParentComponentOfClass (TargetClass* const dummyParameter = 0) const
  19606. {
  19607. (void) dummyParameter;
  19608. Component* p = parentComponent_;
  19609. while (p != 0)
  19610. {
  19611. TargetClass* target = dynamic_cast <TargetClass*> (p);
  19612. if (target != 0)
  19613. return target;
  19614. p = p->parentComponent_;
  19615. }
  19616. return 0;
  19617. }
  19618. /** Returns the highest-level component which contains this one or its parents.
  19619. This will search upwards in the parent-hierarchy from this component, until it
  19620. finds the highest one that doesn't have a parent (i.e. is on the desktop or
  19621. not yet added to a parent), and will return that.
  19622. */
  19623. Component* getTopLevelComponent() const throw();
  19624. /** Checks whether a component is anywhere inside this component or its children.
  19625. This will recursively check through this component's children to see if the
  19626. given component is anywhere inside.
  19627. */
  19628. bool isParentOf (const Component* possibleChild) const throw();
  19629. /** Called to indicate that the component's parents have changed.
  19630. When a component is added or removed from its parent, this method will
  19631. be called on all of its children (recursively - so all children of its
  19632. children will also be called as well).
  19633. Subclasses can override this if they need to react to this in some way.
  19634. @see getParentComponent, isShowing, ComponentListener::componentParentHierarchyChanged
  19635. */
  19636. virtual void parentHierarchyChanged();
  19637. /** Subclasses can use this callback to be told when children are added or removed.
  19638. @see parentHierarchyChanged
  19639. */
  19640. virtual void childrenChanged();
  19641. /** Tests whether a given point inside the component.
  19642. Overriding this method allows you to create components which only intercept
  19643. mouse-clicks within a user-defined area.
  19644. This is called to find out whether a particular x, y co-ordinate is
  19645. considered to be inside the component or not, and is used by methods such
  19646. as contains() and getComponentAt() to work out which component
  19647. the mouse is clicked on.
  19648. Components with custom shapes will probably want to override it to perform
  19649. some more complex hit-testing.
  19650. The default implementation of this method returns either true or false,
  19651. depending on the value that was set by calling setInterceptsMouseClicks() (true
  19652. is the default return value).
  19653. Note that the hit-test region is not related to the opacity with which
  19654. areas of a component are painted.
  19655. Applications should never call hitTest() directly - instead use the
  19656. contains() method, because this will also test for occlusion by the
  19657. component's parent.
  19658. Note that for components on the desktop, this method will be ignored, because it's
  19659. not always possible to implement this behaviour on all platforms.
  19660. @param x the x co-ordinate to test, relative to the left hand edge of this
  19661. component. This value is guaranteed to be greater than or equal to
  19662. zero, and less than the component's width
  19663. @param y the y co-ordinate to test, relative to the top edge of this
  19664. component. This value is guaranteed to be greater than or equal to
  19665. zero, and less than the component's height
  19666. @returns true if the click is considered to be inside the component
  19667. @see setInterceptsMouseClicks, contains
  19668. */
  19669. virtual bool hitTest (int x, int y);
  19670. /** Changes the default return value for the hitTest() method.
  19671. Setting this to false is an easy way to make a component pass its mouse-clicks
  19672. through to the components behind it.
  19673. When a component is created, the default setting for this is true.
  19674. @param allowClicksOnThisComponent if true, hitTest() will always return true; if false, it will
  19675. return false (or true for child components if allowClicksOnChildComponents
  19676. is true)
  19677. @param allowClicksOnChildComponents if this is true and allowClicksOnThisComponent is false, then child
  19678. components can be clicked on as normal but clicks on this component pass
  19679. straight through; if this is false and allowClicksOnThisComponent
  19680. is false, then neither this component nor any child components can
  19681. be clicked on
  19682. @see hitTest, getInterceptsMouseClicks
  19683. */
  19684. void setInterceptsMouseClicks (bool allowClicksOnThisComponent,
  19685. bool allowClicksOnChildComponents) throw();
  19686. /** Retrieves the current state of the mouse-click interception flags.
  19687. On return, the two parameters are set to the state used in the last call to
  19688. setInterceptsMouseClicks().
  19689. @see setInterceptsMouseClicks
  19690. */
  19691. void getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  19692. bool& allowsClicksOnChildComponents) const throw();
  19693. /** Returns true if a given point lies within this component or one of its children.
  19694. Never override this method! Use hitTest to create custom hit regions.
  19695. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19696. @param y the y co-ordinate to test, relative to this component's top edge.
  19697. @returns true if the point is within the component's hit-test area, but only if
  19698. that part of the component isn't clipped by its parent component. Note
  19699. that this won't take into account any overlapping sibling components
  19700. which might be in the way - for that, see reallyContains()
  19701. @see hitTest, reallyContains, getComponentAt
  19702. */
  19703. virtual bool contains (int x, int y);
  19704. /** Returns true if a given point lies in this component, taking any overlapping
  19705. siblings into account.
  19706. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19707. @param y the y co-ordinate to test, relative to this component's top edge.
  19708. @param returnTrueIfWithinAChild if the point actually lies within a child of this
  19709. component, this determines the value that will
  19710. be returned.
  19711. @see contains, getComponentAt
  19712. */
  19713. bool reallyContains (int x, int y, bool returnTrueIfWithinAChild);
  19714. /** Returns the component at a certain point within this one.
  19715. @param x the x co-ordinate to test, relative to this component's left hand edge.
  19716. @param y the y co-ordinate to test, relative to this component's top edge.
  19717. @returns the component that is at this position - which may be 0, this component,
  19718. or one of its children. Note that overlapping siblings that might actually
  19719. be in the way are not taken into account by this method - to account for these,
  19720. instead call getComponentAt on the top-level parent of this component.
  19721. @see hitTest, contains, reallyContains
  19722. */
  19723. Component* getComponentAt (int x, int y);
  19724. /** Returns the component at a certain point within this one.
  19725. @param position the co-ordinates to test, relative to this component's top-left.
  19726. @returns the component that is at this position - which may be 0, this component,
  19727. or one of its children. Note that overlapping siblings that might actually
  19728. be in the way are not taken into account by this method - to account for these,
  19729. instead call getComponentAt on the top-level parent of this component.
  19730. @see hitTest, contains, reallyContains
  19731. */
  19732. Component* getComponentAt (const Point<int>& position);
  19733. /** Marks the whole component as needing to be redrawn.
  19734. Calling this will not do any repainting immediately, but will mark the component
  19735. as 'dirty'. At some point in the near future the operating system will send a paint
  19736. message, which will redraw all the dirty regions of all components.
  19737. There's no guarantee about how soon after calling repaint() the redraw will actually
  19738. happen, and other queued events may be delivered before a redraw is done.
  19739. If the setBufferedToImage() method has been used to cause this component
  19740. to use a buffer, the repaint() call will invalidate the component's buffer.
  19741. To redraw just a subsection of the component rather than the whole thing,
  19742. use the repaint (int, int, int, int) method.
  19743. @see paint
  19744. */
  19745. void repaint();
  19746. /** Marks a subsection of this component as needing to be redrawn.
  19747. Calling this will not do any repainting immediately, but will mark the given region
  19748. of the component as 'dirty'. At some point in the near future the operating system
  19749. will send a paint message, which will redraw all the dirty regions of all components.
  19750. There's no guarantee about how soon after calling repaint() the redraw will actually
  19751. happen, and other queued events may be delivered before a redraw is done.
  19752. The region that is passed in will be clipped to keep it within the bounds of this
  19753. component.
  19754. @see repaint()
  19755. */
  19756. void repaint (int x, int y, int width, int height);
  19757. /** Marks a subsection of this component as needing to be redrawn.
  19758. Calling this will not do any repainting immediately, but will mark the given region
  19759. of the component as 'dirty'. At some point in the near future the operating system
  19760. will send a paint message, which will redraw all the dirty regions of all components.
  19761. There's no guarantee about how soon after calling repaint() the redraw will actually
  19762. happen, and other queued events may be delivered before a redraw is done.
  19763. The region that is passed in will be clipped to keep it within the bounds of this
  19764. component.
  19765. @see repaint()
  19766. */
  19767. void repaint (const Rectangle<int>& area);
  19768. /** Makes the component use an internal buffer to optimise its redrawing.
  19769. Setting this flag to true will cause the component to allocate an
  19770. internal buffer into which it paints itself, so that when asked to
  19771. redraw itself, it can use this buffer rather than actually calling the
  19772. paint() method.
  19773. The buffer is kept until the repaint() method is called directly on
  19774. this component (or until it is resized), when the image is invalidated
  19775. and then redrawn the next time the component is painted.
  19776. Note that only the drawing that happens within the component's paint()
  19777. method is drawn into the buffer, it's child components are not buffered, and
  19778. nor is the paintOverChildren() method.
  19779. @see repaint, paint, createComponentSnapshot
  19780. */
  19781. void setBufferedToImage (bool shouldBeBuffered);
  19782. /** Generates a snapshot of part of this component.
  19783. This will return a new Image, the size of the rectangle specified,
  19784. containing a snapshot of the specified area of the component and all
  19785. its children.
  19786. The image may or may not have an alpha-channel, depending on whether the
  19787. image is opaque or not.
  19788. If the clipImageToComponentBounds parameter is true and the area is greater than
  19789. the size of the component, it'll be clipped. If clipImageToComponentBounds is false
  19790. then parts of the component beyond its bounds can be drawn.
  19791. @see paintEntireComponent
  19792. */
  19793. const Image createComponentSnapshot (const Rectangle<int>& areaToGrab,
  19794. bool clipImageToComponentBounds = true);
  19795. /** Draws this component and all its subcomponents onto the specified graphics
  19796. context.
  19797. You should very rarely have to use this method, it's simply there in case you need
  19798. to draw a component with a custom graphics context for some reason, e.g. for
  19799. creating a snapshot of the component.
  19800. It calls paint(), paintOverChildren() and recursively calls paintEntireComponent()
  19801. on its children in order to render the entire tree.
  19802. The graphics context may be left in an undefined state after this method returns,
  19803. so you may need to reset it if you're going to use it again.
  19804. */
  19805. void paintEntireComponent (Graphics& context);
  19806. /** Adds an effect filter to alter the component's appearance.
  19807. When a component has an effect filter set, then this is applied to the
  19808. results of its paint() method. There are a few preset effects, such as
  19809. a drop-shadow or glow, but they can be user-defined as well.
  19810. The effect that is passed in will not be deleted by the component - the
  19811. caller must take care of deleting it.
  19812. To remove an effect from a component, pass a null pointer in as the parameter.
  19813. @see ImageEffectFilter, DropShadowEffect, GlowEffect
  19814. */
  19815. void setComponentEffect (ImageEffectFilter* newEffect);
  19816. /** Returns the current component effect.
  19817. @see setComponentEffect
  19818. */
  19819. ImageEffectFilter* getComponentEffect() const throw() { return effect_; }
  19820. /** Finds the appropriate look-and-feel to use for this component.
  19821. If the component hasn't had a look-and-feel explicitly set, this will
  19822. return the parent's look-and-feel, or just the default one if there's no
  19823. parent.
  19824. @see setLookAndFeel, lookAndFeelChanged
  19825. */
  19826. LookAndFeel& getLookAndFeel() const throw();
  19827. /** Sets the look and feel to use for this component.
  19828. This will also change the look and feel for any child components that haven't
  19829. had their look set explicitly.
  19830. The object passed in will not be deleted by the component, so it's the caller's
  19831. responsibility to manage it. It may be used at any time until this component
  19832. has been deleted.
  19833. Calling this method will also invoke the sendLookAndFeelChange() method.
  19834. @see getLookAndFeel, lookAndFeelChanged
  19835. */
  19836. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  19837. /** Called to let the component react to a change in the look-and-feel setting.
  19838. When the look-and-feel is changed for a component, this will be called in
  19839. all its child components, recursively.
  19840. It can also be triggered manually by the sendLookAndFeelChange() method, in case
  19841. an application uses a LookAndFeel class that might have changed internally.
  19842. @see sendLookAndFeelChange, getLookAndFeel
  19843. */
  19844. virtual void lookAndFeelChanged();
  19845. /** Calls the lookAndFeelChanged() method in this component and all its children.
  19846. This will recurse through the children and their children, calling lookAndFeelChanged()
  19847. on them all.
  19848. @see lookAndFeelChanged
  19849. */
  19850. void sendLookAndFeelChange();
  19851. /** Indicates whether any parts of the component might be transparent.
  19852. Components that always paint all of their contents with solid colour and
  19853. thus completely cover any components behind them should use this method
  19854. to tell the repaint system that they are opaque.
  19855. This information is used to optimise drawing, because it means that
  19856. objects underneath opaque windows don't need to be painted.
  19857. By default, components are considered transparent, unless this is used to
  19858. make it otherwise.
  19859. @see isOpaque, getVisibleArea
  19860. */
  19861. void setOpaque (bool shouldBeOpaque);
  19862. /** Returns true if no parts of this component are transparent.
  19863. @returns the value that was set by setOpaque, (the default being false)
  19864. @see setOpaque
  19865. */
  19866. bool isOpaque() const throw();
  19867. /** Indicates whether the component should be brought to the front when clicked.
  19868. Setting this flag to true will cause the component to be brought to the front
  19869. when the mouse is clicked somewhere inside it or its child components.
  19870. Note that a top-level desktop window might still be brought to the front by the
  19871. operating system when it's clicked, depending on how the OS works.
  19872. By default this is set to false.
  19873. @see setMouseClickGrabsKeyboardFocus
  19874. */
  19875. void setBroughtToFrontOnMouseClick (bool shouldBeBroughtToFront) throw();
  19876. /** Indicates whether the component should be brought to the front when clicked-on.
  19877. @see setBroughtToFrontOnMouseClick
  19878. */
  19879. bool isBroughtToFrontOnMouseClick() const throw();
  19880. // Keyboard focus methods
  19881. /** Sets a flag to indicate whether this component needs keyboard focus or not.
  19882. By default components aren't actually interested in gaining the
  19883. focus, but this method can be used to turn this on.
  19884. See the grabKeyboardFocus() method for details about the way a component
  19885. is chosen to receive the focus.
  19886. @see grabKeyboardFocus, getWantsKeyboardFocus
  19887. */
  19888. void setWantsKeyboardFocus (bool wantsFocus) throw();
  19889. /** Returns true if the component is interested in getting keyboard focus.
  19890. This returns the flag set by setWantsKeyboardFocus(). The default
  19891. setting is false.
  19892. @see setWantsKeyboardFocus
  19893. */
  19894. bool getWantsKeyboardFocus() const throw();
  19895. /** Chooses whether a click on this component automatically grabs the focus.
  19896. By default this is set to true, but you might want a component which can
  19897. be focused, but where you don't want the user to be able to affect it directly
  19898. by clicking.
  19899. */
  19900. void setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus);
  19901. /** Returns the last value set with setMouseClickGrabsKeyboardFocus().
  19902. See setMouseClickGrabsKeyboardFocus() for more info.
  19903. */
  19904. bool getMouseClickGrabsKeyboardFocus() const throw();
  19905. /** Tries to give keyboard focus to this component.
  19906. When the user clicks on a component or its grabKeyboardFocus()
  19907. method is called, the following procedure is used to work out which
  19908. component should get it:
  19909. - if the component that was clicked on actually wants focus (as indicated
  19910. by calling getWantsKeyboardFocus), it gets it.
  19911. - if the component itself doesn't want focus, it will try to pass it
  19912. on to whichever of its children is the default component, as determined by
  19913. KeyboardFocusTraverser::getDefaultComponent()
  19914. - if none of its children want focus at all, it will pass it up to its
  19915. parent instead, unless it's a top-level component without a parent,
  19916. in which case it just takes the focus itself.
  19917. @see setWantsKeyboardFocus, getWantsKeyboardFocus, hasKeyboardFocus,
  19918. getCurrentlyFocusedComponent, focusGained, focusLost,
  19919. keyPressed, keyStateChanged
  19920. */
  19921. void grabKeyboardFocus();
  19922. /** Returns true if this component currently has the keyboard focus.
  19923. @param trueIfChildIsFocused if this is true, then the method returns true if
  19924. either this component or any of its children (recursively)
  19925. have the focus. If false, the method only returns true if
  19926. this component has the focus.
  19927. @see grabKeyboardFocus, setWantsKeyboardFocus, getCurrentlyFocusedComponent,
  19928. focusGained, focusLost
  19929. */
  19930. bool hasKeyboardFocus (bool trueIfChildIsFocused) const;
  19931. /** Returns the component that currently has the keyboard focus.
  19932. @returns the focused component, or null if nothing is focused.
  19933. */
  19934. static Component* JUCE_CALLTYPE getCurrentlyFocusedComponent() throw();
  19935. /** Tries to move the keyboard focus to one of this component's siblings.
  19936. This will try to move focus to either the next or previous component. (This
  19937. is the method that is used when shifting focus by pressing the tab key).
  19938. Components for which getWantsKeyboardFocus() returns false are not looked at.
  19939. @param moveToNext if true, the focus will move forwards; if false, it will
  19940. move backwards
  19941. @see grabKeyboardFocus, setFocusContainer, setWantsKeyboardFocus
  19942. */
  19943. void moveKeyboardFocusToSibling (bool moveToNext);
  19944. /** Creates a KeyboardFocusTraverser object to use to determine the logic by
  19945. which focus should be passed from this component.
  19946. The default implementation of this method will return a default
  19947. KeyboardFocusTraverser if this component is a focus container (as determined
  19948. by the setFocusContainer() method). If the component isn't a focus
  19949. container, then it will recursively ask its parents for a KeyboardFocusTraverser.
  19950. If you overrride this to return a custom KeyboardFocusTraverser, then
  19951. this component and all its sub-components will use the new object to
  19952. make their focusing decisions.
  19953. The method should return a new object, which the caller is required to
  19954. delete when no longer needed.
  19955. */
  19956. virtual KeyboardFocusTraverser* createFocusTraverser();
  19957. /** Returns the focus order of this component, if one has been specified.
  19958. By default components don't have a focus order - in that case, this
  19959. will return 0. Lower numbers indicate that the component will be
  19960. earlier in the focus traversal order.
  19961. To change the order, call setExplicitFocusOrder().
  19962. The focus order may be used by the KeyboardFocusTraverser class as part of
  19963. its algorithm for deciding the order in which components should be traversed.
  19964. See the KeyboardFocusTraverser class for more details on this.
  19965. @see moveKeyboardFocusToSibling, createFocusTraverser, KeyboardFocusTraverser
  19966. */
  19967. int getExplicitFocusOrder() const;
  19968. /** Sets the index used in determining the order in which focusable components
  19969. should be traversed.
  19970. A value of 0 or less is taken to mean that no explicit order is wanted, and
  19971. that traversal should use other factors, like the component's position.
  19972. @see getExplicitFocusOrder, moveKeyboardFocusToSibling
  19973. */
  19974. void setExplicitFocusOrder (int newFocusOrderIndex);
  19975. /** Indicates whether this component is a parent for components that can have
  19976. their focus traversed.
  19977. This flag is used by the default implementation of the createFocusTraverser()
  19978. method, which uses the flag to find the first parent component (of the currently
  19979. focused one) which wants to be a focus container.
  19980. So using this method to set the flag to 'true' causes this component to
  19981. act as the top level within which focus is passed around.
  19982. @see isFocusContainer, createFocusTraverser, moveKeyboardFocusToSibling
  19983. */
  19984. void setFocusContainer (bool shouldBeFocusContainer) throw();
  19985. /** Returns true if this component has been marked as a focus container.
  19986. See setFocusContainer() for more details.
  19987. @see setFocusContainer, moveKeyboardFocusToSibling, createFocusTraverser
  19988. */
  19989. bool isFocusContainer() const throw();
  19990. /** Returns true if the component (and all its parents) are enabled.
  19991. Components are enabled by default, and can be disabled with setEnabled(). Exactly
  19992. what difference this makes to the component depends on the type. E.g. buttons
  19993. and sliders will choose to draw themselves differently, etc.
  19994. Note that if one of this component's parents is disabled, this will always
  19995. return false, even if this component itself is enabled.
  19996. @see setEnabled, enablementChanged
  19997. */
  19998. bool isEnabled() const throw();
  19999. /** Enables or disables this component.
  20000. Disabling a component will also cause all of its child components to become
  20001. disabled.
  20002. Similarly, enabling a component which is inside a disabled parent
  20003. component won't make any difference until the parent is re-enabled.
  20004. @see isEnabled, enablementChanged
  20005. */
  20006. void setEnabled (bool shouldBeEnabled);
  20007. /** Callback to indicate that this component has been enabled or disabled.
  20008. This can be triggered by one of the component's parent components
  20009. being enabled or disabled, as well as changes to the component itself.
  20010. The default implementation of this method does nothing; your class may
  20011. wish to repaint itself or something when this happens.
  20012. @see setEnabled, isEnabled
  20013. */
  20014. virtual void enablementChanged();
  20015. /** Changes the mouse cursor shape to use when the mouse is over this component.
  20016. Note that the cursor set by this method can be overridden by the getMouseCursor
  20017. method.
  20018. @see MouseCursor
  20019. */
  20020. void setMouseCursor (const MouseCursor& cursorType);
  20021. /** Returns the mouse cursor shape to use when the mouse is over this component.
  20022. The default implementation will return the cursor that was set by setCursor()
  20023. but can be overridden for more specialised purposes, e.g. returning different
  20024. cursors depending on the mouse position.
  20025. @see MouseCursor
  20026. */
  20027. virtual const MouseCursor getMouseCursor();
  20028. /** Forces the current mouse cursor to be updated.
  20029. If you're overriding the getMouseCursor() method to control which cursor is
  20030. displayed, then this will only be checked each time the user moves the mouse. So
  20031. if you want to force the system to check that the cursor being displayed is
  20032. up-to-date (even if the mouse is just sitting there), call this method.
  20033. This isn't needed if you're only using setMouseCursor().
  20034. */
  20035. void updateMouseCursor() const;
  20036. /** Components can override this method to draw their content.
  20037. The paint() method gets called when a region of a component needs redrawing,
  20038. either because the component's repaint() method has been called, or because
  20039. something has happened on the screen that means a section of a window needs
  20040. to be redrawn.
  20041. Any child components will draw themselves over whatever this method draws. If
  20042. you need to paint over the top of your child components, you can also implement
  20043. the paintOverChildren() method to do this.
  20044. If you want to cause a component to redraw itself, this is done asynchronously -
  20045. calling the repaint() method marks a region of the component as "dirty", and the
  20046. paint() method will automatically be called sometime later, by the message thread,
  20047. to paint any bits that need refreshing. In Juce (and almost all modern UI frameworks),
  20048. you never redraw something synchronously.
  20049. You should never need to call this method directly - to take a snapshot of the
  20050. component you could use createComponentSnapshot() or paintEntireComponent().
  20051. @param g the graphics context that must be used to do the drawing operations.
  20052. @see repaint, paintOverChildren, Graphics
  20053. */
  20054. virtual void paint (Graphics& g);
  20055. /** Components can override this method to draw over the top of their children.
  20056. For most drawing operations, it's better to use the normal paint() method,
  20057. but if you need to overlay something on top of the children, this can be
  20058. used.
  20059. @see paint, Graphics
  20060. */
  20061. virtual void paintOverChildren (Graphics& g);
  20062. /** Called when the mouse moves inside this component.
  20063. If the mouse button isn't pressed and the mouse moves over a component,
  20064. this will be called to let the component react to this.
  20065. A component will always get a mouseEnter callback before a mouseMove.
  20066. @param e details about the position and status of the mouse event
  20067. @see mouseEnter, mouseExit, mouseDrag, contains
  20068. */
  20069. virtual void mouseMove (const MouseEvent& e);
  20070. /** Called when the mouse first enters this component.
  20071. If the mouse button isn't pressed and the mouse moves into a component,
  20072. this will be called to let the component react to this.
  20073. When the mouse button is pressed and held down while being moved in
  20074. or out of a component, no mouseEnter or mouseExit callbacks are made - only
  20075. mouseDrag messages are sent to the component that the mouse was originally
  20076. clicked on, until the button is released.
  20077. If you're writing a component that needs to repaint itself when the mouse
  20078. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  20079. method.
  20080. @param e details about the position and status of the mouse event
  20081. @see mouseExit, mouseDrag, mouseMove, contains
  20082. */
  20083. virtual void mouseEnter (const MouseEvent& e);
  20084. /** Called when the mouse moves out of this component.
  20085. This will be called when the mouse moves off the edge of this
  20086. component.
  20087. If the mouse button was pressed, and it was then dragged off the
  20088. edge of the component and released, then this callback will happen
  20089. when the button is released, after the mouseUp callback.
  20090. If you're writing a component that needs to repaint itself when the mouse
  20091. enters and exits, it might be quicker to use the setRepaintsOnMouseActivity()
  20092. method.
  20093. @param e details about the position and status of the mouse event
  20094. @see mouseEnter, mouseDrag, mouseMove, contains
  20095. */
  20096. virtual void mouseExit (const MouseEvent& e);
  20097. /** Called when a mouse button is pressed while it's over this component.
  20098. The MouseEvent object passed in contains lots of methods for finding out
  20099. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  20100. were held down at the time.
  20101. Once a button is held down, the mouseDrag method will be called when the
  20102. mouse moves, until the button is released.
  20103. @param e details about the position and status of the mouse event
  20104. @see mouseUp, mouseDrag, mouseDoubleClick, contains
  20105. */
  20106. virtual void mouseDown (const MouseEvent& e);
  20107. /** Called when the mouse is moved while a button is held down.
  20108. When a mouse button is pressed inside a component, that component
  20109. receives mouseDrag callbacks each time the mouse moves, even if the
  20110. mouse strays outside the component's bounds.
  20111. If you want to be able to drag things off the edge of a component
  20112. and have the component scroll when you get to the edges, the
  20113. beginDragAutoRepeat() method might be useful.
  20114. @param e details about the position and status of the mouse event
  20115. @see mouseDown, mouseUp, mouseMove, contains, beginDragAutoRepeat
  20116. */
  20117. virtual void mouseDrag (const MouseEvent& e);
  20118. /** Called when a mouse button is released.
  20119. A mouseUp callback is sent to the component in which a button was pressed
  20120. even if the mouse is actually over a different component when the
  20121. button is released.
  20122. The MouseEvent object passed in contains lots of methods for finding out
  20123. which buttons were down just before they were released.
  20124. @param e details about the position and status of the mouse event
  20125. @see mouseDown, mouseDrag, mouseDoubleClick, contains
  20126. */
  20127. virtual void mouseUp (const MouseEvent& e);
  20128. /** Called when a mouse button has been double-clicked in this component.
  20129. The MouseEvent object passed in contains lots of methods for finding out
  20130. which button was pressed, as well as which modifier keys (e.g. shift, ctrl)
  20131. were held down at the time.
  20132. For altering the time limit used to detect double-clicks,
  20133. see MouseEvent::setDoubleClickTimeout.
  20134. @param e details about the position and status of the mouse event
  20135. @see mouseDown, mouseUp, MouseEvent::setDoubleClickTimeout,
  20136. MouseEvent::getDoubleClickTimeout
  20137. */
  20138. virtual void mouseDoubleClick (const MouseEvent& e);
  20139. /** Called when the mouse-wheel is moved.
  20140. This callback is sent to the component that the mouse is over when the
  20141. wheel is moved.
  20142. If not overridden, the component will forward this message to its parent, so
  20143. that parent components can collect mouse-wheel messages that happen to
  20144. child components which aren't interested in them.
  20145. @param e details about the position and status of the mouse event
  20146. @param wheelIncrementX the speed and direction of the horizontal scroll-wheel - a positive
  20147. value means the wheel has been pushed to the right, negative means it
  20148. was pushed to the left
  20149. @param wheelIncrementY the speed and direction of the vertical scroll-wheel - a positive
  20150. value means the wheel has been pushed upwards, negative means it
  20151. was pushed downwards
  20152. */
  20153. virtual void mouseWheelMove (const MouseEvent& e,
  20154. float wheelIncrementX,
  20155. float wheelIncrementY);
  20156. /** Ensures that a non-stop stream of mouse-drag events will be sent during the
  20157. next mouse-drag operation.
  20158. This allows you to make sure that mouseDrag() events sent continuously, even
  20159. when the mouse isn't moving. This can be useful for things like auto-scrolling
  20160. components when the mouse is near an edge.
  20161. Call this method during a mouseDown() or mouseDrag() callback, specifying the
  20162. minimum interval between consecutive mouse drag callbacks. The callbacks
  20163. will continue until the mouse is released, and then the interval will be reset,
  20164. so you need to make sure it's called every time you begin a drag event. If it
  20165. is called when the mouse isn't actually being pressed, it will apply to the next
  20166. mouse-drag operation that happens.
  20167. Passing an interval of 0 or less will cancel the auto-repeat.
  20168. @see mouseDrag
  20169. */
  20170. static void beginDragAutoRepeat (int millisecondIntervalBetweenCallbacks);
  20171. /** Causes automatic repaints when the mouse enters or exits this component.
  20172. If turned on, then when the mouse enters/exits, or when the button is pressed/released
  20173. on the component, it will trigger a repaint.
  20174. This is handy for things like buttons that need to draw themselves differently when
  20175. the mouse moves over them, and it avoids having to override all the different mouse
  20176. callbacks and call repaint().
  20177. @see mouseEnter, mouseExit, mouseDown, mouseUp
  20178. */
  20179. void setRepaintsOnMouseActivity (bool shouldRepaint) throw();
  20180. /** Registers a listener to be told when mouse events occur in this component.
  20181. If you need to get informed about mouse events in a component but can't or
  20182. don't want to override its methods, you can attach any number of listeners
  20183. to the component, and these will get told about the events in addition to
  20184. the component's own callbacks being called.
  20185. Note that a MouseListener can also be attached to more than one component.
  20186. @param newListener the listener to register
  20187. @param wantsEventsForAllNestedChildComponents if true, the listener will receive callbacks
  20188. for events that happen to any child component
  20189. within this component, including deeply-nested
  20190. child components. If false, it will only be
  20191. told about events that this component handles.
  20192. @see MouseListener, removeMouseListener
  20193. */
  20194. void addMouseListener (MouseListener* newListener,
  20195. bool wantsEventsForAllNestedChildComponents);
  20196. /** Deregisters a mouse listener.
  20197. @see addMouseListener, MouseListener
  20198. */
  20199. void removeMouseListener (MouseListener* listenerToRemove);
  20200. /** Adds a listener that wants to hear about keypresses that this component receives.
  20201. The listeners that are registered with a component are called by its keyPressed() or
  20202. keyStateChanged() methods (assuming these haven't been overridden to do something else).
  20203. If you add an object as a key listener, be careful to remove it when the object
  20204. is deleted, or the component will be left with a dangling pointer.
  20205. @see keyPressed, keyStateChanged, removeKeyListener
  20206. */
  20207. void addKeyListener (KeyListener* newListener);
  20208. /** Removes a previously-registered key listener.
  20209. @see addKeyListener
  20210. */
  20211. void removeKeyListener (KeyListener* listenerToRemove);
  20212. /** Called when a key is pressed.
  20213. When a key is pressed, the component that has the keyboard focus will have this
  20214. method called. Remember that a component will only be given the focus if its
  20215. setWantsKeyboardFocus() method has been used to enable this.
  20216. If your implementation returns true, the event will be consumed and not passed
  20217. on to any other listeners. If it returns false, the key will be passed to any
  20218. KeyListeners that have been registered with this component. As soon as one of these
  20219. returns true, the process will stop, but if they all return false, the event will
  20220. be passed upwards to this component's parent, and so on.
  20221. The default implementation of this method does nothing and returns false.
  20222. @see keyStateChanged, getCurrentlyFocusedComponent, addKeyListener
  20223. */
  20224. virtual bool keyPressed (const KeyPress& key);
  20225. /** Called when a key is pressed or released.
  20226. Whenever a key on the keyboard is pressed or released (including modifier keys
  20227. like shift and ctrl), this method will be called on the component that currently
  20228. has the keyboard focus. Remember that a component will only be given the focus if
  20229. its setWantsKeyboardFocus() method has been used to enable this.
  20230. If your implementation returns true, the event will be consumed and not passed
  20231. on to any other listeners. If it returns false, then any KeyListeners that have
  20232. been registered with this component will have their keyStateChanged methods called.
  20233. As soon as one of these returns true, the process will stop, but if they all return
  20234. false, the event will be passed upwards to this component's parent, and so on.
  20235. The default implementation of this method does nothing and returns false.
  20236. To find out which keys are up or down at any time, see the KeyPress::isKeyCurrentlyDown()
  20237. method.
  20238. @param isKeyDown true if a key has been pressed; false if it has been released
  20239. @see keyPressed, KeyPress, getCurrentlyFocusedComponent, addKeyListener
  20240. */
  20241. virtual bool keyStateChanged (bool isKeyDown);
  20242. /** Called when a modifier key is pressed or released.
  20243. Whenever the shift, control, alt or command keys are pressed or released,
  20244. this method will be called on the component that currently has the keyboard focus.
  20245. Remember that a component will only be given the focus if its setWantsKeyboardFocus()
  20246. method has been used to enable this.
  20247. The default implementation of this method actually calls its parent's modifierKeysChanged
  20248. method, so that focused components which aren't interested in this will give their
  20249. parents a chance to act on the event instead.
  20250. @see keyStateChanged, ModifierKeys
  20251. */
  20252. virtual void modifierKeysChanged (const ModifierKeys& modifiers);
  20253. /** Enumeration used by the focusChanged() and focusLost() methods. */
  20254. enum FocusChangeType
  20255. {
  20256. focusChangedByMouseClick, /**< Means that the user clicked the mouse to change focus. */
  20257. focusChangedByTabKey, /**< Means that the user pressed the tab key to move the focus. */
  20258. focusChangedDirectly /**< Means that the focus was changed by a call to grabKeyboardFocus(). */
  20259. };
  20260. /** Called to indicate that this component has just acquired the keyboard focus.
  20261. @see focusLost, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20262. */
  20263. virtual void focusGained (FocusChangeType cause);
  20264. /** Called to indicate that this component has just lost the keyboard focus.
  20265. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20266. */
  20267. virtual void focusLost (FocusChangeType cause);
  20268. /** Called to indicate that one of this component's children has been focused or unfocused.
  20269. Essentially this means that the return value of a call to hasKeyboardFocus (true) has
  20270. changed. It happens when focus moves from one of this component's children (at any depth)
  20271. to a component that isn't contained in this one, (or vice-versa).
  20272. @see focusGained, setWantsKeyboardFocus, getCurrentlyFocusedComponent, hasKeyboardFocus
  20273. */
  20274. virtual void focusOfChildComponentChanged (FocusChangeType cause);
  20275. /** Returns true if the mouse is currently over this component.
  20276. If the mouse isn't over the component, this will return false, even if the
  20277. mouse is currently being dragged - so you can use this in your mouseDrag
  20278. method to find out whether it's really over the component or not.
  20279. Note that when the mouse button is being held down, then the only component
  20280. for which this method will return true is the one that was originally
  20281. clicked on.
  20282. @see isMouseButtonDown. isMouseOverOrDragging, mouseDrag
  20283. */
  20284. bool isMouseOver() const throw();
  20285. /** Returns true if the mouse button is currently held down in this component.
  20286. Note that this is a test to see whether the mouse is being pressed in this
  20287. component, so it'll return false if called on component A when the mouse
  20288. is actually being dragged in component B.
  20289. @see isMouseButtonDownAnywhere, isMouseOver, isMouseOverOrDragging
  20290. */
  20291. bool isMouseButtonDown() const throw();
  20292. /** True if the mouse is over this component, or if it's being dragged in this component.
  20293. This is a handy equivalent to (isMouseOver() || isMouseButtonDown()).
  20294. @see isMouseOver, isMouseButtonDown, isMouseButtonDownAnywhere
  20295. */
  20296. bool isMouseOverOrDragging() const throw();
  20297. /** Returns true if a mouse button is currently down.
  20298. Unlike isMouseButtonDown, this will test the current state of the
  20299. buttons without regard to which component (if any) it has been
  20300. pressed in.
  20301. @see isMouseButtonDown, ModifierKeys
  20302. */
  20303. static bool JUCE_CALLTYPE isMouseButtonDownAnywhere() throw();
  20304. /** Returns the mouse's current position, relative to this component.
  20305. The co-ordinates are relative to the component's top-left corner.
  20306. */
  20307. const Point<int> getMouseXYRelative() const;
  20308. /** Called when this component's size has been changed.
  20309. A component can implement this method to do things such as laying out its
  20310. child components when its width or height changes.
  20311. The method is called synchronously as a result of the setBounds or setSize
  20312. methods, so repeatedly changing a components size will repeatedly call its
  20313. resized method (unlike things like repainting, where multiple calls to repaint
  20314. are coalesced together).
  20315. If the component is a top-level window on the desktop, its size could also
  20316. be changed by operating-system factors beyond the application's control.
  20317. @see moved, setSize
  20318. */
  20319. virtual void resized();
  20320. /** Called when this component's position has been changed.
  20321. This is called when the position relative to its parent changes, not when
  20322. its absolute position on the screen changes (so it won't be called for
  20323. all child components when a parent component is moved).
  20324. The method is called synchronously as a result of the setBounds, setTopLeftPosition
  20325. or any of the other repositioning methods, and like resized(), it will be
  20326. called each time those methods are called.
  20327. If the component is a top-level window on the desktop, its position could also
  20328. be changed by operating-system factors beyond the application's control.
  20329. @see resized, setBounds
  20330. */
  20331. virtual void moved();
  20332. /** Called when one of this component's children is moved or resized.
  20333. If the parent wants to know about changes to its immediate children (not
  20334. to children of its children), this is the method to override.
  20335. @see moved, resized, parentSizeChanged
  20336. */
  20337. virtual void childBoundsChanged (Component* child);
  20338. /** Called when this component's immediate parent has been resized.
  20339. If the component is a top-level window, this indicates that the screen size
  20340. has changed.
  20341. @see childBoundsChanged, moved, resized
  20342. */
  20343. virtual void parentSizeChanged();
  20344. /** Called when this component has been moved to the front of its siblings.
  20345. The component may have been brought to the front by the toFront() method, or
  20346. by the operating system if it's a top-level window.
  20347. @see toFront
  20348. */
  20349. virtual void broughtToFront();
  20350. /** Adds a listener to be told about changes to the component hierarchy or position.
  20351. Component listeners get called when this component's size, position or children
  20352. change - see the ComponentListener class for more details.
  20353. @param newListener the listener to register - if this is already registered, it
  20354. will be ignored.
  20355. @see ComponentListener, removeComponentListener
  20356. */
  20357. void addComponentListener (ComponentListener* newListener);
  20358. /** Removes a component listener.
  20359. @see addComponentListener
  20360. */
  20361. void removeComponentListener (ComponentListener* listenerToRemove);
  20362. /** Dispatches a numbered message to this component.
  20363. This is a quick and cheap way of allowing simple asynchronous messages to
  20364. be sent to components. It's also safe, because if the component that you
  20365. send the message to is a null or dangling pointer, this won't cause an error.
  20366. The command ID is later delivered to the component's handleCommandMessage() method by
  20367. the application's message queue.
  20368. @see handleCommandMessage
  20369. */
  20370. void postCommandMessage (int commandId);
  20371. /** Called to handle a command that was sent by postCommandMessage().
  20372. This is called by the message thread when a command message arrives, and
  20373. the component can override this method to process it in any way it needs to.
  20374. @see postCommandMessage
  20375. */
  20376. virtual void handleCommandMessage (int commandId);
  20377. /** Runs a component modally, waiting until the loop terminates.
  20378. This method first makes the component visible, brings it to the front and
  20379. gives it the keyboard focus.
  20380. It then runs a loop, dispatching messages from the system message queue, but
  20381. blocking all mouse or keyboard messages from reaching any components other
  20382. than this one and its children.
  20383. This loop continues until the component's exitModalState() method is called (or
  20384. the component is deleted), and then this method returns, returning the value
  20385. passed into exitModalState().
  20386. @see enterModalState, exitModalState, isCurrentlyModal, getCurrentlyModalComponent,
  20387. isCurrentlyBlockedByAnotherModalComponent, ModalComponentManager
  20388. */
  20389. int runModalLoop();
  20390. /** Puts the component into a modal state.
  20391. This makes the component modal, so that messages are blocked from reaching
  20392. any components other than this one and its children, but unlike runModalLoop(),
  20393. this method returns immediately.
  20394. If takeKeyboardFocus is true, the component will use grabKeyboardFocus() to
  20395. get the focus, which is usually what you'll want it to do. If not, it will leave
  20396. the focus unchanged.
  20397. The callback is an optional object which will receive a callback when the modal
  20398. component loses its modal status, either by being hidden or when exitModalState()
  20399. is called. If you pass an object in here, the system will take care of deleting it
  20400. later, after making the callback
  20401. @see exitModalState, runModalLoop, ModalComponentManager::attachCallback
  20402. */
  20403. void enterModalState (bool takeKeyboardFocus = true,
  20404. ModalComponentManager::Callback* callback = 0);
  20405. /** Ends a component's modal state.
  20406. If this component is currently modal, this will turn of its modalness, and return
  20407. a value to the runModalLoop() method that might have be running its modal loop.
  20408. @see runModalLoop, enterModalState, isCurrentlyModal
  20409. */
  20410. void exitModalState (int returnValue);
  20411. /** Returns true if this component is the modal one.
  20412. It's possible to have nested modal components, e.g. a pop-up dialog box
  20413. that launches another pop-up, but this will only return true for
  20414. the one at the top of the stack.
  20415. @see getCurrentlyModalComponent
  20416. */
  20417. bool isCurrentlyModal() const throw();
  20418. /** Returns the number of components that are currently in a modal state.
  20419. @see getCurrentlyModalComponent
  20420. */
  20421. static int JUCE_CALLTYPE getNumCurrentlyModalComponents() throw();
  20422. /** Returns one of the components that are currently modal.
  20423. The index specifies which of the possible modal components to return. The order
  20424. of the components in this list is the reverse of the order in which they became
  20425. modal - so the component at index 0 is always the active component, and the others
  20426. are progressively earlier ones that are themselves now blocked by later ones.
  20427. @returns the modal component, or null if no components are modal (or if the
  20428. index is out of range)
  20429. @see getNumCurrentlyModalComponents, runModalLoop, isCurrentlyModal
  20430. */
  20431. static Component* JUCE_CALLTYPE getCurrentlyModalComponent (int index = 0) throw();
  20432. /** Checks whether there's a modal component somewhere that's stopping this one
  20433. from receiving messages.
  20434. If there is a modal component, its canModalEventBeSentToComponent() method
  20435. will be called to see if it will still allow this component to receive events.
  20436. @see runModalLoop, getCurrentlyModalComponent
  20437. */
  20438. bool isCurrentlyBlockedByAnotherModalComponent() const;
  20439. /** When a component is modal, this callback allows it to choose which other
  20440. components can still receive events.
  20441. When a modal component is active and the user clicks on a non-modal component,
  20442. this method is called on the modal component, and if it returns true, the
  20443. event is allowed to reach its target. If it returns false, the event is blocked
  20444. and the inputAttemptWhenModal() callback is made.
  20445. It called by the isCurrentlyBlockedByAnotherModalComponent() method. The default
  20446. implementation just returns false in all cases.
  20447. */
  20448. virtual bool canModalEventBeSentToComponent (const Component* targetComponent);
  20449. /** Called when the user tries to click on a component that is blocked by another
  20450. modal component.
  20451. When a component is modal and the user clicks on one of the other components,
  20452. the modal component will receive this callback.
  20453. The default implementation of this method will play a beep, and bring the currently
  20454. modal component to the front, but it can be overridden to do other tasks.
  20455. @see isCurrentlyBlockedByAnotherModalComponent, canModalEventBeSentToComponent
  20456. */
  20457. virtual void inputAttemptWhenModal();
  20458. /** Returns the set of properties that belong to this component.
  20459. Each component has a NamedValueSet object which you can use to attach arbitrary
  20460. items of data to it.
  20461. */
  20462. NamedValueSet& getProperties() throw() { return properties; }
  20463. /** Returns the set of properties that belong to this component.
  20464. Each component has a NamedValueSet object which you can use to attach arbitrary
  20465. items of data to it.
  20466. */
  20467. const NamedValueSet& getProperties() const throw() { return properties; }
  20468. /** Looks for a colour that has been registered with the given colour ID number.
  20469. If a colour has been set for this ID number using setColour(), then it is
  20470. returned. If none has been set, the method will try calling the component's
  20471. LookAndFeel class's findColour() method. If none has been registered with the
  20472. look-and-feel either, it will just return black.
  20473. The colour IDs for various purposes are stored as enums in the components that
  20474. they are relevent to - for an example, see Slider::ColourIds,
  20475. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  20476. @see setColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20477. */
  20478. const Colour findColour (int colourId, bool inheritFromParent = false) const;
  20479. /** Registers a colour to be used for a particular purpose.
  20480. Changing a colour will cause a synchronous callback to the colourChanged()
  20481. method, which your component can override if it needs to do something when
  20482. colours are altered.
  20483. For more details about colour IDs, see the comments for findColour().
  20484. @see findColour, isColourSpecified, colourChanged, LookAndFeel::findColour, LookAndFeel::setColour
  20485. */
  20486. void setColour (int colourId, const Colour& colour);
  20487. /** If a colour has been set with setColour(), this will remove it.
  20488. This allows you to make a colour revert to its default state.
  20489. */
  20490. void removeColour (int colourId);
  20491. /** Returns true if the specified colour ID has been explicitly set for this
  20492. component using the setColour() method.
  20493. */
  20494. bool isColourSpecified (int colourId) const;
  20495. /** This looks for any colours that have been specified for this component,
  20496. and copies them to the specified target component.
  20497. */
  20498. void copyAllExplicitColoursTo (Component& target) const;
  20499. /** This method is called when a colour is changed by the setColour() method.
  20500. @see setColour, findColour
  20501. */
  20502. virtual void colourChanged();
  20503. /** Returns the underlying native window handle for this component.
  20504. This is platform-dependent and strictly for power-users only!
  20505. */
  20506. void* getWindowHandle() const;
  20507. /** When created, each component is given a number to uniquely identify it.
  20508. The number is incremented each time a new component is created, so it's a more
  20509. unique way of identifying a component than using its memory location (which
  20510. may be reused after the component is deleted, of course).
  20511. */
  20512. uint32 getComponentUID() const throw() { return componentUID; }
  20513. /** Holds a pointer to some type of Component, which automatically becomes null if
  20514. the component is deleted.
  20515. If you're using a component which may be deleted by another event that's outside
  20516. of your control, use a SafePointer instead of a normal pointer to refer to it,
  20517. and you can test whether it's null before using it to see if something has deleted
  20518. it.
  20519. The ComponentType typedef must be Component, or some subclass of Component.
  20520. Note that this class isn't thread-safe, and assumes that all the code that uses
  20521. it is running on the message thread.
  20522. */
  20523. template <class ComponentType>
  20524. class SafePointer : private ComponentListener
  20525. {
  20526. public:
  20527. /** Creates a null SafePointer. */
  20528. SafePointer() : comp (0) {}
  20529. /** Creates a SafePointer that points at the given component. */
  20530. SafePointer (ComponentType* const component) : comp (component) { attach(); }
  20531. /** Creates a copy of another SafePointer. */
  20532. SafePointer (const SafePointer& other) : comp (other.comp) { attach(); }
  20533. /** Destructor. */
  20534. ~SafePointer() { detach(); }
  20535. /** Copies another pointer to this one. */
  20536. SafePointer& operator= (const SafePointer& other) { return operator= (other.comp); }
  20537. /** Copies another pointer to this one. */
  20538. SafePointer& operator= (ComponentType* const newComponent)
  20539. {
  20540. detach();
  20541. comp = newComponent;
  20542. attach();
  20543. return *this;
  20544. }
  20545. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20546. operator ComponentType*() const throw() { return comp; }
  20547. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20548. ComponentType* getComponent() const throw() { return comp; }
  20549. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20550. ComponentType* operator->() throw() { jassert (comp != 0); return comp; }
  20551. /** Returns the component that this pointer refers to, or null if the component no longer exists. */
  20552. const ComponentType* operator->() const throw() { jassert (comp != 0); return comp; }
  20553. juce_UseDebuggingNewOperator
  20554. private:
  20555. ComponentType* comp;
  20556. void attach() { if (comp != 0) comp->addComponentListener (this); }
  20557. void detach() { if (comp != 0) comp->removeComponentListener (this); }
  20558. void componentBeingDeleted (Component&) { comp = 0; }
  20559. };
  20560. /** A class to keep an eye on one or two components and check for them being deleted.
  20561. This is designed for use with the ListenerList::callChecked() methods, to allow
  20562. the list iterator to stop cleanly if the component is deleted by a listener callback
  20563. while the list is still being iterated.
  20564. */
  20565. class BailOutChecker
  20566. {
  20567. public:
  20568. /** Creates a checker that watches either one or two components.
  20569. component1 must be a valid component; component2 can be null if you only need
  20570. to check on one component.
  20571. */
  20572. BailOutChecker (Component* component1,
  20573. Component* component2 = 0);
  20574. /** Returns true if either of the two components have been deleted since this
  20575. object was created. */
  20576. bool shouldBailOut() const throw();
  20577. private:
  20578. typedef SafePointer<Component> SafeComponentPtr;
  20579. SafeComponentPtr safePointer1, safePointer2;
  20580. Component* const component2;
  20581. BailOutChecker (const BailOutChecker&);
  20582. BailOutChecker& operator= (const BailOutChecker&);
  20583. };
  20584. juce_UseDebuggingNewOperator
  20585. private:
  20586. friend class ComponentPeer;
  20587. friend class InternalDragRepeater;
  20588. friend class MouseInputSource;
  20589. friend class MouseInputSourceInternal;
  20590. static Component* currentlyFocusedComponent;
  20591. String componentName_;
  20592. Component* parentComponent_;
  20593. uint32 componentUID;
  20594. Rectangle<int> bounds_;
  20595. int numDeepMouseListeners;
  20596. Array <Component*> childComponentList_;
  20597. LookAndFeel* lookAndFeel_;
  20598. MouseCursor cursor_;
  20599. ImageEffectFilter* effect_;
  20600. Image bufferedImage_;
  20601. Array <MouseListener*>* mouseListeners_;
  20602. Array <KeyListener*>* keyListeners_;
  20603. ListenerList <ComponentListener> componentListeners;
  20604. NamedValueSet properties;
  20605. struct ComponentFlags
  20606. {
  20607. bool hasHeavyweightPeerFlag : 1;
  20608. bool visibleFlag : 1;
  20609. bool opaqueFlag : 1;
  20610. bool ignoresMouseClicksFlag : 1;
  20611. bool allowChildMouseClicksFlag : 1;
  20612. bool wantsFocusFlag : 1;
  20613. bool isFocusContainerFlag : 1;
  20614. bool dontFocusOnMouseClickFlag : 1;
  20615. bool alwaysOnTopFlag : 1;
  20616. bool bufferToImageFlag : 1;
  20617. bool bringToFrontOnClickFlag : 1;
  20618. bool repaintOnMouseActivityFlag : 1;
  20619. bool draggingFlag : 1;
  20620. bool mouseOverFlag : 1;
  20621. bool mouseInsideFlag : 1;
  20622. bool currentlyModalFlag : 1;
  20623. bool isDisabledFlag : 1;
  20624. bool childCompFocusedFlag : 1;
  20625. #if JUCE_DEBUG
  20626. bool isInsidePaintCall : 1;
  20627. #endif
  20628. };
  20629. union
  20630. {
  20631. uint32 componentFlags_;
  20632. ComponentFlags flags;
  20633. };
  20634. void internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20635. void internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20636. void internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20637. void internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers);
  20638. void internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20639. void internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time);
  20640. void internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos, const Time& time, float amountX, float amountY);
  20641. void internalBroughtToFront();
  20642. void internalFocusGain (const FocusChangeType cause);
  20643. void internalFocusLoss (const FocusChangeType cause);
  20644. void internalChildFocusChange (FocusChangeType cause);
  20645. void internalModalInputAttempt();
  20646. void internalModifierKeysChanged();
  20647. void internalChildrenChanged();
  20648. void internalHierarchyChanged();
  20649. void renderComponent (Graphics& context);
  20650. void sendMovedResizedMessages (bool wasMoved, bool wasResized);
  20651. void repaintParent();
  20652. void sendFakeMouseMove() const;
  20653. void takeKeyboardFocus (const FocusChangeType cause);
  20654. void grabFocusInternal (const FocusChangeType cause, bool canTryParent = true);
  20655. static void giveAwayFocus();
  20656. void sendEnablementChangeMessage();
  20657. static void* runModalLoopCallback (void*);
  20658. static void bringModalComponentToFront();
  20659. void subtractObscuredRegions (RectangleList& result, const Point<int>& delta,
  20660. const Rectangle<int>& clipRect,
  20661. const Component* const compToAvoid) const;
  20662. void clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  20663. int deltaX, int deltaY) const;
  20664. // how much of the component is not off the edges of its parents
  20665. const Rectangle<int> getUnclippedArea() const;
  20666. void sendVisibilityChangeMessage();
  20667. const Rectangle<int> getParentOrMainMonitorBounds() const;
  20668. // This is included here just to cause a compile error if your code is still handling
  20669. // drag-and-drop with this method. If so, just update it to use the new FileDragAndDropTarget
  20670. // class, which is easy (just make your class inherit from FileDragAndDropTarget, and
  20671. // implement its methods instead of this Component method).
  20672. virtual void filesDropped (const StringArray&, int, int) {}
  20673. // components aren't allowed to have copy constructors, as this would mess up parent
  20674. // hierarchies. You might need to give your subclasses a private dummy constructor like
  20675. // this one to avoid compiler warnings.
  20676. Component (const Component&);
  20677. Component& operator= (const Component&);
  20678. protected:
  20679. /** @internal */
  20680. virtual void internalRepaint (int x, int y, int w, int h);
  20681. virtual ComponentPeer* createNewPeer (int styleFlags, void* nativeWindowToAttachTo);
  20682. /** Overridden from the MessageListener parent class.
  20683. You can override this if you really need to, but be sure to pass your unwanted messages up
  20684. to this base class implementation, as the Component class needs to send itself messages
  20685. to work properly.
  20686. */
  20687. void handleMessage (const Message&);
  20688. };
  20689. #endif // __JUCE_COMPONENT_JUCEHEADER__
  20690. /*** End of inlined file: juce_Component.h ***/
  20691. /*** Start of inlined file: juce_ApplicationCommandInfo.h ***/
  20692. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20693. #define __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20694. /*** Start of inlined file: juce_ApplicationCommandID.h ***/
  20695. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20696. #define __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20697. /** A type used to hold the unique ID for an application command.
  20698. This is a numeric type, so it can be stored as an integer.
  20699. @see ApplicationCommandInfo, ApplicationCommandManager,
  20700. ApplicationCommandTarget, KeyPressMappingSet
  20701. */
  20702. typedef int CommandID;
  20703. /** A set of general-purpose application command IDs.
  20704. Because these commands are likely to be used in most apps, they're defined
  20705. here to help different apps to use the same numeric values for them.
  20706. Of course you don't have to use these, but some of them are used internally by
  20707. Juce - e.g. the quit ID is recognised as a command by the JUCEApplication class.
  20708. @see ApplicationCommandInfo, ApplicationCommandManager,
  20709. ApplicationCommandTarget, KeyPressMappingSet
  20710. */
  20711. namespace StandardApplicationCommandIDs
  20712. {
  20713. /** This command ID should be used to send a "Quit the App" command.
  20714. This command is recognised by the JUCEApplication class, so if it is invoked
  20715. and no other ApplicationCommandTarget handles the event first, the JUCEApplication
  20716. object will catch it and call JUCEApplication::systemRequestedQuit().
  20717. */
  20718. static const CommandID quit = 0x1001;
  20719. /** The command ID that should be used to send a "Delete" command. */
  20720. static const CommandID del = 0x1002;
  20721. /** The command ID that should be used to send a "Cut" command. */
  20722. static const CommandID cut = 0x1003;
  20723. /** The command ID that should be used to send a "Copy to clipboard" command. */
  20724. static const CommandID copy = 0x1004;
  20725. /** The command ID that should be used to send a "Paste from clipboard" command. */
  20726. static const CommandID paste = 0x1005;
  20727. /** The command ID that should be used to send a "Select all" command. */
  20728. static const CommandID selectAll = 0x1006;
  20729. /** The command ID that should be used to send a "Deselect all" command. */
  20730. static const CommandID deselectAll = 0x1007;
  20731. }
  20732. #endif // __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  20733. /*** End of inlined file: juce_ApplicationCommandID.h ***/
  20734. /**
  20735. Holds information describing an application command.
  20736. This object is used to pass information about a particular command, such as its
  20737. name, description and other usage flags.
  20738. When an ApplicationCommandTarget is asked to provide information about the commands
  20739. it can perform, this is the structure gets filled-in to describe each one.
  20740. @see ApplicationCommandTarget, ApplicationCommandTarget::getCommandInfo(),
  20741. ApplicationCommandManager
  20742. */
  20743. struct JUCE_API ApplicationCommandInfo
  20744. {
  20745. explicit ApplicationCommandInfo (CommandID commandID) throw();
  20746. /** Sets a number of the structures values at once.
  20747. The meanings of each of the parameters is described below, in the appropriate
  20748. member variable's description.
  20749. */
  20750. void setInfo (const String& shortName,
  20751. const String& description,
  20752. const String& categoryName,
  20753. int flags) throw();
  20754. /** An easy way to set or remove the isDisabled bit in the structure's flags field.
  20755. If isActive is true, the flags member has the isDisabled bit cleared; if isActive
  20756. is false, the bit is set.
  20757. */
  20758. void setActive (bool isActive) throw();
  20759. /** An easy way to set or remove the isTicked bit in the structure's flags field.
  20760. */
  20761. void setTicked (bool isTicked) throw();
  20762. /** Handy method for adding a keypress to the defaultKeypresses array.
  20763. This is just so you can write things like:
  20764. @code
  20765. myinfo.addDefaultKeypress ('s', ModifierKeys::commandModifier);
  20766. @endcode
  20767. instead of
  20768. @code
  20769. myinfo.defaultKeypresses.add (KeyPress ('s', ModifierKeys::commandModifier));
  20770. @endcode
  20771. */
  20772. void addDefaultKeypress (int keyCode,
  20773. const ModifierKeys& modifiers) throw();
  20774. /** The command's unique ID number.
  20775. */
  20776. CommandID commandID;
  20777. /** A short name to describe the command.
  20778. This should be suitable for use in menus, on buttons that trigger the command, etc.
  20779. You can use the setInfo() method to quickly set this and some of the command's
  20780. other properties.
  20781. */
  20782. String shortName;
  20783. /** A longer description of the command.
  20784. This should be suitable for use in contexts such as a KeyMappingEditorComponent or
  20785. pop-up tooltip describing what the command does.
  20786. You can use the setInfo() method to quickly set this and some of the command's
  20787. other properties.
  20788. */
  20789. String description;
  20790. /** A named category that the command fits into.
  20791. You can give your commands any category you like, and these will be displayed in
  20792. contexts such as the KeyMappingEditorComponent, where the category is used to group
  20793. commands together.
  20794. You can use the setInfo() method to quickly set this and some of the command's
  20795. other properties.
  20796. */
  20797. String categoryName;
  20798. /** A list of zero or more keypresses that should be used as the default keys for
  20799. this command.
  20800. Methods such as KeyPressMappingSet::resetToDefaultMappings() will use the keypresses in
  20801. this list to initialise the default set of key-to-command mappings.
  20802. @see addDefaultKeypress
  20803. */
  20804. Array <KeyPress> defaultKeypresses;
  20805. /** Flags describing the ways in which this command should be used.
  20806. A bitwise-OR of these values is stored in the ApplicationCommandInfo::flags
  20807. variable.
  20808. */
  20809. enum CommandFlags
  20810. {
  20811. /** Indicates that the command can't currently be performed.
  20812. The ApplicationCommandTarget::getCommandInfo() method must set this flag if it's
  20813. not currently permissable to perform the command. If the flag is set, then
  20814. components that trigger the command, e.g. PopupMenu, may choose to grey-out the
  20815. command or show themselves as not being enabled.
  20816. @see ApplicationCommandInfo::setActive
  20817. */
  20818. isDisabled = 1 << 0,
  20819. /** Indicates that the command should have a tick next to it on a menu.
  20820. If your command is shown on a menu and this is set, it'll show a tick next to
  20821. it. Other components such as buttons may also use this flag to indicate that it
  20822. is a value that can be toggled, and is currently in the 'on' state.
  20823. @see ApplicationCommandInfo::setTicked
  20824. */
  20825. isTicked = 1 << 1,
  20826. /** If this flag is present, then when a KeyPressMappingSet invokes the command,
  20827. it will call the command twice, once on key-down and again on key-up.
  20828. @see ApplicationCommandTarget::InvocationInfo
  20829. */
  20830. wantsKeyUpDownCallbacks = 1 << 2,
  20831. /** If this flag is present, then a KeyMappingEditorComponent will not display the
  20832. command in its list.
  20833. */
  20834. hiddenFromKeyEditor = 1 << 3,
  20835. /** If this flag is present, then a KeyMappingEditorComponent will display the
  20836. command in its list, but won't allow the assigned keypress to be changed.
  20837. */
  20838. readOnlyInKeyEditor = 1 << 4,
  20839. /** If this flag is present and the command is invoked from a keypress, then any
  20840. buttons or menus that are also connected to the command will not flash to
  20841. indicate that they've been triggered.
  20842. */
  20843. dontTriggerVisualFeedback = 1 << 5
  20844. };
  20845. /** A bitwise-OR of the values specified in the CommandFlags enum.
  20846. You can use the setInfo() method to quickly set this and some of the command's
  20847. other properties.
  20848. */
  20849. int flags;
  20850. };
  20851. #endif // __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  20852. /*** End of inlined file: juce_ApplicationCommandInfo.h ***/
  20853. /**
  20854. A command target publishes a list of command IDs that it can perform.
  20855. An ApplicationCommandManager despatches commands to targets, which must be
  20856. able to provide information about what commands they can handle.
  20857. To create a target, you'll need to inherit from this class, implementing all of
  20858. its pure virtual methods.
  20859. For info about how a target is chosen to receive a command, see
  20860. ApplicationCommandManager::getFirstCommandTarget().
  20861. @see ApplicationCommandManager, ApplicationCommandInfo
  20862. */
  20863. class JUCE_API ApplicationCommandTarget
  20864. {
  20865. public:
  20866. /** Creates a command target. */
  20867. ApplicationCommandTarget();
  20868. /** Destructor. */
  20869. virtual ~ApplicationCommandTarget();
  20870. /**
  20871. */
  20872. struct JUCE_API InvocationInfo
  20873. {
  20874. InvocationInfo (const CommandID commandID) throw();
  20875. /** The UID of the command that should be performed. */
  20876. CommandID commandID;
  20877. /** The command's flags.
  20878. See ApplicationCommandInfo for a description of these flag values.
  20879. */
  20880. int commandFlags;
  20881. /** The types of context in which the command might be called. */
  20882. enum InvocationMethod
  20883. {
  20884. direct = 0, /**< The command is being invoked directly by a piece of code. */
  20885. fromKeyPress, /**< The command is being invoked by a key-press. */
  20886. fromMenu, /**< The command is being invoked by a menu selection. */
  20887. fromButton /**< The command is being invoked by a button click. */
  20888. };
  20889. /** The type of event that triggered this command. */
  20890. InvocationMethod invocationMethod;
  20891. /** If triggered by a keypress or menu, this will be the component that had the
  20892. keyboard focus at the time.
  20893. If triggered by a button, it may be set to that component, or it may be null.
  20894. */
  20895. Component* originatingComponent;
  20896. /** The keypress that was used to invoke it.
  20897. Note that this will be an invalid keypress if the command was invoked
  20898. by some other means than a keyboard shortcut.
  20899. */
  20900. KeyPress keyPress;
  20901. /** True if the callback is being invoked when the key is pressed,
  20902. false if the key is being released.
  20903. @see KeyPressMappingSet::addCommand()
  20904. */
  20905. bool isKeyDown;
  20906. /** If the key is being released, this indicates how long it had been held
  20907. down for.
  20908. (Only relevant if isKeyDown is false.)
  20909. */
  20910. int millisecsSinceKeyPressed;
  20911. };
  20912. /** This must return the next target to try after this one.
  20913. When a command is being sent, and the first target can't handle
  20914. that command, this method is used to determine the next target that should
  20915. be tried.
  20916. It may return 0 if it doesn't know of another target.
  20917. If your target is a Component, you would usually use the findFirstTargetParentComponent()
  20918. method to return a parent component that might want to handle it.
  20919. @see invoke
  20920. */
  20921. virtual ApplicationCommandTarget* getNextCommandTarget() = 0;
  20922. /** This must return a complete list of commands that this target can handle.
  20923. Your target should add all the command IDs that it handles to the array that is
  20924. passed-in.
  20925. */
  20926. virtual void getAllCommands (Array <CommandID>& commands) = 0;
  20927. /** This must provide details about one of the commands that this target can perform.
  20928. This will be called with one of the command IDs that the target provided in its
  20929. getAllCommands() methods.
  20930. It should fill-in all appropriate fields of the ApplicationCommandInfo structure with
  20931. suitable information about the command. (The commandID field will already have been filled-in
  20932. by the caller).
  20933. The easiest way to set the info is using the ApplicationCommandInfo::setInfo() method to
  20934. set all the fields at once.
  20935. If the command is currently inactive for some reason, this method must use
  20936. ApplicationCommandInfo::setActive() to make that clear, (or it should set the isDisabled
  20937. bit of the ApplicationCommandInfo::flags field).
  20938. Any default key-presses for the command should be appended to the
  20939. ApplicationCommandInfo::defaultKeypresses field.
  20940. Note that if you change something that affects the status of the commands
  20941. that would be returned by this method (e.g. something that makes some commands
  20942. active or inactive), you should call ApplicationCommandManager::commandStatusChanged()
  20943. to cause the manager to refresh its status.
  20944. */
  20945. virtual void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) = 0;
  20946. /** This must actually perform the specified command.
  20947. If this target is able to perform the command specified by the commandID field of the
  20948. InvocationInfo structure, then it should do so, and must return true.
  20949. If it can't handle this command, it should return false, which tells the caller to pass
  20950. the command on to the next target in line.
  20951. @see invoke, ApplicationCommandManager::invoke
  20952. */
  20953. virtual bool perform (const InvocationInfo& info) = 0;
  20954. /** Makes this target invoke a command.
  20955. Your code can call this method to invoke a command on this target, but normally
  20956. you'd call it indirectly via ApplicationCommandManager::invoke() or
  20957. ApplicationCommandManager::invokeDirectly().
  20958. If this target can perform the given command, it will call its perform() method to
  20959. do so. If not, then getNextCommandTarget() will be used to determine the next target
  20960. to try, and the command will be passed along to it.
  20961. @param invocationInfo this must be correctly filled-in, describing the context for
  20962. the invocation.
  20963. @param asynchronously if false, the command will be performed before this method returns.
  20964. If true, a message will be posted so that the command will be performed
  20965. later on the message thread, and this method will return immediately.
  20966. @see perform, ApplicationCommandManager::invoke
  20967. */
  20968. bool invoke (const InvocationInfo& invocationInfo,
  20969. const bool asynchronously);
  20970. /** Invokes a given command directly on this target.
  20971. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  20972. structure.
  20973. */
  20974. bool invokeDirectly (const CommandID commandID,
  20975. const bool asynchronously);
  20976. /** Searches this target and all subsequent ones for the first one that can handle
  20977. the specified command.
  20978. This will use getNextCommandTarget() to determine the chain of targets to try
  20979. after this one.
  20980. */
  20981. ApplicationCommandTarget* getTargetForCommand (const CommandID commandID);
  20982. /** Checks whether this command can currently be performed by this target.
  20983. This will return true only if a call to getCommandInfo() doesn't set the
  20984. isDisabled flag to indicate that the command is inactive.
  20985. */
  20986. bool isCommandActive (const CommandID commandID);
  20987. /** If this object is a Component, this method will seach upwards in its current
  20988. UI hierarchy for the next parent component that implements the
  20989. ApplicationCommandTarget class.
  20990. If your target is a Component, this is a very handy method to use in your
  20991. getNextCommandTarget() implementation.
  20992. */
  20993. ApplicationCommandTarget* findFirstTargetParentComponent();
  20994. juce_UseDebuggingNewOperator
  20995. /** @internal */
  20996. void releaseMessageListener();
  20997. private:
  20998. // (for async invocation of commands)
  20999. class CommandTargetMessageInvoker : public MessageListener
  21000. {
  21001. public:
  21002. CommandTargetMessageInvoker (ApplicationCommandTarget* const owner);
  21003. ~CommandTargetMessageInvoker();
  21004. void handleMessage (const Message& message);
  21005. private:
  21006. ApplicationCommandTarget* const owner;
  21007. CommandTargetMessageInvoker (const CommandTargetMessageInvoker&);
  21008. CommandTargetMessageInvoker& operator= (const CommandTargetMessageInvoker&);
  21009. };
  21010. ScopedPointer <CommandTargetMessageInvoker> messageInvoker;
  21011. friend class CommandTargetMessageInvoker;
  21012. bool tryToInvoke (const InvocationInfo& info, const bool async);
  21013. ApplicationCommandTarget (const ApplicationCommandTarget&);
  21014. ApplicationCommandTarget& operator= (const ApplicationCommandTarget&);
  21015. };
  21016. #endif // __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  21017. /*** End of inlined file: juce_ApplicationCommandTarget.h ***/
  21018. /*** Start of inlined file: juce_ActionListener.h ***/
  21019. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  21020. #define __JUCE_ACTIONLISTENER_JUCEHEADER__
  21021. /**
  21022. Receives callbacks to indicate that some kind of event has occurred.
  21023. Used by various classes, e.g. buttons when they are pressed, to tell listeners
  21024. about something that's happened.
  21025. @see ActionListenerList, ActionBroadcaster, ChangeListener
  21026. */
  21027. class JUCE_API ActionListener
  21028. {
  21029. public:
  21030. /** Destructor. */
  21031. virtual ~ActionListener() {}
  21032. /** Overridden by your subclass to receive the callback.
  21033. @param message the string that was specified when the event was triggered
  21034. by a call to ActionListenerList::sendActionMessage()
  21035. */
  21036. virtual void actionListenerCallback (const String& message) = 0;
  21037. };
  21038. #endif // __JUCE_ACTIONLISTENER_JUCEHEADER__
  21039. /*** End of inlined file: juce_ActionListener.h ***/
  21040. /**
  21041. An instance of this class is used to specify initialisation and shutdown
  21042. code for the application.
  21043. An application that wants to run in the JUCE framework needs to declare a
  21044. subclass of JUCEApplication and implement its various pure virtual methods.
  21045. It then needs to use the START_JUCE_APPLICATION macro somewhere in a cpp file
  21046. to declare an instance of this class and generate a suitable platform-specific
  21047. main() function.
  21048. e.g. @code
  21049. class MyJUCEApp : public JUCEApplication
  21050. {
  21051. // NEVER put objects inside a JUCEApplication class - only use pointers to
  21052. // objects, which you must create in the initialise() method.
  21053. MyApplicationWindow* myMainWindow;
  21054. public:
  21055. MyJUCEApp()
  21056. : myMainWindow (0)
  21057. {
  21058. // never create any Juce objects in the constructor - do all your initialisation
  21059. // in the initialise() method.
  21060. }
  21061. ~MyJUCEApp()
  21062. {
  21063. // all your shutdown code must have already been done in the shutdown() method -
  21064. // nothing should happen in this destructor.
  21065. }
  21066. void initialise (const String& commandLine)
  21067. {
  21068. myMainWindow = new MyApplicationWindow();
  21069. myMainWindow->setBounds (100, 100, 400, 500);
  21070. myMainWindow->setVisible (true);
  21071. }
  21072. void shutdown()
  21073. {
  21074. delete myMainWindow;
  21075. }
  21076. const String getApplicationName()
  21077. {
  21078. return "Super JUCE-o-matic";
  21079. }
  21080. const String getApplicationVersion()
  21081. {
  21082. return "1.0";
  21083. }
  21084. };
  21085. // this creates wrapper code to actually launch the app properly.
  21086. START_JUCE_APPLICATION (MyJUCEApp)
  21087. @endcode
  21088. Because this object will be created before Juce has properly initialised, you must
  21089. NEVER add any member variable objects that will be automatically constructed. Likewise
  21090. don't put ANY code in the constructor that could call Juce functions. Any objects that
  21091. you want to add to the class must be pointers, which you should instantiate during the
  21092. initialise() method, and delete in the shutdown() method.
  21093. @see MessageManager, DeletedAtShutdown
  21094. */
  21095. class JUCE_API JUCEApplication : public ApplicationCommandTarget,
  21096. private ActionListener
  21097. {
  21098. protected:
  21099. /** Constructs a JUCE app object.
  21100. If subclasses implement a constructor or destructor, they shouldn't call any
  21101. JUCE code in there - put your startup/shutdown code in initialise() and
  21102. shutdown() instead.
  21103. */
  21104. JUCEApplication();
  21105. public:
  21106. /** Destructor.
  21107. If subclasses implement a constructor or destructor, they shouldn't call any
  21108. JUCE code in there - put your startup/shutdown code in initialise() and
  21109. shutdown() instead.
  21110. */
  21111. virtual ~JUCEApplication();
  21112. /** Returns the global instance of the application object being run. */
  21113. static JUCEApplication* getInstance() throw();
  21114. /** Called when the application starts.
  21115. This will be called once to let the application do whatever initialisation
  21116. it needs, create its windows, etc.
  21117. After the method returns, the normal event-dispatch loop will be run,
  21118. until the quit() method is called, at which point the shutdown()
  21119. method will be called to let the application clear up anything it needs
  21120. to delete.
  21121. If during the initialise() method, the application decides not to start-up
  21122. after all, it can just call the quit() method and the event loop won't be run.
  21123. @param commandLineParameters the line passed in does not include the
  21124. name of the executable, just the parameter list.
  21125. @see shutdown, quit
  21126. */
  21127. virtual void initialise (const String& commandLineParameters) = 0;
  21128. /** Returns true if the application hasn't yet completed its initialise() method
  21129. and entered the main event loop.
  21130. This is handy for things like splash screens to know when the app's up-and-running
  21131. properly.
  21132. */
  21133. bool isInitialising() const throw();
  21134. /* Called to allow the application to clear up before exiting.
  21135. After JUCEApplication::quit() has been called, the event-dispatch loop will
  21136. terminate, and this method will get called to allow the app to sort itself
  21137. out.
  21138. Be careful that nothing happens in this method that might rely on messages
  21139. being sent, or any kind of window activity, because the message loop is no
  21140. longer running at this point.
  21141. @see DeletedAtShutdown
  21142. */
  21143. virtual void shutdown() = 0;
  21144. /** Returns the application's name.
  21145. An application must implement this to name itself.
  21146. */
  21147. virtual const String getApplicationName() = 0;
  21148. /** Returns the application's version number.
  21149. An application can implement this to give itself a version.
  21150. (The default implementation of this just returns an empty string).
  21151. */
  21152. virtual const String getApplicationVersion();
  21153. /** Checks whether multiple instances of the app are allowed.
  21154. If you application class returns true for this, more than one instance is
  21155. permitted to run (except on the Mac where this isn't possible).
  21156. If it's false, the second instance won't start, but it you will still get a
  21157. callback to anotherInstanceStarted() to tell you about this - which
  21158. gives you a chance to react to what the user was trying to do.
  21159. */
  21160. virtual bool moreThanOneInstanceAllowed();
  21161. /** Indicates that the user has tried to start up another instance of the app.
  21162. This will get called even if moreThanOneInstanceAllowed() is false.
  21163. */
  21164. virtual void anotherInstanceStarted (const String& commandLine);
  21165. /** Called when the operating system is trying to close the application.
  21166. The default implementation of this method is to call quit(), but it may
  21167. be overloaded to ignore the request or do some other special behaviour
  21168. instead. For example, you might want to offer the user the chance to save
  21169. their changes before quitting, and give them the chance to cancel.
  21170. If you want to send a quit signal to your app, this is the correct method
  21171. to call, because it means that requests that come from the system get handled
  21172. in the same way as those from your own application code. So e.g. you'd
  21173. call this method from a "quit" item on a menu bar.
  21174. */
  21175. virtual void systemRequestedQuit();
  21176. /** If any unhandled exceptions make it through to the message dispatch loop, this
  21177. callback will be triggered, in case you want to log them or do some other
  21178. type of error-handling.
  21179. If the type of exception is derived from the std::exception class, the pointer
  21180. passed-in will be valid. If the exception is of unknown type, this pointer
  21181. will be null.
  21182. */
  21183. virtual void unhandledException (const std::exception* e,
  21184. const String& sourceFilename,
  21185. int lineNumber);
  21186. /** Signals that the main message loop should stop and the application should terminate.
  21187. This isn't synchronous, it just posts a quit message to the main queue, and
  21188. when this message arrives, the message loop will stop, the shutdown() method
  21189. will be called, and the app will exit.
  21190. Note that this will cause an unconditional quit to happen, so if you need an
  21191. extra level before this, e.g. to give the user the chance to save their work
  21192. and maybe cancel the quit, you'll need to handle this in the systemRequestedQuit()
  21193. method - see that method's help for more info.
  21194. @see MessageManager, DeletedAtShutdown
  21195. */
  21196. static void quit();
  21197. /** Sets the value that should be returned as the application's exit code when the
  21198. app quits.
  21199. This is the value that's returned by the main() function. Normally you'd leave this
  21200. as 0 unless you want to indicate an error code.
  21201. @see getApplicationReturnValue
  21202. */
  21203. void setApplicationReturnValue (int newReturnValue) throw();
  21204. /** Returns the value that has been set as the application's exit code.
  21205. @see setApplicationReturnValue
  21206. */
  21207. int getApplicationReturnValue() const throw() { return appReturnValue; }
  21208. /** Returns the application's command line params.
  21209. */
  21210. const String getCommandLineParameters() const throw() { return commandLineParameters; }
  21211. // These are used by the START_JUCE_APPLICATION() macro and aren't for public use.
  21212. /** @internal */
  21213. static int main (String& commandLine, JUCEApplication* newApp);
  21214. /** @internal */
  21215. static int main (int argc, const char* argv[], JUCEApplication* newApp);
  21216. /** @internal */
  21217. static void sendUnhandledException (const std::exception* e,
  21218. const char* sourceFile,
  21219. int lineNumber);
  21220. /** @internal */
  21221. ApplicationCommandTarget* getNextCommandTarget();
  21222. /** @internal */
  21223. void getCommandInfo (CommandID commandID, ApplicationCommandInfo& result);
  21224. /** @internal */
  21225. void getAllCommands (Array <CommandID>& commands);
  21226. /** @internal */
  21227. bool perform (const InvocationInfo& info);
  21228. /** @internal */
  21229. void actionListenerCallback (const String& message);
  21230. private:
  21231. String commandLineParameters;
  21232. int appReturnValue;
  21233. bool stillInitialising;
  21234. ScopedPointer<InterProcessLock> appLock;
  21235. JUCEApplication (const JUCEApplication&);
  21236. JUCEApplication& operator= (const JUCEApplication&);
  21237. public:
  21238. /** @internal */
  21239. bool initialiseApp (String& commandLine);
  21240. /** @internal */
  21241. static int shutdownAppAndClearUp();
  21242. };
  21243. #endif // __JUCE_APPLICATION_JUCEHEADER__
  21244. /*** End of inlined file: juce_Application.h ***/
  21245. #endif
  21246. #ifndef __JUCE_APPLICATIONCOMMANDID_JUCEHEADER__
  21247. #endif
  21248. #ifndef __JUCE_APPLICATIONCOMMANDINFO_JUCEHEADER__
  21249. #endif
  21250. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21251. /*** Start of inlined file: juce_ApplicationCommandManager.h ***/
  21252. #ifndef __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21253. #define __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21254. /*** Start of inlined file: juce_Desktop.h ***/
  21255. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  21256. #define __JUCE_DESKTOP_JUCEHEADER__
  21257. /*** Start of inlined file: juce_Timer.h ***/
  21258. #ifndef __JUCE_TIMER_JUCEHEADER__
  21259. #define __JUCE_TIMER_JUCEHEADER__
  21260. class InternalTimerThread;
  21261. /**
  21262. Repeatedly calls a user-defined method at a specified time interval.
  21263. A Timer's timerCallback() method will be repeatedly called at a given
  21264. interval. Initially when a Timer object is created, they will do nothing
  21265. until the startTimer() method is called, then the message thread will
  21266. start calling it back until stopTimer() is called.
  21267. The time interval isn't guaranteed to be precise to any more than maybe
  21268. 10-20ms, and the intervals may end up being much longer than requested if the
  21269. system is busy. Because it's the message thread that is doing the callbacks,
  21270. any messages that take a significant amount of time to process will block
  21271. all the timers for that period.
  21272. If you need to have a single callback that is shared by multiple timers with
  21273. different frequencies, then the MultiTimer class allows you to do that - its
  21274. structure is very similar to the Timer class, but contains multiple timers
  21275. internally, each one identified by an ID number.
  21276. @see MultiTimer
  21277. */
  21278. class JUCE_API Timer
  21279. {
  21280. protected:
  21281. /** Creates a Timer.
  21282. When created, the timer is stopped, so use startTimer() to get it going.
  21283. */
  21284. Timer() throw();
  21285. /** Creates a copy of another timer.
  21286. Note that this timer won't be started, even if the one you're copying
  21287. is running.
  21288. */
  21289. Timer (const Timer& other) throw();
  21290. public:
  21291. /** Destructor. */
  21292. virtual ~Timer();
  21293. /** The user-defined callback routine that actually gets called periodically.
  21294. It's perfectly ok to call startTimer() or stopTimer() from within this
  21295. callback to change the subsequent intervals.
  21296. */
  21297. virtual void timerCallback() = 0;
  21298. /** Starts the timer and sets the length of interval required.
  21299. If the timer is already started, this will reset it, so the
  21300. time between calling this method and the next timer callback
  21301. will not be less than the interval length passed in.
  21302. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  21303. rounded up to 1)
  21304. */
  21305. void startTimer (int intervalInMilliseconds) throw();
  21306. /** Stops the timer.
  21307. No more callbacks will be made after this method returns.
  21308. If this is called from a different thread, any callbacks that may
  21309. be currently executing may be allowed to finish before the method
  21310. returns.
  21311. */
  21312. void stopTimer() throw();
  21313. /** Checks if the timer has been started.
  21314. @returns true if the timer is running.
  21315. */
  21316. bool isTimerRunning() const throw() { return periodMs > 0; }
  21317. /** Returns the timer's interval.
  21318. @returns the timer's interval in milliseconds if it's running, or 0 if it's not.
  21319. */
  21320. int getTimerInterval() const throw() { return periodMs; }
  21321. private:
  21322. friend class InternalTimerThread;
  21323. int countdownMs, periodMs;
  21324. Timer* previous;
  21325. Timer* next;
  21326. Timer& operator= (const Timer&);
  21327. };
  21328. #endif // __JUCE_TIMER_JUCEHEADER__
  21329. /*** End of inlined file: juce_Timer.h ***/
  21330. class MouseInputSource;
  21331. class MouseInputSourceInternal;
  21332. class MouseListener;
  21333. /**
  21334. Classes can implement this interface and register themselves with the Desktop class
  21335. to receive callbacks when the currently focused component changes.
  21336. @see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
  21337. */
  21338. class JUCE_API FocusChangeListener
  21339. {
  21340. public:
  21341. /** Destructor. */
  21342. virtual ~FocusChangeListener() {}
  21343. /** Callback to indicate that the currently focused component has changed. */
  21344. virtual void globalFocusChanged (Component* focusedComponent) = 0;
  21345. };
  21346. /**
  21347. Describes and controls aspects of the computer's desktop.
  21348. */
  21349. class JUCE_API Desktop : private DeletedAtShutdown,
  21350. private Timer,
  21351. private AsyncUpdater
  21352. {
  21353. public:
  21354. /** There's only one dektop object, and this method will return it.
  21355. */
  21356. static Desktop& JUCE_CALLTYPE getInstance();
  21357. /** Returns a list of the positions of all the monitors available.
  21358. The first rectangle in the list will be the main monitor area.
  21359. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21360. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21361. */
  21362. const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const throw();
  21363. /** Returns the position and size of the main monitor.
  21364. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21365. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21366. */
  21367. const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const throw();
  21368. /** Returns the position and size of the monitor which contains this co-ordinate.
  21369. If none of the monitors contains the point, this will just return the
  21370. main monitor.
  21371. If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
  21372. or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
  21373. */
  21374. const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
  21375. /** Returns the mouse position.
  21376. The co-ordinates are relative to the top-left of the main monitor.
  21377. */
  21378. static const Point<int> getMousePosition();
  21379. /** Makes the mouse pointer jump to a given location.
  21380. The co-ordinates are relative to the top-left of the main monitor.
  21381. */
  21382. static void setMousePosition (const Point<int>& newPosition);
  21383. /** Returns the last position at which a mouse button was pressed.
  21384. */
  21385. static const Point<int> getLastMouseDownPosition() throw();
  21386. /** Returns the number of times the mouse button has been clicked since the
  21387. app started.
  21388. Each mouse-down event increments this number by 1.
  21389. */
  21390. static int getMouseButtonClickCounter() throw();
  21391. /** This lets you prevent the screensaver from becoming active.
  21392. Handy if you're running some sort of presentation app where having a screensaver
  21393. appear would be annoying.
  21394. Pass false to disable the screensaver, and true to re-enable it. (Note that this
  21395. won't enable a screensaver unless the user has actually set one up).
  21396. The disablement will only happen while the Juce application is the foreground
  21397. process - if another task is running in front of it, then the screensaver will
  21398. be unaffected.
  21399. @see isScreenSaverEnabled
  21400. */
  21401. static void setScreenSaverEnabled (bool isEnabled);
  21402. /** Returns true if the screensaver has not been turned off.
  21403. This will return the last value passed into setScreenSaverEnabled(). Note that
  21404. it won't tell you whether the user is actually using a screen saver, just
  21405. whether this app is deliberately preventing one from running.
  21406. @see setScreenSaverEnabled
  21407. */
  21408. static bool isScreenSaverEnabled();
  21409. /** Registers a MouseListener that will receive all mouse events that occur on
  21410. any component.
  21411. @see removeGlobalMouseListener
  21412. */
  21413. void addGlobalMouseListener (MouseListener* listener);
  21414. /** Unregisters a MouseListener that was added with the addGlobalMouseListener()
  21415. method.
  21416. @see addGlobalMouseListener
  21417. */
  21418. void removeGlobalMouseListener (MouseListener* listener);
  21419. /** Registers a MouseListener that will receive a callback whenever the focused
  21420. component changes.
  21421. */
  21422. void addFocusChangeListener (FocusChangeListener* listener);
  21423. /** Unregisters a listener that was added with addFocusChangeListener(). */
  21424. void removeFocusChangeListener (FocusChangeListener* listener);
  21425. /** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
  21426. The component must already be on the desktop for this method to work. It will
  21427. be resized to completely fill the screen and any extraneous taskbars, menu bars,
  21428. etc will be hidden.
  21429. To exit kiosk mode, just call setKioskModeComponent (0). When this is called,
  21430. the component that's currently being used will be resized back to the size
  21431. and position it was in before being put into this mode.
  21432. If allowMenusAndBars is true, things like the menu and dock (on mac) are still
  21433. allowed to pop up when the mouse moves onto them. If this is false, it'll try
  21434. to hide as much on-screen paraphenalia as possible.
  21435. */
  21436. void setKioskModeComponent (Component* componentToUse,
  21437. bool allowMenusAndBars = true);
  21438. /** Returns the component that is currently being used in kiosk-mode.
  21439. This is the component that was last set by setKioskModeComponent(). If none
  21440. has been set, this returns 0.
  21441. */
  21442. Component* getKioskModeComponent() const throw() { return kioskModeComponent; }
  21443. /** Returns the number of components that are currently active as top-level
  21444. desktop windows.
  21445. @see getComponent, Component::addToDesktop
  21446. */
  21447. int getNumComponents() const throw();
  21448. /** Returns one of the top-level desktop window components.
  21449. The index is from 0 to getNumComponents() - 1. This could return 0 if the
  21450. index is out-of-range.
  21451. @see getNumComponents, Component::addToDesktop
  21452. */
  21453. Component* getComponent (int index) const throw();
  21454. /** Finds the component at a given screen location.
  21455. This will drill down into top-level windows to find the child component at
  21456. the given position.
  21457. Returns 0 if the co-ordinates are inside a non-Juce window.
  21458. */
  21459. Component* findComponentAt (const Point<int>& screenPosition) const;
  21460. /** Returns the number of MouseInputSource objects the system has at its disposal.
  21461. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21462. system, there could be one input source per potential finger.
  21463. To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
  21464. @see getMouseSource
  21465. */
  21466. int getNumMouseSources() const throw() { return mouseSources.size(); }
  21467. /** Returns one of the system's MouseInputSource objects.
  21468. The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
  21469. a null pointer.
  21470. In a traditional single-mouse system, there might be only one object. On a multi-touch
  21471. system, there could be one input source per potential finger.
  21472. */
  21473. MouseInputSource* getMouseSource (int index) const throw() { return mouseSources [index]; }
  21474. /** Returns the main mouse input device that the system is using.
  21475. @see getNumMouseSources()
  21476. */
  21477. MouseInputSource& getMainMouseSource() const throw() { return *mouseSources.getUnchecked(0); }
  21478. /** Returns the number of mouse-sources that are currently being dragged.
  21479. In a traditional single-mouse system, this will be 0 or 1, depending on whether a
  21480. juce component has the button down on it. In a multi-touch system, this could
  21481. be any number from 0 to the number of simultaneous touches that can be detected.
  21482. */
  21483. int getNumDraggingMouseSources() const throw();
  21484. /** Returns one of the mouse sources that's currently being dragged.
  21485. The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
  21486. out of range, or if no mice or fingers are down, this will return a null pointer.
  21487. */
  21488. MouseInputSource* getDraggingMouseSource (int index) const throw();
  21489. juce_UseDebuggingNewOperator
  21490. /** Tells this object to refresh its idea of what the screen resolution is.
  21491. (Called internally by the native code).
  21492. */
  21493. void refreshMonitorSizes();
  21494. /** True if the OS supports semitransparent windows */
  21495. static bool canUseSemiTransparentWindows() throw();
  21496. private:
  21497. static Desktop* instance;
  21498. friend class Component;
  21499. friend class ComponentPeer;
  21500. friend class MouseInputSource;
  21501. friend class MouseInputSourceInternal;
  21502. friend class DeletedAtShutdown;
  21503. friend class TopLevelWindowManager;
  21504. OwnedArray <MouseInputSource> mouseSources;
  21505. void createMouseInputSources();
  21506. ListenerList <MouseListener> mouseListeners;
  21507. ListenerList <FocusChangeListener> focusListeners;
  21508. Array <Component*> desktopComponents;
  21509. Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
  21510. Point<int> lastFakeMouseMove;
  21511. void sendMouseMove();
  21512. int mouseClickCounter;
  21513. void incrementMouseClickCounter() throw();
  21514. Component* kioskModeComponent;
  21515. Rectangle<int> kioskComponentOriginalBounds;
  21516. void timerCallback();
  21517. void resetTimer();
  21518. int getNumDisplayMonitors() const throw();
  21519. const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const throw();
  21520. void addDesktopComponent (Component* c);
  21521. void removeDesktopComponent (Component* c);
  21522. void componentBroughtToFront (Component* c);
  21523. void triggerFocusCallback();
  21524. void handleAsyncUpdate();
  21525. Desktop();
  21526. ~Desktop();
  21527. Desktop (const Desktop&);
  21528. Desktop& operator= (const Desktop&);
  21529. };
  21530. #endif // __JUCE_DESKTOP_JUCEHEADER__
  21531. /*** End of inlined file: juce_Desktop.h ***/
  21532. class KeyPressMappingSet;
  21533. class ApplicationCommandManagerListener;
  21534. /**
  21535. One of these objects holds a list of all the commands your app can perform,
  21536. and despatches these commands when needed.
  21537. Application commands are a good way to trigger actions in your app, e.g. "Quit",
  21538. "Copy", "Paste", etc. Menus, buttons and keypresses can all be given commands
  21539. to invoke automatically, which means you don't have to handle the result of a menu
  21540. or button click manually. Commands are despatched to ApplicationCommandTarget objects
  21541. which can choose which events they want to handle.
  21542. This architecture also allows for nested ApplicationCommandTargets, so that for example
  21543. you could have two different objects, one inside the other, both of which can respond to
  21544. a "delete" command. Depending on which one has focus, the command will be sent to the
  21545. appropriate place, regardless of whether it was triggered by a menu, keypress or some other
  21546. method.
  21547. To set up your app to use commands, you'll need to do the following:
  21548. - Create a global ApplicationCommandManager to hold the list of all possible
  21549. commands. (This will also manage a set of key-mappings for them).
  21550. - Make some of your UI components (or other objects) inherit from ApplicationCommandTarget.
  21551. This allows the object to provide a list of commands that it can perform, and
  21552. to handle them.
  21553. - Register each type of command using ApplicationCommandManager::registerAllCommandsForTarget(),
  21554. or ApplicationCommandManager::registerCommand().
  21555. - If you want key-presses to trigger your commands, use the ApplicationCommandManager::getKeyMappings()
  21556. method to access the key-mapper object, which you will need to register as a key-listener
  21557. in whatever top-level component you're using. See the KeyPressMappingSet class for more help
  21558. about setting this up.
  21559. - Use methods such as PopupMenu::addCommandItem() or Button::setCommandToTrigger() to
  21560. cause these commands to be invoked automatically.
  21561. - Commands can be invoked directly by your code using ApplicationCommandManager::invokeDirectly().
  21562. When a command is invoked, the ApplicationCommandManager will try to choose the best
  21563. ApplicationCommandTarget to receive the specified command. To do this it will use the
  21564. current keyboard focus to see which component might be interested, and will search the
  21565. component hierarchy for those that also implement the ApplicationCommandTarget interface.
  21566. If an ApplicationCommandTarget isn't interested in the command that is being invoked, then
  21567. the next one in line will be tried (see the ApplicationCommandTarget::getNextCommandTarget()
  21568. method), and so on until ApplicationCommandTarget::getNextCommandTarget() returns 0. At this
  21569. point if the command still hasn't been performed, it will be passed to the current
  21570. JUCEApplication object (which is itself an ApplicationCommandTarget).
  21571. To exert some custom control over which ApplicationCommandTarget is chosen to invoke a command,
  21572. you can override the ApplicationCommandManager::getFirstCommandTarget() method and choose
  21573. the object yourself.
  21574. @see ApplicationCommandTarget, ApplicationCommandInfo
  21575. */
  21576. class JUCE_API ApplicationCommandManager : private AsyncUpdater,
  21577. private FocusChangeListener
  21578. {
  21579. public:
  21580. /** Creates an ApplicationCommandManager.
  21581. Once created, you'll need to register all your app's commands with it, using
  21582. ApplicationCommandManager::registerAllCommandsForTarget() or
  21583. ApplicationCommandManager::registerCommand().
  21584. */
  21585. ApplicationCommandManager();
  21586. /** Destructor.
  21587. Make sure that you don't delete this if pointers to it are still being used by
  21588. objects such as PopupMenus or Buttons.
  21589. */
  21590. virtual ~ApplicationCommandManager();
  21591. /** Clears the current list of all commands.
  21592. Note that this will also clear the contents of the KeyPressMappingSet.
  21593. */
  21594. void clearCommands();
  21595. /** Adds a command to the list of registered commands.
  21596. @see registerAllCommandsForTarget
  21597. */
  21598. void registerCommand (const ApplicationCommandInfo& newCommand);
  21599. /** Adds all the commands that this target publishes to the manager's list.
  21600. This will use ApplicationCommandTarget::getAllCommands() and ApplicationCommandTarget::getCommandInfo()
  21601. to get details about all the commands that this target can do, and will call
  21602. registerCommand() to add each one to the manger's list.
  21603. @see registerCommand
  21604. */
  21605. void registerAllCommandsForTarget (ApplicationCommandTarget* target);
  21606. /** Removes the command with a specified ID.
  21607. Note that this will also remove any key mappings that are mapped to the command.
  21608. */
  21609. void removeCommand (CommandID commandID);
  21610. /** This should be called to tell the manager that one of its registered commands may have changed
  21611. its active status.
  21612. Because the command manager only finds out whether a command is active or inactive by querying
  21613. the current ApplicationCommandTarget, this is used to tell it that things may have changed. It
  21614. allows things like buttons to update their enablement, etc.
  21615. This method will cause an asynchronous call to ApplicationCommandManagerListener::applicationCommandListChanged()
  21616. for any registered listeners.
  21617. */
  21618. void commandStatusChanged();
  21619. /** Returns the number of commands that have been registered.
  21620. @see registerCommand
  21621. */
  21622. int getNumCommands() const throw() { return commands.size(); }
  21623. /** Returns the details about one of the registered commands.
  21624. The index is between 0 and (getNumCommands() - 1).
  21625. */
  21626. const ApplicationCommandInfo* getCommandForIndex (int index) const throw() { return commands [index]; }
  21627. /** Returns the details about a given command ID.
  21628. This will search the list of registered commands for one with the given command
  21629. ID number, and return its associated info. If no matching command is found, this
  21630. will return 0.
  21631. */
  21632. const ApplicationCommandInfo* getCommandForID (CommandID commandID) const throw();
  21633. /** Returns the name field for a command.
  21634. An empty string is returned if no command with this ID has been registered.
  21635. @see getDescriptionOfCommand
  21636. */
  21637. const String getNameOfCommand (CommandID commandID) const throw();
  21638. /** Returns the description field for a command.
  21639. An empty string is returned if no command with this ID has been registered. If the
  21640. command has no description, this will return its short name field instead.
  21641. @see getNameOfCommand
  21642. */
  21643. const String getDescriptionOfCommand (CommandID commandID) const throw();
  21644. /** Returns the list of categories.
  21645. This will go through all registered commands, and return a list of all the distict
  21646. categoryName values from their ApplicationCommandInfo structure.
  21647. @see getCommandsInCategory()
  21648. */
  21649. const StringArray getCommandCategories() const throw();
  21650. /** Returns a list of all the command UIDs in a particular category.
  21651. @see getCommandCategories()
  21652. */
  21653. const Array <CommandID> getCommandsInCategory (const String& categoryName) const throw();
  21654. /** Returns the manager's internal set of key mappings.
  21655. This object can be used to edit the keypresses. To actually link this object up
  21656. to invoke commands when a key is pressed, see the comments for the KeyPressMappingSet
  21657. class.
  21658. @see KeyPressMappingSet
  21659. */
  21660. KeyPressMappingSet* getKeyMappings() const throw() { return keyMappings; }
  21661. /** Invokes the given command directly, sending it to the default target.
  21662. This is just an easy way to call invoke() without having to fill out the InvocationInfo
  21663. structure.
  21664. */
  21665. bool invokeDirectly (CommandID commandID, bool asynchronously);
  21666. /** Sends a command to the default target.
  21667. This will choose a target using getFirstCommandTarget(), and send the specified command
  21668. to it using the ApplicationCommandTarget::invoke() method. This means that if the
  21669. first target can't handle the command, it will be passed on to targets further down the
  21670. chain (see ApplicationCommandTarget::invoke() for more info).
  21671. @param invocationInfo this must be correctly filled-in, describing the context for
  21672. the invocation.
  21673. @param asynchronously if false, the command will be performed before this method returns.
  21674. If true, a message will be posted so that the command will be performed
  21675. later on the message thread, and this method will return immediately.
  21676. @see ApplicationCommandTarget::invoke
  21677. */
  21678. bool invoke (const ApplicationCommandTarget::InvocationInfo& invocationInfo,
  21679. bool asynchronously);
  21680. /** Chooses the ApplicationCommandTarget to which a command should be sent.
  21681. Whenever the manager needs to know which target a command should be sent to, it calls
  21682. this method to determine the first one to try.
  21683. By default, this method will return the target that was set by calling setFirstCommandTarget().
  21684. If no target is set, it will return the result of findDefaultComponentTarget().
  21685. If you need to make sure all commands go via your own custom target, then you can
  21686. either use setFirstCommandTarget() to specify a single target, or override this method
  21687. if you need more complex logic to choose one.
  21688. It may return 0 if no targets are available.
  21689. @see getTargetForCommand, invoke, invokeDirectly
  21690. */
  21691. virtual ApplicationCommandTarget* getFirstCommandTarget (CommandID commandID);
  21692. /** Sets a target to be returned by getFirstCommandTarget().
  21693. If this is set to 0, then getFirstCommandTarget() will by default return the
  21694. result of findDefaultComponentTarget().
  21695. If you use this to set a target, make sure you call setFirstCommandTarget (0) before
  21696. deleting the target object.
  21697. */
  21698. void setFirstCommandTarget (ApplicationCommandTarget* newTarget) throw();
  21699. /** Tries to find the best target to use to perform a given command.
  21700. This will call getFirstCommandTarget() to find the preferred target, and will
  21701. check whether that target can handle the given command. If it can't, then it'll use
  21702. ApplicationCommandTarget::getNextCommandTarget() to find the next one to try, and
  21703. so on until no more are available.
  21704. If no targets are found that can perform the command, this method will return 0.
  21705. If a target is found, then it will get the target to fill-in the upToDateInfo
  21706. structure with the latest info about that command, so that the caller can see
  21707. whether the command is disabled, ticked, etc.
  21708. */
  21709. ApplicationCommandTarget* getTargetForCommand (CommandID commandID,
  21710. ApplicationCommandInfo& upToDateInfo);
  21711. /** Registers a listener that will be called when various events occur. */
  21712. void addListener (ApplicationCommandManagerListener* listener) throw();
  21713. /** Deregisters a previously-added listener. */
  21714. void removeListener (ApplicationCommandManagerListener* listener) throw();
  21715. /** Looks for a suitable command target based on which Components have the keyboard focus.
  21716. This is used by the default implementation of ApplicationCommandTarget::getFirstCommandTarget(),
  21717. but is exposed here in case it's useful.
  21718. It tries to pick the best ApplicationCommandTarget by looking at focused components, top level
  21719. windows, etc., and using the findTargetForComponent() method.
  21720. */
  21721. static ApplicationCommandTarget* findDefaultComponentTarget();
  21722. /** Examines this component and all its parents in turn, looking for the first one
  21723. which is a ApplicationCommandTarget.
  21724. Returns the first ApplicationCommandTarget that it finds, or 0 if none of them implement
  21725. that class.
  21726. */
  21727. static ApplicationCommandTarget* findTargetForComponent (Component* component);
  21728. juce_UseDebuggingNewOperator
  21729. private:
  21730. OwnedArray <ApplicationCommandInfo> commands;
  21731. ListenerList <ApplicationCommandManagerListener> listeners;
  21732. ScopedPointer <KeyPressMappingSet> keyMappings;
  21733. ApplicationCommandTarget* firstTarget;
  21734. void sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info);
  21735. void handleAsyncUpdate();
  21736. void globalFocusChanged (Component*);
  21737. // xxx this is just here to cause a compile error in old code that hasn't been changed to use the new
  21738. // version of this method.
  21739. virtual short getFirstCommandTarget() { return 0; }
  21740. ApplicationCommandManager (const ApplicationCommandManager&);
  21741. ApplicationCommandManager& operator= (const ApplicationCommandManager&);
  21742. };
  21743. /**
  21744. A listener that receives callbacks from an ApplicationCommandManager when
  21745. commands are invoked or the command list is changed.
  21746. @see ApplicationCommandManager::addListener, ApplicationCommandManager::removeListener
  21747. */
  21748. class JUCE_API ApplicationCommandManagerListener
  21749. {
  21750. public:
  21751. /** Destructor. */
  21752. virtual ~ApplicationCommandManagerListener() {}
  21753. /** Called when an app command is about to be invoked. */
  21754. virtual void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info) = 0;
  21755. /** Called when commands are registered or deregistered from the
  21756. command manager, or when commands are made active or inactive.
  21757. Note that if you're using this to watch for changes to whether a command is disabled,
  21758. you'll need to make sure that ApplicationCommandManager::commandStatusChanged() is called
  21759. whenever the status of your command might have changed.
  21760. */
  21761. virtual void applicationCommandListChanged() = 0;
  21762. };
  21763. #endif // __JUCE_APPLICATIONCOMMANDMANAGER_JUCEHEADER__
  21764. /*** End of inlined file: juce_ApplicationCommandManager.h ***/
  21765. #endif
  21766. #ifndef __JUCE_APPLICATIONCOMMANDTARGET_JUCEHEADER__
  21767. #endif
  21768. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21769. /*** Start of inlined file: juce_ApplicationProperties.h ***/
  21770. #ifndef __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21771. #define __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21772. /*** Start of inlined file: juce_PropertiesFile.h ***/
  21773. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  21774. #define __JUCE_PROPERTIESFILE_JUCEHEADER__
  21775. /** Wrapper on a file that stores a list of key/value data pairs.
  21776. Useful for storing application settings, etc. See the PropertySet class for
  21777. the interfaces that read and write values.
  21778. Not designed for very large amounts of data, as it keeps all the values in
  21779. memory and writes them out to disk lazily when they are changed.
  21780. Because this class derives from ChangeBroadcaster, ChangeListeners can be registered
  21781. with it, and these will be signalled when a value changes.
  21782. @see PropertySet
  21783. */
  21784. class JUCE_API PropertiesFile : public PropertySet,
  21785. public ChangeBroadcaster,
  21786. private Timer
  21787. {
  21788. public:
  21789. enum FileFormatOptions
  21790. {
  21791. ignoreCaseOfKeyNames = 1,
  21792. storeAsBinary = 2,
  21793. storeAsCompressedBinary = 4,
  21794. storeAsXML = 8
  21795. };
  21796. /**
  21797. Creates a PropertiesFile object.
  21798. @param file the file to use
  21799. @param millisecondsBeforeSaving if this is zero or greater, then after a value
  21800. is changed, the object will wait for this amount
  21801. of time and then save the file. If zero, the file
  21802. will be written to disk immediately on being changed
  21803. (which might be slow, as it'll re-write synchronously
  21804. each time a value-change method is called). If it is
  21805. less than zero, the file won't be saved until
  21806. save() or saveIfNeeded() are explicitly called.
  21807. @param optionFlags a combination of the flags in the FileFormatOptions
  21808. enum, which specify the type of file to save, and other
  21809. options.
  21810. @param processLock an optional InterprocessLock object that will be used to
  21811. prevent multiple threads or processes from writing to the file
  21812. at the same time. The PropertiesFile will keep a pointer to
  21813. this object but will not take ownership of it - the caller is
  21814. responsible for making sure that the lock doesn't get deleted
  21815. before the PropertiesFile has been deleted.
  21816. */
  21817. PropertiesFile (const File& file,
  21818. int millisecondsBeforeSaving,
  21819. int optionFlags,
  21820. InterProcessLock* processLock = 0);
  21821. /** Destructor.
  21822. When deleted, the file will first call saveIfNeeded() to flush any changes to disk.
  21823. */
  21824. ~PropertiesFile();
  21825. /** Returns true if this file was created from a valid (or non-existent) file.
  21826. If the file failed to load correctly because it was corrupt or had insufficient
  21827. access, this will be false.
  21828. */
  21829. bool isValidFile() const throw() { return loadedOk; }
  21830. /** This will flush all the values to disk if they've changed since the last
  21831. time they were saved.
  21832. Returns false if it fails to write to the file for some reason (maybe because
  21833. it's read-only or the directory doesn't exist or something).
  21834. @see save
  21835. */
  21836. bool saveIfNeeded();
  21837. /** This will force a write-to-disk of the current values, regardless of whether
  21838. anything has changed since the last save.
  21839. Returns false if it fails to write to the file for some reason (maybe because
  21840. it's read-only or the directory doesn't exist or something).
  21841. @see saveIfNeeded
  21842. */
  21843. bool save();
  21844. /** Returns true if the properties have been altered since the last time they were saved.
  21845. The file is flagged as needing to be saved when you change a value, but you can
  21846. explicitly set this flag with setNeedsToBeSaved().
  21847. */
  21848. bool needsToBeSaved() const;
  21849. /** Explicitly sets the flag to indicate whether the file needs saving or not.
  21850. @see needsToBeSaved
  21851. */
  21852. void setNeedsToBeSaved (bool needsToBeSaved);
  21853. /** Returns the file that's being used. */
  21854. const File getFile() const { return file; }
  21855. /** Handy utility to create a properties file in whatever the standard OS-specific
  21856. location is for these things.
  21857. This uses getDefaultAppSettingsFile() to decide what file to create, then
  21858. creates a PropertiesFile object with the specified properties. See
  21859. getDefaultAppSettingsFile() and the class's constructor for descriptions of
  21860. what the parameters do.
  21861. @see getDefaultAppSettingsFile
  21862. */
  21863. static PropertiesFile* createDefaultAppPropertiesFile (const String& applicationName,
  21864. const String& fileNameSuffix,
  21865. const String& folderName,
  21866. bool commonToAllUsers,
  21867. int millisecondsBeforeSaving,
  21868. int propertiesFileOptions,
  21869. InterProcessLock* processLock = 0);
  21870. /** Handy utility to choose a file in the standard OS-dependent location for application
  21871. settings files.
  21872. So on a Mac, this will return a file called:
  21873. ~/Library/Preferences/[folderName]/[applicationName].[fileNameSuffix]
  21874. On Windows it'll return something like:
  21875. C:\\Documents and Settings\\username\\Application Data\\[folderName]\\[applicationName].[fileNameSuffix]
  21876. On Linux it'll return
  21877. ~/.[folderName]/[applicationName].[fileNameSuffix]
  21878. If you pass an empty string as the folder name, it'll use the app name for this (or
  21879. omit the folder name on the Mac).
  21880. If commonToAllUsers is true, then this will return the same file for all users of the
  21881. computer, regardless of the current user. If it is false, the file will be specific to
  21882. only the current user. Use this to choose whether you're saving settings that are common
  21883. or user-specific.
  21884. */
  21885. static const File getDefaultAppSettingsFile (const String& applicationName,
  21886. const String& fileNameSuffix,
  21887. const String& folderName,
  21888. bool commonToAllUsers);
  21889. juce_UseDebuggingNewOperator
  21890. protected:
  21891. virtual void propertyChanged();
  21892. private:
  21893. File file;
  21894. int timerInterval;
  21895. const int options;
  21896. bool loadedOk, needsWriting;
  21897. InterProcessLock* processLock;
  21898. typedef const ScopedPointer<InterProcessLock::ScopedLockType> ProcessScopedLock;
  21899. InterProcessLock::ScopedLockType* createProcessLock() const;
  21900. void timerCallback();
  21901. PropertiesFile (const PropertiesFile&);
  21902. PropertiesFile& operator= (const PropertiesFile&);
  21903. };
  21904. #endif // __JUCE_PROPERTIESFILE_JUCEHEADER__
  21905. /*** End of inlined file: juce_PropertiesFile.h ***/
  21906. /**
  21907. Manages a collection of properties.
  21908. This is a slightly higher-level wrapper for PropertiesFile, which can be used
  21909. as a singleton.
  21910. It holds two different PropertiesFile objects internally, one for user-specific
  21911. settings (stored in your user directory), and one for settings that are common to
  21912. all users (stored in a folder accessible to all users).
  21913. The class manages the creation of these files on-demand, allowing access via the
  21914. getUserSettings() and getCommonSettings() methods. It also has a few handy
  21915. methods like testWriteAccess() to check that the files can be saved.
  21916. If you're using one of these as a singleton, then your app's start-up code should
  21917. first of all call setStorageParameters() to tell it the parameters to use to create
  21918. the properties files.
  21919. @see PropertiesFile
  21920. */
  21921. class JUCE_API ApplicationProperties : public DeletedAtShutdown
  21922. {
  21923. public:
  21924. /**
  21925. Creates an ApplicationProperties object.
  21926. Before using it, you must call setStorageParameters() to give it the info
  21927. it needs to create the property files.
  21928. */
  21929. ApplicationProperties() throw();
  21930. /** Destructor.
  21931. */
  21932. ~ApplicationProperties();
  21933. juce_DeclareSingleton (ApplicationProperties, false)
  21934. /** Gives the object the information it needs to create the appropriate properties files.
  21935. See the comments for PropertiesFile::createDefaultAppPropertiesFile() for more
  21936. info about how these parameters are used.
  21937. */
  21938. void setStorageParameters (const String& applicationName,
  21939. const String& fileNameSuffix,
  21940. const String& folderName,
  21941. int millisecondsBeforeSaving,
  21942. int propertiesFileOptions) throw();
  21943. /** Tests whether the files can be successfully written to, and can show
  21944. an error message if not.
  21945. Returns true if none of the tests fail.
  21946. @param testUserSettings if true, the user settings file will be tested
  21947. @param testCommonSettings if true, the common settings file will be tested
  21948. @param showWarningDialogOnFailure if true, the method will show a helpful error
  21949. message box if either of the tests fail
  21950. */
  21951. bool testWriteAccess (bool testUserSettings,
  21952. bool testCommonSettings,
  21953. bool showWarningDialogOnFailure);
  21954. /** Returns the user settings file.
  21955. The first time this is called, it will create and load the properties file.
  21956. Note that when you search the user PropertiesFile for a value that it doesn't contain,
  21957. the common settings are used as a second-chance place to look. This is done via the
  21958. PropertySet::setFallbackPropertySet() method - by default the common settings are set
  21959. to the fallback for the user settings.
  21960. @see getCommonSettings
  21961. */
  21962. PropertiesFile* getUserSettings() throw();
  21963. /** Returns the common settings file.
  21964. The first time this is called, it will create and load the properties file.
  21965. @param returnUserPropsIfReadOnly if this is true, and the common properties file is
  21966. read-only (e.g. because the user doesn't have permission to write
  21967. to shared files), then this will return the user settings instead,
  21968. (like getUserSettings() would do). This is handy if you'd like to
  21969. write a value to the common settings, but if that's no possible,
  21970. then you'd rather write to the user settings than none at all.
  21971. If returnUserPropsIfReadOnly is false, this method will always return
  21972. the common settings, even if any changes to them can't be saved.
  21973. @see getUserSettings
  21974. */
  21975. PropertiesFile* getCommonSettings (bool returnUserPropsIfReadOnly) throw();
  21976. /** Saves both files if they need to be saved.
  21977. @see PropertiesFile::saveIfNeeded
  21978. */
  21979. bool saveIfNeeded();
  21980. /** Flushes and closes both files if they are open.
  21981. This flushes any pending changes to disk with PropertiesFile::saveIfNeeded()
  21982. and closes both files. They will then be re-opened the next time getUserSettings()
  21983. or getCommonSettings() is called.
  21984. */
  21985. void closeFiles();
  21986. juce_UseDebuggingNewOperator
  21987. private:
  21988. ScopedPointer <PropertiesFile> userProps, commonProps;
  21989. String appName, fileSuffix, folderName;
  21990. int msBeforeSaving, options;
  21991. int commonSettingsAreReadOnly;
  21992. ApplicationProperties (const ApplicationProperties&);
  21993. ApplicationProperties& operator= (const ApplicationProperties&);
  21994. void openFiles() throw();
  21995. };
  21996. #endif // __JUCE_APPLICATIONPROPERTIES_JUCEHEADER__
  21997. /*** End of inlined file: juce_ApplicationProperties.h ***/
  21998. #endif
  21999. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22000. /*** Start of inlined file: juce_AiffAudioFormat.h ***/
  22001. #ifndef __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22002. #define __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22003. /*** Start of inlined file: juce_AudioFormat.h ***/
  22004. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  22005. #define __JUCE_AUDIOFORMAT_JUCEHEADER__
  22006. /*** Start of inlined file: juce_AudioFormatReader.h ***/
  22007. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22008. #define __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22009. class AudioFormat;
  22010. /**
  22011. Reads samples from an audio file stream.
  22012. A subclass that reads a specific type of audio format will be created by
  22013. an AudioFormat object.
  22014. @see AudioFormat, AudioFormatWriter
  22015. */
  22016. class JUCE_API AudioFormatReader
  22017. {
  22018. protected:
  22019. /** Creates an AudioFormatReader object.
  22020. @param sourceStream the stream to read from - this will be deleted
  22021. by this object when it is no longer needed. (Some
  22022. specialised readers might not use this parameter and
  22023. can leave it as 0).
  22024. @param formatName the description that will be returned by the getFormatName()
  22025. method
  22026. */
  22027. AudioFormatReader (InputStream* sourceStream,
  22028. const String& formatName);
  22029. public:
  22030. /** Destructor. */
  22031. virtual ~AudioFormatReader();
  22032. /** Returns a description of what type of format this is.
  22033. E.g. "AIFF"
  22034. */
  22035. const String getFormatName() const throw() { return formatName; }
  22036. /** Reads samples from the stream.
  22037. @param destSamples an array of buffers into which the sample data for each
  22038. channel will be written.
  22039. If the format is fixed-point, each channel will be written
  22040. as an array of 32-bit signed integers using the full
  22041. range -0x80000000 to 0x7fffffff, regardless of the source's
  22042. bit-depth. If it is a floating-point format, you should cast
  22043. the resulting array to a (float**) to get the values (in the
  22044. range -1.0 to 1.0 or beyond)
  22045. If the format is stereo, then destSamples[0] is the left channel
  22046. data, and destSamples[1] is the right channel.
  22047. The numDestChannels parameter indicates how many pointers this array
  22048. contains, but some of these pointers can be null if you don't want to
  22049. read data for some of the channels
  22050. @param numDestChannels the number of array elements in the destChannels array
  22051. @param startSampleInSource the position in the audio file or stream at which the samples
  22052. should be read, as a number of samples from the start of the
  22053. stream. It's ok for this to be beyond the start or end of the
  22054. available data - any samples that are out-of-range will be returned
  22055. as zeros.
  22056. @param numSamplesToRead the number of samples to read. If this is greater than the number
  22057. of samples that the file or stream contains. the result will be padded
  22058. with zeros
  22059. @param fillLeftoverChannelsWithCopies if true, this indicates that if there's no source data available
  22060. for some of the channels that you pass in, then they should be filled with
  22061. copies of valid source channels.
  22062. E.g. if you're reading a mono file and you pass 2 channels to this method, then
  22063. if fillLeftoverChannelsWithCopies is true, both destination channels will be filled
  22064. with the same data from the file's single channel. If fillLeftoverChannelsWithCopies
  22065. was false, then only the first channel would be filled with the file's contents, and
  22066. the second would be cleared. If there are many channels, e.g. you try to read 4 channels
  22067. from a stereo file, then the last 3 would all end up with copies of the same data.
  22068. @returns true if the operation succeeded, false if there was an error. Note
  22069. that reading sections of data beyond the extent of the stream isn't an
  22070. error - the reader should just return zeros for these regions
  22071. @see readMaxLevels
  22072. */
  22073. bool read (int** destSamples,
  22074. int numDestChannels,
  22075. int64 startSampleInSource,
  22076. int numSamplesToRead,
  22077. bool fillLeftoverChannelsWithCopies);
  22078. /** Finds the highest and lowest sample levels from a section of the audio stream.
  22079. This will read a block of samples from the stream, and measure the
  22080. highest and lowest sample levels from the channels in that section, returning
  22081. these as normalised floating-point levels.
  22082. @param startSample the offset into the audio stream to start reading from. It's
  22083. ok for this to be beyond the start or end of the stream.
  22084. @param numSamples how many samples to read
  22085. @param lowestLeft on return, this is the lowest absolute sample from the left channel
  22086. @param highestLeft on return, this is the highest absolute sample from the left channel
  22087. @param lowestRight on return, this is the lowest absolute sample from the right
  22088. channel (if there is one)
  22089. @param highestRight on return, this is the highest absolute sample from the right
  22090. channel (if there is one)
  22091. @see read
  22092. */
  22093. virtual void readMaxLevels (int64 startSample,
  22094. int64 numSamples,
  22095. float& lowestLeft,
  22096. float& highestLeft,
  22097. float& lowestRight,
  22098. float& highestRight);
  22099. /** Scans the source looking for a sample whose magnitude is in a specified range.
  22100. This will read from the source, either forwards or backwards between two sample
  22101. positions, until it finds a sample whose magnitude lies between two specified levels.
  22102. If it finds a suitable sample, it returns its position; if not, it will return -1.
  22103. There's also a minimumConsecutiveSamples setting to help avoid spikes or zero-crossing
  22104. points when you're searching for a continuous range of samples
  22105. @param startSample the first sample to look at
  22106. @param numSamplesToSearch the number of samples to scan. If this value is negative,
  22107. the search will go backwards
  22108. @param magnitudeRangeMinimum the lowest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  22109. @param magnitudeRangeMaximum the highest magnitude (inclusive) that is considered a hit, from 0 to 1.0
  22110. @param minimumConsecutiveSamples if this is > 0, the method will only look for a sequence
  22111. of this many consecutive samples, all of which lie
  22112. within the target range. When it finds such a sequence,
  22113. it returns the position of the first in-range sample
  22114. it found (i.e. the earliest one if scanning forwards, the
  22115. latest one if scanning backwards)
  22116. */
  22117. int64 searchForLevel (int64 startSample,
  22118. int64 numSamplesToSearch,
  22119. double magnitudeRangeMinimum,
  22120. double magnitudeRangeMaximum,
  22121. int minimumConsecutiveSamples);
  22122. /** The sample-rate of the stream. */
  22123. double sampleRate;
  22124. /** The number of bits per sample, e.g. 16, 24, 32. */
  22125. unsigned int bitsPerSample;
  22126. /** The total number of samples in the audio stream. */
  22127. int64 lengthInSamples;
  22128. /** The total number of channels in the audio stream. */
  22129. unsigned int numChannels;
  22130. /** Indicates whether the data is floating-point or fixed. */
  22131. bool usesFloatingPointData;
  22132. /** A set of metadata values that the reader has pulled out of the stream.
  22133. Exactly what these values are depends on the format, so you can
  22134. check out the format implementation code to see what kind of stuff
  22135. they understand.
  22136. */
  22137. StringPairArray metadataValues;
  22138. /** The input stream, for use by subclasses. */
  22139. InputStream* input;
  22140. /** Subclasses must implement this method to perform the low-level read operation.
  22141. Callers should use read() instead of calling this directly.
  22142. @param destSamples the array of destination buffers to fill. Some of these
  22143. pointers may be null
  22144. @param numDestChannels the number of items in the destSamples array. This
  22145. value is guaranteed not to be greater than the number of
  22146. channels that this reader object contains
  22147. @param startOffsetInDestBuffer the number of samples from the start of the
  22148. dest data at which to begin writing
  22149. @param startSampleInFile the number of samples into the source data at which
  22150. to begin reading. This value is guaranteed to be >= 0.
  22151. @param numSamples the number of samples to read
  22152. */
  22153. virtual bool readSamples (int** destSamples,
  22154. int numDestChannels,
  22155. int startOffsetInDestBuffer,
  22156. int64 startSampleInFile,
  22157. int numSamples) = 0;
  22158. juce_UseDebuggingNewOperator
  22159. private:
  22160. String formatName;
  22161. AudioFormatReader (const AudioFormatReader&);
  22162. AudioFormatReader& operator= (const AudioFormatReader&);
  22163. };
  22164. #endif // __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  22165. /*** End of inlined file: juce_AudioFormatReader.h ***/
  22166. /*** Start of inlined file: juce_AudioFormatWriter.h ***/
  22167. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22168. #define __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22169. /*** Start of inlined file: juce_AudioSource.h ***/
  22170. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  22171. #define __JUCE_AUDIOSOURCE_JUCEHEADER__
  22172. /*** Start of inlined file: juce_AudioSampleBuffer.h ***/
  22173. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22174. #define __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22175. class AudioFormatReader;
  22176. class AudioFormatWriter;
  22177. /**
  22178. A multi-channel buffer of 32-bit floating point audio samples.
  22179. */
  22180. class JUCE_API AudioSampleBuffer
  22181. {
  22182. public:
  22183. /** Creates a buffer with a specified number of channels and samples.
  22184. The contents of the buffer will initially be undefined, so use clear() to
  22185. set all the samples to zero.
  22186. The buffer will allocate its memory internally, and this will be released
  22187. when the buffer is deleted.
  22188. */
  22189. AudioSampleBuffer (int numChannels,
  22190. int numSamples) throw();
  22191. /** Creates a buffer using a pre-allocated block of memory.
  22192. Note that if the buffer is resized or its number of channels is changed, it
  22193. will re-allocate memory internally and copy the existing data to this new area,
  22194. so it will then stop directly addressing this memory.
  22195. @param dataToReferTo a pre-allocated array containing pointers to the data
  22196. for each channel that should be used by this buffer. The
  22197. buffer will only refer to this memory, it won't try to delete
  22198. it when the buffer is deleted or resized.
  22199. @param numChannels the number of channels to use - this must correspond to the
  22200. number of elements in the array passed in
  22201. @param numSamples the number of samples to use - this must correspond to the
  22202. size of the arrays passed in
  22203. */
  22204. AudioSampleBuffer (float** dataToReferTo,
  22205. int numChannels,
  22206. int numSamples) throw();
  22207. /** Copies another buffer.
  22208. This buffer will make its own copy of the other's data, unless the buffer was created
  22209. using an external data buffer, in which case boths buffers will just point to the same
  22210. shared block of data.
  22211. */
  22212. AudioSampleBuffer (const AudioSampleBuffer& other) throw();
  22213. /** Copies another buffer onto this one.
  22214. This buffer's size will be changed to that of the other buffer.
  22215. */
  22216. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) throw();
  22217. /** Destructor.
  22218. This will free any memory allocated by the buffer.
  22219. */
  22220. virtual ~AudioSampleBuffer() throw();
  22221. /** Returns the number of channels of audio data that this buffer contains.
  22222. @see getSampleData
  22223. */
  22224. int getNumChannels() const throw() { return numChannels; }
  22225. /** Returns the number of samples allocated in each of the buffer's channels.
  22226. @see getSampleData
  22227. */
  22228. int getNumSamples() const throw() { return size; }
  22229. /** Returns a pointer one of the buffer's channels.
  22230. For speed, this doesn't check whether the channel number is out of range,
  22231. so be careful when using it!
  22232. */
  22233. float* getSampleData (const int channelNumber) const throw()
  22234. {
  22235. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  22236. return channels [channelNumber];
  22237. }
  22238. /** Returns a pointer to a sample in one of the buffer's channels.
  22239. For speed, this doesn't check whether the channel and sample number
  22240. are out-of-range, so be careful when using it!
  22241. */
  22242. float* getSampleData (const int channelNumber,
  22243. const int sampleOffset) const throw()
  22244. {
  22245. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  22246. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  22247. return channels [channelNumber] + sampleOffset;
  22248. }
  22249. /** Returns an array of pointers to the channels in the buffer.
  22250. Don't modify any of the pointers that are returned, and bear in mind that
  22251. these will become invalid if the buffer is resized.
  22252. */
  22253. float** getArrayOfChannels() const throw() { return channels; }
  22254. /** Chages the buffer's size or number of channels.
  22255. This can expand or contract the buffer's length, and add or remove channels.
  22256. If keepExistingContent is true, it will try to preserve as much of the
  22257. old data as it can in the new buffer.
  22258. If clearExtraSpace is true, then any extra channels or space that is
  22259. allocated will be also be cleared. If false, then this space is left
  22260. uninitialised.
  22261. If avoidReallocating is true, then changing the buffer's size won't reduce the
  22262. amount of memory that is currently allocated (but it will still increase it if
  22263. the new size is bigger than the amount it currently has). If this is false, then
  22264. a new allocation will be done so that the buffer uses takes up the minimum amount
  22265. of memory that it needs.
  22266. */
  22267. void setSize (int newNumChannels,
  22268. int newNumSamples,
  22269. bool keepExistingContent = false,
  22270. bool clearExtraSpace = false,
  22271. bool avoidReallocating = false) throw();
  22272. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  22273. There's also a constructor that lets you specify arrays like this, but this
  22274. lets you change the channels dynamically.
  22275. Note that if the buffer is resized or its number of channels is changed, it
  22276. will re-allocate memory internally and copy the existing data to this new area,
  22277. so it will then stop directly addressing this memory.
  22278. @param dataToReferTo a pre-allocated array containing pointers to the data
  22279. for each channel that should be used by this buffer. The
  22280. buffer will only refer to this memory, it won't try to delete
  22281. it when the buffer is deleted or resized.
  22282. @param numChannels the number of channels to use - this must correspond to the
  22283. number of elements in the array passed in
  22284. @param numSamples the number of samples to use - this must correspond to the
  22285. size of the arrays passed in
  22286. */
  22287. void setDataToReferTo (float** dataToReferTo,
  22288. int numChannels,
  22289. int numSamples) throw();
  22290. /** Clears all the samples in all channels. */
  22291. void clear() throw();
  22292. /** Clears a specified region of all the channels.
  22293. For speed, this doesn't check whether the channel and sample number
  22294. are in-range, so be careful!
  22295. */
  22296. void clear (int startSample,
  22297. int numSamples) throw();
  22298. /** Clears a specified region of just one channel.
  22299. For speed, this doesn't check whether the channel and sample number
  22300. are in-range, so be careful!
  22301. */
  22302. void clear (int channel,
  22303. int startSample,
  22304. int numSamples) throw();
  22305. /** Applies a gain multiple to a region of one channel.
  22306. For speed, this doesn't check whether the channel and sample number
  22307. are in-range, so be careful!
  22308. */
  22309. void applyGain (int channel,
  22310. int startSample,
  22311. int numSamples,
  22312. float gain) throw();
  22313. /** Applies a gain multiple to a region of all the channels.
  22314. For speed, this doesn't check whether the sample numbers
  22315. are in-range, so be careful!
  22316. */
  22317. void applyGain (int startSample,
  22318. int numSamples,
  22319. float gain) throw();
  22320. /** Applies a range of gains to a region of a channel.
  22321. The gain that is applied to each sample will vary from
  22322. startGain on the first sample to endGain on the last Sample,
  22323. so it can be used to do basic fades.
  22324. For speed, this doesn't check whether the sample numbers
  22325. are in-range, so be careful!
  22326. */
  22327. void applyGainRamp (int channel,
  22328. int startSample,
  22329. int numSamples,
  22330. float startGain,
  22331. float endGain) throw();
  22332. /** Adds samples from another buffer to this one.
  22333. @param destChannel the channel within this buffer to add the samples to
  22334. @param destStartSample the start sample within this buffer's channel
  22335. @param source the source buffer to add from
  22336. @param sourceChannel the channel within the source buffer to read from
  22337. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22338. @param numSamples the number of samples to process
  22339. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22340. added to this buffer's samples
  22341. @see copyFrom
  22342. */
  22343. void addFrom (int destChannel,
  22344. int destStartSample,
  22345. const AudioSampleBuffer& source,
  22346. int sourceChannel,
  22347. int sourceStartSample,
  22348. int numSamples,
  22349. float gainToApplyToSource = 1.0f) throw();
  22350. /** Adds samples from an array of floats to one of the channels.
  22351. @param destChannel the channel within this buffer to add the samples to
  22352. @param destStartSample the start sample within this buffer's channel
  22353. @param source the source data to use
  22354. @param numSamples the number of samples to process
  22355. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  22356. added to this buffer's samples
  22357. @see copyFrom
  22358. */
  22359. void addFrom (int destChannel,
  22360. int destStartSample,
  22361. const float* source,
  22362. int numSamples,
  22363. float gainToApplyToSource = 1.0f) throw();
  22364. /** Adds samples from an array of floats, applying a gain ramp to them.
  22365. @param destChannel the channel within this buffer to add the samples to
  22366. @param destStartSample the start sample within this buffer's channel
  22367. @param source the source data to use
  22368. @param numSamples the number of samples to process
  22369. @param startGain the gain to apply to the first sample (this is multiplied with
  22370. the source samples before they are added to this buffer)
  22371. @param endGain the gain to apply to the final sample. The gain is linearly
  22372. interpolated between the first and last samples.
  22373. */
  22374. void addFromWithRamp (int destChannel,
  22375. int destStartSample,
  22376. const float* source,
  22377. int numSamples,
  22378. float startGain,
  22379. float endGain) throw();
  22380. /** Copies samples from another buffer to this one.
  22381. @param destChannel the channel within this buffer to copy the samples to
  22382. @param destStartSample the start sample within this buffer's channel
  22383. @param source the source buffer to read from
  22384. @param sourceChannel the channel within the source buffer to read from
  22385. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  22386. @param numSamples the number of samples to process
  22387. @see addFrom
  22388. */
  22389. void copyFrom (int destChannel,
  22390. int destStartSample,
  22391. const AudioSampleBuffer& source,
  22392. int sourceChannel,
  22393. int sourceStartSample,
  22394. int numSamples) throw();
  22395. /** Copies samples from an array of floats into one of the channels.
  22396. @param destChannel the channel within this buffer to copy the samples to
  22397. @param destStartSample the start sample within this buffer's channel
  22398. @param source the source buffer to read from
  22399. @param numSamples the number of samples to process
  22400. @see addFrom
  22401. */
  22402. void copyFrom (int destChannel,
  22403. int destStartSample,
  22404. const float* source,
  22405. int numSamples) throw();
  22406. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  22407. @param destChannel the channel within this buffer to copy the samples to
  22408. @param destStartSample the start sample within this buffer's channel
  22409. @param source the source buffer to read from
  22410. @param numSamples the number of samples to process
  22411. @param gain the gain to apply
  22412. @see addFrom
  22413. */
  22414. void copyFrom (int destChannel,
  22415. int destStartSample,
  22416. const float* source,
  22417. int numSamples,
  22418. float gain) throw();
  22419. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  22420. @param destChannel the channel within this buffer to copy the samples to
  22421. @param destStartSample the start sample within this buffer's channel
  22422. @param source the source buffer to read from
  22423. @param numSamples the number of samples to process
  22424. @param startGain the gain to apply to the first sample (this is multiplied with
  22425. the source samples before they are copied to this buffer)
  22426. @param endGain the gain to apply to the final sample. The gain is linearly
  22427. interpolated between the first and last samples.
  22428. @see addFrom
  22429. */
  22430. void copyFromWithRamp (int destChannel,
  22431. int destStartSample,
  22432. const float* source,
  22433. int numSamples,
  22434. float startGain,
  22435. float endGain) throw();
  22436. /** Finds the highest and lowest sample values in a given range.
  22437. @param channel the channel to read from
  22438. @param startSample the start sample within the channel
  22439. @param numSamples the number of samples to check
  22440. @param minVal on return, the lowest value that was found
  22441. @param maxVal on return, the highest value that was found
  22442. */
  22443. void findMinMax (int channel,
  22444. int startSample,
  22445. int numSamples,
  22446. float& minVal,
  22447. float& maxVal) const throw();
  22448. /** Finds the highest absolute sample value within a region of a channel.
  22449. */
  22450. float getMagnitude (int channel,
  22451. int startSample,
  22452. int numSamples) const throw();
  22453. /** Finds the highest absolute sample value within a region on all channels.
  22454. */
  22455. float getMagnitude (int startSample,
  22456. int numSamples) const throw();
  22457. /** Returns the root mean squared level for a region of a channel.
  22458. */
  22459. float getRMSLevel (int channel,
  22460. int startSample,
  22461. int numSamples) const throw();
  22462. /** Fills a section of the buffer using an AudioReader as its source.
  22463. This will convert the reader's fixed- or floating-point data to
  22464. the buffer's floating-point format, and will try to intelligently
  22465. cope with mismatches between the number of channels in the reader
  22466. and the buffer.
  22467. @see writeToAudioWriter
  22468. */
  22469. void readFromAudioReader (AudioFormatReader* reader,
  22470. int startSample,
  22471. int numSamples,
  22472. int readerStartSample,
  22473. bool useReaderLeftChan,
  22474. bool useReaderRightChan);
  22475. /** Writes a section of this buffer to an audio writer.
  22476. This saves you having to mess about with channels or floating/fixed
  22477. point conversion.
  22478. @see readFromAudioReader
  22479. */
  22480. void writeToAudioWriter (AudioFormatWriter* writer,
  22481. int startSample,
  22482. int numSamples) const;
  22483. juce_UseDebuggingNewOperator
  22484. private:
  22485. int numChannels, size;
  22486. size_t allocatedBytes;
  22487. float** channels;
  22488. HeapBlock <char> allocatedData;
  22489. float* preallocatedChannelSpace [32];
  22490. void allocateData();
  22491. void allocateChannels (float** dataToReferTo);
  22492. };
  22493. #endif // __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  22494. /*** End of inlined file: juce_AudioSampleBuffer.h ***/
  22495. /**
  22496. Used by AudioSource::getNextAudioBlock().
  22497. */
  22498. struct JUCE_API AudioSourceChannelInfo
  22499. {
  22500. /** The destination buffer to fill with audio data.
  22501. When the AudioSource::getNextAudioBlock() method is called, the active section
  22502. of this buffer should be filled with whatever output the source produces.
  22503. Only the samples specified by the startSample and numSamples members of this structure
  22504. should be affected by the call.
  22505. The contents of the buffer when it is passed to the the AudioSource::getNextAudioBlock()
  22506. method can be treated as the input if the source is performing some kind of filter operation,
  22507. but should be cleared if this is not the case - the clearActiveBufferRegion() is
  22508. a handy way of doing this.
  22509. The number of channels in the buffer could be anything, so the AudioSource
  22510. must cope with this in whatever way is appropriate for its function.
  22511. */
  22512. AudioSampleBuffer* buffer;
  22513. /** The first sample in the buffer from which the callback is expected
  22514. to write data. */
  22515. int startSample;
  22516. /** The number of samples in the buffer which the callback is expected to
  22517. fill with data. */
  22518. int numSamples;
  22519. /** Convenient method to clear the buffer if the source is not producing any data. */
  22520. void clearActiveBufferRegion() const
  22521. {
  22522. if (buffer != 0)
  22523. buffer->clear (startSample, numSamples);
  22524. }
  22525. };
  22526. /**
  22527. Base class for objects that can produce a continuous stream of audio.
  22528. @see AudioFormatReaderSource, ResamplingAudioSource
  22529. */
  22530. class JUCE_API AudioSource
  22531. {
  22532. protected:
  22533. /** Creates an AudioSource. */
  22534. AudioSource() throw() {}
  22535. public:
  22536. /** Destructor. */
  22537. virtual ~AudioSource() {}
  22538. /** Tells the source to prepare for playing.
  22539. The source can use this opportunity to initialise anything it needs to.
  22540. Note that this method could be called more than once in succession without
  22541. a matching call to releaseResources(), so make sure your code is robust and
  22542. can handle that kind of situation.
  22543. @param samplesPerBlockExpected the number of samples that the source
  22544. will be expected to supply each time its
  22545. getNextAudioBlock() method is called. This
  22546. number may vary slightly, because it will be dependent
  22547. on audio hardware callbacks, and these aren't
  22548. guaranteed to always use a constant block size, so
  22549. the source should be able to cope with small variations.
  22550. @param sampleRate the sample rate that the output will be used at - this
  22551. is needed by sources such as tone generators.
  22552. @see releaseResources, getNextAudioBlock
  22553. */
  22554. virtual void prepareToPlay (int samplesPerBlockExpected,
  22555. double sampleRate) = 0;
  22556. /** Allows the source to release anything it no longer needs after playback has stopped.
  22557. This will be called when the source is no longer going to have its getNextAudioBlock()
  22558. method called, so it should release any spare memory, etc. that it might have
  22559. allocated during the prepareToPlay() call.
  22560. Note that there's no guarantee that prepareToPlay() will actually have been called before
  22561. releaseResources(), and it may be called more than once in succession, so make sure your
  22562. code is robust and doesn't make any assumptions about when it will be called.
  22563. @see prepareToPlay, getNextAudioBlock
  22564. */
  22565. virtual void releaseResources() = 0;
  22566. /** Called repeatedly to fetch subsequent blocks of audio data.
  22567. After calling the prepareToPlay() method, this callback will be made each
  22568. time the audio playback hardware (or whatever other destination the audio
  22569. data is going to) needs another block of data.
  22570. It will generally be called on a high-priority system thread, or possibly even
  22571. an interrupt, so be careful not to do too much work here, as that will cause
  22572. audio glitches!
  22573. @see AudioSourceChannelInfo, prepareToPlay, releaseResources
  22574. */
  22575. virtual void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) = 0;
  22576. };
  22577. #endif // __JUCE_AUDIOSOURCE_JUCEHEADER__
  22578. /*** End of inlined file: juce_AudioSource.h ***/
  22579. /**
  22580. Writes samples to an audio file stream.
  22581. A subclass that writes a specific type of audio format will be created by
  22582. an AudioFormat object.
  22583. After creating one of these with the AudioFormat::createWriterFor() method
  22584. you can call its write() method to store the samples, and then delete it.
  22585. @see AudioFormat, AudioFormatReader
  22586. */
  22587. class JUCE_API AudioFormatWriter
  22588. {
  22589. protected:
  22590. /** Creates an AudioFormatWriter object.
  22591. @param destStream the stream to write to - this will be deleted
  22592. by this object when it is no longer needed
  22593. @param formatName the description that will be returned by the getFormatName()
  22594. method
  22595. @param sampleRate the sample rate to use - the base class just stores
  22596. this value, it doesn't do anything with it
  22597. @param numberOfChannels the number of channels to write - the base class just stores
  22598. this value, it doesn't do anything with it
  22599. @param bitsPerSample the bit depth of the stream - the base class just stores
  22600. this value, it doesn't do anything with it
  22601. */
  22602. AudioFormatWriter (OutputStream* destStream,
  22603. const String& formatName,
  22604. double sampleRate,
  22605. unsigned int numberOfChannels,
  22606. unsigned int bitsPerSample);
  22607. public:
  22608. /** Destructor. */
  22609. virtual ~AudioFormatWriter();
  22610. /** Returns a description of what type of format this is.
  22611. E.g. "AIFF file"
  22612. */
  22613. const String getFormatName() const throw() { return formatName; }
  22614. /** Writes a set of samples to the audio stream.
  22615. Note that if you're trying to write the contents of an AudioSampleBuffer, you
  22616. can use AudioSampleBuffer::writeToAudioWriter().
  22617. @param samplesToWrite an array of arrays containing the sample data for
  22618. each channel to write. This is a zero-terminated
  22619. array of arrays, and can contain a different number
  22620. of channels than the actual stream uses, and the
  22621. writer should do its best to cope with this.
  22622. If the format is fixed-point, each channel will be formatted
  22623. as an array of signed integers using the full 32-bit
  22624. range -0x80000000 to 0x7fffffff, regardless of the source's
  22625. bit-depth. If it is a floating-point format, you should treat
  22626. the arrays as arrays of floats, and just cast it to an (int**)
  22627. to pass it into the method.
  22628. @param numSamples the number of samples to write
  22629. */
  22630. virtual bool write (const int** samplesToWrite,
  22631. int numSamples) = 0;
  22632. /** Reads a section of samples from an AudioFormatReader, and writes these to
  22633. the output.
  22634. This will take care of any floating-point conversion that's required to convert
  22635. between the two formats. It won't deal with sample-rate conversion, though.
  22636. If numSamplesToRead < 0, it will write the entire length of the reader.
  22637. @returns false if it can't read or write properly during the operation
  22638. */
  22639. bool writeFromAudioReader (AudioFormatReader& reader,
  22640. int64 startSample,
  22641. int64 numSamplesToRead);
  22642. /** Reads some samples from an AudioSource, and writes these to the output.
  22643. The source must already have been initialised with the AudioSource::prepareToPlay() method
  22644. @param source the source to read from
  22645. @param numSamplesToRead total number of samples to read and write
  22646. @param samplesPerBlock the maximum number of samples to fetch from the source
  22647. @returns false if it can't read or write properly during the operation
  22648. */
  22649. bool writeFromAudioSource (AudioSource& source,
  22650. int numSamplesToRead,
  22651. int samplesPerBlock = 2048);
  22652. /** Returns the sample rate being used. */
  22653. double getSampleRate() const throw() { return sampleRate; }
  22654. /** Returns the number of channels being written. */
  22655. int getNumChannels() const throw() { return numChannels; }
  22656. /** Returns the bit-depth of the data being written. */
  22657. int getBitsPerSample() const throw() { return bitsPerSample; }
  22658. /** Returns true if it's a floating-point format, false if it's fixed-point. */
  22659. bool isFloatingPoint() const throw() { return usesFloatingPointData; }
  22660. juce_UseDebuggingNewOperator
  22661. protected:
  22662. /** The sample rate of the stream. */
  22663. double sampleRate;
  22664. /** The number of channels being written to the stream. */
  22665. unsigned int numChannels;
  22666. /** The bit depth of the file. */
  22667. unsigned int bitsPerSample;
  22668. /** True if it's a floating-point format, false if it's fixed-point. */
  22669. bool usesFloatingPointData;
  22670. /** The output stream for Use by subclasses. */
  22671. OutputStream* output;
  22672. private:
  22673. String formatName;
  22674. AudioFormatWriter (const AudioFormatWriter&);
  22675. AudioFormatWriter& operator= (const AudioFormatWriter&);
  22676. };
  22677. #endif // __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  22678. /*** End of inlined file: juce_AudioFormatWriter.h ***/
  22679. /**
  22680. Subclasses of AudioFormat are used to read and write different audio
  22681. file formats.
  22682. @see AudioFormatReader, AudioFormatWriter, WavAudioFormat, AiffAudioFormat
  22683. */
  22684. class JUCE_API AudioFormat
  22685. {
  22686. public:
  22687. /** Destructor. */
  22688. virtual ~AudioFormat();
  22689. /** Returns the name of this format.
  22690. e.g. "WAV file" or "AIFF file"
  22691. */
  22692. const String& getFormatName() const;
  22693. /** Returns all the file extensions that might apply to a file of this format.
  22694. The first item will be the one that's preferred when creating a new file.
  22695. So for a wav file this might just return ".wav"; for an AIFF file it might
  22696. return two items, ".aif" and ".aiff"
  22697. */
  22698. const StringArray& getFileExtensions() const;
  22699. /** Returns true if this the given file can be read by this format.
  22700. Subclasses shouldn't do too much work here, just check the extension or
  22701. file type. The base class implementation just checks the file's extension
  22702. against one of the ones that was registered in the constructor.
  22703. */
  22704. virtual bool canHandleFile (const File& fileToTest);
  22705. /** Returns a set of sample rates that the format can read and write. */
  22706. virtual const Array <int> getPossibleSampleRates() = 0;
  22707. /** Returns a set of bit depths that the format can read and write. */
  22708. virtual const Array <int> getPossibleBitDepths() = 0;
  22709. /** Returns true if the format can do 2-channel audio. */
  22710. virtual bool canDoStereo() = 0;
  22711. /** Returns true if the format can do 1-channel audio. */
  22712. virtual bool canDoMono() = 0;
  22713. /** Returns true if the format uses compressed data. */
  22714. virtual bool isCompressed();
  22715. /** Returns a list of different qualities that can be used when writing.
  22716. Non-compressed formats will just return an empty array, but for something
  22717. like Ogg-Vorbis or MP3, it might return a list of bit-rates, etc.
  22718. When calling createWriterFor(), an index from this array is passed in to
  22719. tell the format which option is required.
  22720. */
  22721. virtual const StringArray getQualityOptions();
  22722. /** Tries to create an object that can read from a stream containing audio
  22723. data in this format.
  22724. The reader object that is returned can be used to read from the stream, and
  22725. should then be deleted by the caller.
  22726. @param sourceStream the stream to read from - the AudioFormatReader object
  22727. that is returned will delete this stream when it no longer
  22728. needs it.
  22729. @param deleteStreamIfOpeningFails if no reader can be created, this determines whether this method
  22730. should delete the stream object that was passed-in. (If a valid
  22731. reader is returned, it will always be in charge of deleting the
  22732. stream, so this parameter is ignored)
  22733. @see AudioFormatReader
  22734. */
  22735. virtual AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22736. const bool deleteStreamIfOpeningFails) = 0;
  22737. /** Tries to create an object that can write to a stream with this audio format.
  22738. The writer object that is returned can be used to write to the stream, and
  22739. should then be deleted by the caller.
  22740. If the stream can't be created for some reason (e.g. the parameters passed in
  22741. here aren't suitable), this will return 0.
  22742. @param streamToWriteTo the stream that the data will go to - this will be
  22743. deleted by the AudioFormatWriter object when it's no longer
  22744. needed. If no AudioFormatWriter can be created by this method,
  22745. the stream will NOT be deleted, so that the caller can re-use it
  22746. to try to open a different format, etc
  22747. @param sampleRateToUse the sample rate for the file, which must be one of the ones
  22748. returned by getPossibleSampleRates()
  22749. @param numberOfChannels the number of channels - this must be either 1 or 2, and
  22750. the choice will depend on the results of canDoMono() and
  22751. canDoStereo()
  22752. @param bitsPerSample the bits per sample to use - this must be one of the values
  22753. returned by getPossibleBitDepths()
  22754. @param metadataValues a set of metadata values that the writer should try to write
  22755. to the stream. Exactly what these are depends on the format,
  22756. and the subclass doesn't actually have to do anything with
  22757. them if it doesn't want to. Have a look at the specific format
  22758. implementation classes to see possible values that can be
  22759. used
  22760. @param qualityOptionIndex the index of one of compression qualities returned by the
  22761. getQualityOptions() method. If there aren't any quality options
  22762. for this format, just pass 0 in this parameter, as it'll be
  22763. ignored
  22764. @see AudioFormatWriter
  22765. */
  22766. virtual AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22767. double sampleRateToUse,
  22768. unsigned int numberOfChannels,
  22769. int bitsPerSample,
  22770. const StringPairArray& metadataValues,
  22771. int qualityOptionIndex) = 0;
  22772. protected:
  22773. /** Creates an AudioFormat object.
  22774. @param formatName this sets the value that will be returned by getFormatName()
  22775. @param fileExtensions a zero-terminated list of file extensions - this is what will
  22776. be returned by getFileExtension()
  22777. */
  22778. AudioFormat (const String& formatName,
  22779. const StringArray& fileExtensions);
  22780. private:
  22781. String formatName;
  22782. StringArray fileExtensions;
  22783. };
  22784. #endif // __JUCE_AUDIOFORMAT_JUCEHEADER__
  22785. /*** End of inlined file: juce_AudioFormat.h ***/
  22786. /**
  22787. Reads and Writes AIFF format audio files.
  22788. @see AudioFormat
  22789. */
  22790. class JUCE_API AiffAudioFormat : public AudioFormat
  22791. {
  22792. public:
  22793. /** Creates an format object. */
  22794. AiffAudioFormat();
  22795. /** Destructor. */
  22796. ~AiffAudioFormat();
  22797. const Array <int> getPossibleSampleRates();
  22798. const Array <int> getPossibleBitDepths();
  22799. bool canDoStereo();
  22800. bool canDoMono();
  22801. #if JUCE_MAC
  22802. bool canHandleFile (const File& fileToTest);
  22803. #endif
  22804. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  22805. const bool deleteStreamIfOpeningFails);
  22806. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  22807. double sampleRateToUse,
  22808. unsigned int numberOfChannels,
  22809. int bitsPerSample,
  22810. const StringPairArray& metadataValues,
  22811. int qualityOptionIndex);
  22812. juce_UseDebuggingNewOperator
  22813. };
  22814. #endif // __JUCE_AIFFAUDIOFORMAT_JUCEHEADER__
  22815. /*** End of inlined file: juce_AiffAudioFormat.h ***/
  22816. #endif
  22817. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22818. /*** Start of inlined file: juce_AudioCDBurner.h ***/
  22819. #ifndef __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22820. #define __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22821. #if JUCE_USE_CDBURNER || DOXYGEN
  22822. /**
  22823. */
  22824. class AudioCDBurner : public ChangeBroadcaster
  22825. {
  22826. public:
  22827. /** Returns a list of available optical drives.
  22828. Use openDevice() to open one of the items from this list.
  22829. */
  22830. static const StringArray findAvailableDevices();
  22831. /** Tries to open one of the optical drives.
  22832. The deviceIndex is an index into the array returned by findAvailableDevices().
  22833. */
  22834. static AudioCDBurner* openDevice (const int deviceIndex);
  22835. /** Destructor. */
  22836. ~AudioCDBurner();
  22837. enum DiskState
  22838. {
  22839. unknown, /**< An error condition, if the device isn't responding. */
  22840. trayOpen, /**< The drive is currently open. Note that a slot-loading drive
  22841. may seem to be permanently open. */
  22842. noDisc, /**< The drive has no disk in it. */
  22843. writableDiskPresent, /**< The drive contains a writeable disk. */
  22844. readOnlyDiskPresent /**< The drive contains a read-only disk. */
  22845. };
  22846. /** Returns the current status of the device.
  22847. To get informed when the drive's status changes, attach a ChangeListener to
  22848. the AudioCDBurner.
  22849. */
  22850. DiskState getDiskState() const;
  22851. /** Returns true if there's a writable disk in the drive. */
  22852. bool isDiskPresent() const;
  22853. /** Sends an eject signal to the drive.
  22854. The eject will happen asynchronously, so you can use getDiskState() and
  22855. waitUntilStateChange() to monitor its progress.
  22856. */
  22857. bool openTray();
  22858. /** Blocks the current thread until the drive's state changes, or until the timeout expires.
  22859. @returns the device's new state
  22860. */
  22861. DiskState waitUntilStateChange (int timeOutMilliseconds);
  22862. /** Returns the set of possible write speeds that the device can handle.
  22863. These are as a multiple of 'normal' speed, so e.g. '24x' returns 24, etc.
  22864. Note that if there's no media present in the drive, this value may be unavailable!
  22865. @see setWriteSpeed, getWriteSpeed
  22866. */
  22867. const Array<int> getAvailableWriteSpeeds() const;
  22868. /** Tries to enable or disable buffer underrun safety on devices that support it.
  22869. @returns true if it's now enabled. If the device doesn't support it, this
  22870. will always return false.
  22871. */
  22872. bool setBufferUnderrunProtection (const bool shouldBeEnabled);
  22873. /** Returns the number of free blocks on the disk.
  22874. There are 75 blocks per second, at 44100Hz.
  22875. */
  22876. int getNumAvailableAudioBlocks() const;
  22877. /** Adds a track to be written.
  22878. The source passed-in here will be kept by this object, and it will
  22879. be used and deleted at some point in the future, either during the
  22880. burn() method or when this AudioCDBurner object is deleted. Your caller
  22881. method shouldn't keep a reference to it or use it again after passing
  22882. it in here.
  22883. */
  22884. bool addAudioTrack (AudioSource* source, int numSamples);
  22885. /** Receives progress callbacks during a cd-burn operation.
  22886. @see AudioCDBurner::burn()
  22887. */
  22888. class BurnProgressListener
  22889. {
  22890. public:
  22891. BurnProgressListener() throw() {}
  22892. virtual ~BurnProgressListener() {}
  22893. /** Called at intervals to report on the progress of the AudioCDBurner.
  22894. To cancel the burn, return true from this method.
  22895. */
  22896. virtual bool audioCDBurnProgress (float proportionComplete) = 0;
  22897. };
  22898. /** Runs the burn process.
  22899. This method will block until the operation is complete.
  22900. @param listener the object to receive callbacks about progress
  22901. @param ejectDiscAfterwards whether to eject the disk after the burn completes
  22902. @param performFakeBurnForTesting if true, no data will actually be written to the disk
  22903. @param writeSpeed one of the write speeds from getAvailableWriteSpeeds(), or
  22904. 0 or less to mean the fastest speed.
  22905. */
  22906. const String burn (BurnProgressListener* listener,
  22907. bool ejectDiscAfterwards,
  22908. bool performFakeBurnForTesting,
  22909. int writeSpeed);
  22910. /** If a burn operation is currently in progress, this tells it to stop
  22911. as soon as possible.
  22912. It's also possible to stop the burn process by returning true from
  22913. BurnProgressListener::audioCDBurnProgress()
  22914. */
  22915. void abortBurn();
  22916. juce_UseDebuggingNewOperator
  22917. private:
  22918. AudioCDBurner (const int deviceIndex);
  22919. class Pimpl;
  22920. friend class ScopedPointer<Pimpl>;
  22921. ScopedPointer<Pimpl> pimpl;
  22922. };
  22923. #endif
  22924. #endif // __JUCE_AUDIOCDBURNER_JUCEHEADER__
  22925. /*** End of inlined file: juce_AudioCDBurner.h ***/
  22926. #endif
  22927. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22928. /*** Start of inlined file: juce_AudioCDReader.h ***/
  22929. #ifndef __JUCE_AUDIOCDREADER_JUCEHEADER__
  22930. #define __JUCE_AUDIOCDREADER_JUCEHEADER__
  22931. #if JUCE_USE_CDREADER || DOXYGEN
  22932. #if JUCE_MAC
  22933. #endif
  22934. /**
  22935. A type of AudioFormatReader that reads from an audio CD.
  22936. One of these can be used to read a CD as if it's one big audio stream. Use the
  22937. getPositionOfTrackStart() method to find where the individual tracks are
  22938. within the stream.
  22939. @see AudioFormatReader
  22940. */
  22941. class JUCE_API AudioCDReader : public AudioFormatReader
  22942. {
  22943. public:
  22944. /** Returns a list of names of Audio CDs currently available for reading.
  22945. If there's a CD drive but no CD in it, this might return an empty list, or
  22946. possibly a device that can be opened but which has no tracks, depending
  22947. on the platform.
  22948. @see createReaderForCD
  22949. */
  22950. static const StringArray getAvailableCDNames();
  22951. /** Tries to create an AudioFormatReader that can read from an Audio CD.
  22952. @param index the index of one of the available CDs - use getAvailableCDNames()
  22953. to find out how many there are.
  22954. @returns a new AudioCDReader object, or 0 if it couldn't be created. The
  22955. caller will be responsible for deleting the object returned.
  22956. */
  22957. static AudioCDReader* createReaderForCD (const int index);
  22958. /** Destructor. */
  22959. ~AudioCDReader();
  22960. /** Implementation of the AudioFormatReader method. */
  22961. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  22962. int64 startSampleInFile, int numSamples);
  22963. /** Checks whether the CD has been removed from the drive.
  22964. */
  22965. bool isCDStillPresent() const;
  22966. /** Returns the total number of tracks (audio + data).
  22967. */
  22968. int getNumTracks() const;
  22969. /** Finds the sample offset of the start of a track.
  22970. @param trackNum the track number, where 0 is the first track.
  22971. */
  22972. int getPositionOfTrackStart (int trackNum) const;
  22973. /** Returns true if a given track is an audio track.
  22974. @param trackNum the track number, where 0 is the first track.
  22975. */
  22976. bool isTrackAudio (int trackNum) const;
  22977. /** Refreshes the object's table of contents.
  22978. If the disc has been ejected and a different one put in since this
  22979. object was created, this will cause it to update its idea of how many tracks
  22980. there are, etc.
  22981. */
  22982. void refreshTrackLengths();
  22983. /** Enables scanning for indexes within tracks.
  22984. @see getLastIndex
  22985. */
  22986. void enableIndexScanning (bool enabled);
  22987. /** Returns the index number found during the last read() call.
  22988. Index scanning is turned off by default - turn it on with enableIndexScanning().
  22989. Then when the read() method is called, if it comes across an index within that
  22990. block, the index number is stored and returned by this method.
  22991. Some devices might not support indexes, of course.
  22992. (If you don't know what CD indexes are, it's unlikely you'll ever need them).
  22993. @see enableIndexScanning
  22994. */
  22995. int getLastIndex() const;
  22996. /** Scans a track to find the position of any indexes within it.
  22997. @param trackNumber the track to look in, where 0 is the first track on the disc
  22998. @returns an array of sample positions of any index points found (not including
  22999. the index that marks the start of the track)
  23000. */
  23001. const Array <int> findIndexesInTrack (const int trackNumber);
  23002. /** Returns the CDDB id number for the CD.
  23003. It's not a great way of identifying a disc, but it's traditional.
  23004. */
  23005. int getCDDBId();
  23006. /** Tries to eject the disk.
  23007. Of course this might not be possible, if some other process is using it.
  23008. */
  23009. void ejectDisk();
  23010. juce_UseDebuggingNewOperator
  23011. private:
  23012. #if JUCE_MAC
  23013. File volumeDir;
  23014. Array<File> tracks;
  23015. Array<int> trackStartSamples;
  23016. int currentReaderTrack;
  23017. ScopedPointer <AudioFormatReader> reader;
  23018. AudioCDReader (const File& volume);
  23019. public:
  23020. static int compareElements (const File&, const File&);
  23021. private:
  23022. #elif JUCE_WINDOWS
  23023. int numTracks;
  23024. int trackStarts[100];
  23025. bool audioTracks [100];
  23026. void* handle;
  23027. bool indexingEnabled;
  23028. int lastIndex, firstFrameInBuffer, samplesInBuffer;
  23029. MemoryBlock buffer;
  23030. AudioCDReader (void* handle);
  23031. int getIndexAt (int samplePos);
  23032. #elif JUCE_LINUX
  23033. AudioCDReader();
  23034. #endif
  23035. AudioCDReader (const AudioCDReader&);
  23036. AudioCDReader& operator= (const AudioCDReader&);
  23037. };
  23038. #endif
  23039. #endif // __JUCE_AUDIOCDREADER_JUCEHEADER__
  23040. /*** End of inlined file: juce_AudioCDReader.h ***/
  23041. #endif
  23042. #ifndef __JUCE_AUDIOFORMAT_JUCEHEADER__
  23043. #endif
  23044. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23045. /*** Start of inlined file: juce_AudioFormatManager.h ***/
  23046. #ifndef __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23047. #define __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23048. /**
  23049. A class for keeping a list of available audio formats, and for deciding which
  23050. one to use to open a given file.
  23051. You can either use this class as a singleton object, or create instances of it
  23052. yourself. Once created, use its registerFormat() method to tell it which
  23053. formats it should use.
  23054. @see AudioFormat
  23055. */
  23056. class JUCE_API AudioFormatManager
  23057. {
  23058. public:
  23059. /** Creates an empty format manager.
  23060. Before it'll be any use, you'll need to call registerFormat() with all the
  23061. formats you want it to be able to recognise.
  23062. */
  23063. AudioFormatManager();
  23064. /** Destructor. */
  23065. ~AudioFormatManager();
  23066. juce_DeclareSingleton (AudioFormatManager, false);
  23067. /** Adds a format to the manager's list of available file types.
  23068. The object passed-in will be deleted by this object, so don't keep a pointer
  23069. to it!
  23070. If makeThisTheDefaultFormat is true, then the getDefaultFormat() method will
  23071. return this one when called.
  23072. */
  23073. void registerFormat (AudioFormat* newFormat,
  23074. bool makeThisTheDefaultFormat);
  23075. /** Handy method to make it easy to register the formats that come with Juce.
  23076. Currently, this will add WAV and AIFF to the list.
  23077. */
  23078. void registerBasicFormats();
  23079. /** Clears the list of known formats. */
  23080. void clearFormats();
  23081. /** Returns the number of currently registered file formats. */
  23082. int getNumKnownFormats() const;
  23083. /** Returns one of the registered file formats. */
  23084. AudioFormat* getKnownFormat (int index) const;
  23085. /** Looks for which of the known formats is listed as being for a given file
  23086. extension.
  23087. The extension may have a dot before it, so e.g. ".wav" or "wav" are both ok.
  23088. */
  23089. AudioFormat* findFormatForFileExtension (const String& fileExtension) const;
  23090. /** Returns the format which has been set as the default one.
  23091. You can set a format as being the default when it is registered. It's useful
  23092. when you want to write to a file, because the best format may change between
  23093. platforms, e.g. AIFF is preferred on the Mac, WAV on Windows.
  23094. If none has been set as the default, this method will just return the first
  23095. one in the list.
  23096. */
  23097. AudioFormat* getDefaultFormat() const;
  23098. /** Returns a set of wildcards for file-matching that contains the extensions for
  23099. all known formats.
  23100. E.g. if might return "*.wav;*.aiff" if it just knows about wavs and aiffs.
  23101. */
  23102. const String getWildcardForAllFormats() const;
  23103. /** Searches through the known formats to try to create a suitable reader for
  23104. this file.
  23105. If none of the registered formats can open the file, it'll return 0. If it
  23106. returns a reader, it's the caller's responsibility to delete the reader.
  23107. */
  23108. AudioFormatReader* createReaderFor (const File& audioFile);
  23109. /** Searches through the known formats to try to create a suitable reader for
  23110. this stream.
  23111. The stream object that is passed-in will be deleted by this method or by the
  23112. reader that is returned, so the caller should not keep any references to it.
  23113. The stream that is passed-in must be capable of being repositioned so
  23114. that all the formats can have a go at opening it.
  23115. If none of the registered formats can open the stream, it'll return 0. If it
  23116. returns a reader, it's the caller's responsibility to delete the reader.
  23117. */
  23118. AudioFormatReader* createReaderFor (InputStream* audioFileStream);
  23119. juce_UseDebuggingNewOperator
  23120. private:
  23121. OwnedArray<AudioFormat> knownFormats;
  23122. int defaultFormatIndex;
  23123. };
  23124. #endif // __JUCE_AUDIOFORMATMANAGER_JUCEHEADER__
  23125. /*** End of inlined file: juce_AudioFormatManager.h ***/
  23126. #endif
  23127. #ifndef __JUCE_AUDIOFORMATREADER_JUCEHEADER__
  23128. #endif
  23129. #ifndef __JUCE_AUDIOFORMATWRITER_JUCEHEADER__
  23130. #endif
  23131. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23132. /*** Start of inlined file: juce_AudioSubsectionReader.h ***/
  23133. #ifndef __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23134. #define __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23135. /**
  23136. This class is used to wrap an AudioFormatReader and only read from a
  23137. subsection of the file.
  23138. So if you have a reader which can read a 1000 sample file, you could wrap it
  23139. in one of these to only access, e.g. samples 100 to 200, and any samples
  23140. outside that will come back as 0. Accessing sample 0 from this reader will
  23141. actually read the first sample from the other's subsection, which might
  23142. be at a non-zero position.
  23143. @see AudioFormatReader
  23144. */
  23145. class JUCE_API AudioSubsectionReader : public AudioFormatReader
  23146. {
  23147. public:
  23148. /** Creates a AudioSubsectionReader for a given data source.
  23149. @param sourceReader the source reader from which we'll be taking data
  23150. @param subsectionStartSample the sample within the source reader which will be
  23151. mapped onto sample 0 for this reader.
  23152. @param subsectionLength the number of samples from the source that will
  23153. make up the subsection. If this reader is asked for
  23154. any samples beyond this region, it will return zero.
  23155. @param deleteSourceWhenDeleted if true, the sourceReader object will be deleted when
  23156. this object is deleted.
  23157. */
  23158. AudioSubsectionReader (AudioFormatReader* sourceReader,
  23159. int64 subsectionStartSample,
  23160. int64 subsectionLength,
  23161. bool deleteSourceWhenDeleted);
  23162. /** Destructor. */
  23163. ~AudioSubsectionReader();
  23164. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  23165. int64 startSampleInFile, int numSamples);
  23166. void readMaxLevels (int64 startSample,
  23167. int64 numSamples,
  23168. float& lowestLeft,
  23169. float& highestLeft,
  23170. float& lowestRight,
  23171. float& highestRight);
  23172. juce_UseDebuggingNewOperator
  23173. private:
  23174. AudioFormatReader* const source;
  23175. int64 startSample, length;
  23176. const bool deleteSourceWhenDeleted;
  23177. AudioSubsectionReader (const AudioSubsectionReader&);
  23178. AudioSubsectionReader& operator= (const AudioSubsectionReader&);
  23179. };
  23180. #endif // __JUCE_AUDIOSUBSECTIONREADER_JUCEHEADER__
  23181. /*** End of inlined file: juce_AudioSubsectionReader.h ***/
  23182. #endif
  23183. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23184. /*** Start of inlined file: juce_AudioThumbnail.h ***/
  23185. #ifndef __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23186. #define __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23187. class AudioThumbnailCache;
  23188. /**
  23189. Makes it easy to quickly draw scaled views of the waveform shape of an
  23190. audio file.
  23191. To use this class, just create an AudioThumbNail class for the file you want
  23192. to draw, call setSource to tell it which file or resource to use, then call
  23193. drawChannel() to draw it.
  23194. The class will asynchronously scan the wavefile to create its scaled-down view,
  23195. so you should make your UI repaint itself as this data comes in. To do this, the
  23196. AudioThumbnail is a ChangeBroadcaster, and will broadcast a message when its
  23197. listeners should repaint themselves.
  23198. The thumbnail stores an internal low-res version of the wave data, and this can
  23199. be loaded and saved to avoid having to scan the file again.
  23200. @see AudioThumbnailCache
  23201. */
  23202. class JUCE_API AudioThumbnail : public ChangeBroadcaster,
  23203. public TimeSliceClient,
  23204. private Timer
  23205. {
  23206. public:
  23207. /** Creates an audio thumbnail.
  23208. @param sourceSamplesPerThumbnailSample when creating a stored, low-res version
  23209. of the audio data, this is the scale at which it should be done. (This
  23210. number is the number of original samples that will be averaged for each
  23211. low-res sample)
  23212. @param formatManagerToUse the audio format manager that is used to open the file
  23213. @param cacheToUse an instance of an AudioThumbnailCache - this provides a background
  23214. thread and storage that is used to by the thumbnail, and the cache
  23215. object can be shared between multiple thumbnails
  23216. */
  23217. AudioThumbnail (int sourceSamplesPerThumbnailSample,
  23218. AudioFormatManager& formatManagerToUse,
  23219. AudioThumbnailCache& cacheToUse);
  23220. /** Destructor. */
  23221. ~AudioThumbnail();
  23222. /** Specifies the file or stream that contains the audio file.
  23223. For a file, just call
  23224. @code
  23225. setSource (new FileInputSource (file))
  23226. @endcode
  23227. You can pass a zero in here to clear the thumbnail.
  23228. The source that is passed in will be deleted by this object when it is no
  23229. longer needed
  23230. */
  23231. void setSource (InputSource* newSource);
  23232. /** Reloads the low res thumbnail data from an input stream.
  23233. The thumb will automatically attempt to reload itself from its
  23234. AudioThumbnailCache.
  23235. */
  23236. void loadFrom (InputStream& input);
  23237. /** Saves the low res thumbnail data to an output stream.
  23238. The thumb will automatically attempt to save itself to its
  23239. AudioThumbnailCache after it finishes scanning the wave file.
  23240. */
  23241. void saveTo (OutputStream& output) const;
  23242. /** Returns the number of channels in the file.
  23243. */
  23244. int getNumChannels() const throw();
  23245. /** Returns the length of the audio file, in seconds.
  23246. */
  23247. double getTotalLength() const throw();
  23248. /** Renders the waveform shape for a channel.
  23249. The waveform will be drawn within the specified rectangle, where startTime
  23250. and endTime specify the times within the audio file that should be positioned
  23251. at the left and right edges of the rectangle.
  23252. The waveform will be scaled vertically so that a full-volume sample will fill
  23253. the rectangle vertically, but you can also specify an extra vertical scale factor
  23254. with the verticalZoomFactor parameter.
  23255. */
  23256. void drawChannel (Graphics& g,
  23257. int x, int y, int w, int h,
  23258. double startTimeSeconds,
  23259. double endTimeSeconds,
  23260. int channelNum,
  23261. float verticalZoomFactor);
  23262. /** Returns true if the low res preview is fully generated.
  23263. */
  23264. bool isFullyLoaded() const throw();
  23265. /** @internal */
  23266. bool useTimeSlice();
  23267. /** @internal */
  23268. void timerCallback();
  23269. juce_UseDebuggingNewOperator
  23270. private:
  23271. AudioFormatManager& formatManagerToUse;
  23272. AudioThumbnailCache& cache;
  23273. ScopedPointer <InputSource> source;
  23274. CriticalSection readerLock;
  23275. ScopedPointer <AudioFormatReader> reader;
  23276. MemoryBlock data, cachedLevels;
  23277. int orginalSamplesPerThumbnailSample;
  23278. int numChannelsCached, numSamplesCached;
  23279. double cachedStart, cachedTimePerPixel;
  23280. bool cacheNeedsRefilling;
  23281. void clear();
  23282. AudioFormatReader* createReader() const;
  23283. void generateSection (AudioFormatReader& reader, int64 startSample, int numSamples);
  23284. char* getChannelData (int channel) const;
  23285. void refillCache (int numSamples, double startTime, double timePerPixel);
  23286. friend class AudioThumbnailCache;
  23287. // true if it needs more callbacks from the readNextBlockFromAudioFile() method
  23288. bool initialiseFromAudioFile (AudioFormatReader& reader);
  23289. // returns true if more needs to be read
  23290. bool readNextBlockFromAudioFile (AudioFormatReader& reader);
  23291. };
  23292. #endif // __JUCE_AUDIOTHUMBNAIL_JUCEHEADER__
  23293. /*** End of inlined file: juce_AudioThumbnail.h ***/
  23294. #endif
  23295. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23296. /*** Start of inlined file: juce_AudioThumbnailCache.h ***/
  23297. #ifndef __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23298. #define __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23299. struct ThumbnailCacheEntry;
  23300. /**
  23301. An instance of this class is used to manage multiple AudioThumbnail objects.
  23302. The cache runs a single background thread that is shared by all the thumbnails
  23303. that need it, and it maintains a set of low-res previews in memory, to avoid
  23304. having to re-scan audio files too often.
  23305. @see AudioThumbnail
  23306. */
  23307. class JUCE_API AudioThumbnailCache : public TimeSliceThread
  23308. {
  23309. public:
  23310. /** Creates a cache object.
  23311. The maxNumThumbsToStore parameter lets you specify how many previews should
  23312. be kept in memory at once.
  23313. */
  23314. explicit AudioThumbnailCache (int maxNumThumbsToStore);
  23315. /** Destructor. */
  23316. ~AudioThumbnailCache();
  23317. /** Clears out any stored thumbnails.
  23318. */
  23319. void clear();
  23320. /** Reloads the specified thumb if this cache contains the appropriate stored
  23321. data.
  23322. This is called automatically by the AudioThumbnail class, so you shouldn't
  23323. normally need to call it directly.
  23324. */
  23325. bool loadThumb (AudioThumbnail& thumb, int64 hashCode);
  23326. /** Stores the cachable data from the specified thumb in this cache.
  23327. This is called automatically by the AudioThumbnail class, so you shouldn't
  23328. normally need to call it directly.
  23329. */
  23330. void storeThumb (const AudioThumbnail& thumb, int64 hashCode);
  23331. juce_UseDebuggingNewOperator
  23332. private:
  23333. OwnedArray <ThumbnailCacheEntry> thumbs;
  23334. int maxNumThumbsToStore;
  23335. friend class AudioThumbnail;
  23336. void addThumbnail (AudioThumbnail* thumb);
  23337. void removeThumbnail (AudioThumbnail* thumb);
  23338. };
  23339. #endif // __JUCE_AUDIOTHUMBNAILCACHE_JUCEHEADER__
  23340. /*** End of inlined file: juce_AudioThumbnailCache.h ***/
  23341. #endif
  23342. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23343. /*** Start of inlined file: juce_FlacAudioFormat.h ***/
  23344. #ifndef __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23345. #define __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23346. #if JUCE_USE_FLAC || defined (DOXYGEN)
  23347. /**
  23348. Reads and writes the lossless-compression FLAC audio format.
  23349. To compile this, you'll need to set the JUCE_USE_FLAC flag in juce_Config.h,
  23350. and make sure your include search path and library search path are set up to find
  23351. the FLAC header files and static libraries.
  23352. @see AudioFormat
  23353. */
  23354. class JUCE_API FlacAudioFormat : public AudioFormat
  23355. {
  23356. public:
  23357. FlacAudioFormat();
  23358. ~FlacAudioFormat();
  23359. const Array <int> getPossibleSampleRates();
  23360. const Array <int> getPossibleBitDepths();
  23361. bool canDoStereo();
  23362. bool canDoMono();
  23363. bool isCompressed();
  23364. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23365. const bool deleteStreamIfOpeningFails);
  23366. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23367. double sampleRateToUse,
  23368. unsigned int numberOfChannels,
  23369. int bitsPerSample,
  23370. const StringPairArray& metadataValues,
  23371. int qualityOptionIndex);
  23372. juce_UseDebuggingNewOperator
  23373. };
  23374. #endif
  23375. #endif // __JUCE_FLACAUDIOFORMAT_JUCEHEADER__
  23376. /*** End of inlined file: juce_FlacAudioFormat.h ***/
  23377. #endif
  23378. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23379. /*** Start of inlined file: juce_OggVorbisAudioFormat.h ***/
  23380. #ifndef __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23381. #define __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23382. #if JUCE_USE_OGGVORBIS || defined (DOXYGEN)
  23383. /**
  23384. Reads and writes the Ogg-Vorbis audio format.
  23385. To compile this, you'll need to set the JUCE_USE_OGGVORBIS flag in juce_Config.h,
  23386. and make sure your include search path and library search path are set up to find
  23387. the Vorbis and Ogg header files and static libraries.
  23388. @see AudioFormat,
  23389. */
  23390. class JUCE_API OggVorbisAudioFormat : public AudioFormat
  23391. {
  23392. public:
  23393. OggVorbisAudioFormat();
  23394. ~OggVorbisAudioFormat();
  23395. const Array <int> getPossibleSampleRates();
  23396. const Array <int> getPossibleBitDepths();
  23397. bool canDoStereo();
  23398. bool canDoMono();
  23399. bool isCompressed();
  23400. const StringArray getQualityOptions();
  23401. /** Tries to estimate the quality level of an ogg file based on its size.
  23402. If it can't read the file for some reason, this will just return 1 (medium quality),
  23403. otherwise it will return the approximate quality setting that would have been used
  23404. to create the file.
  23405. @see getQualityOptions
  23406. */
  23407. int estimateOggFileQuality (const File& source);
  23408. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23409. const bool deleteStreamIfOpeningFails);
  23410. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23411. double sampleRateToUse,
  23412. unsigned int numberOfChannels,
  23413. int bitsPerSample,
  23414. const StringPairArray& metadataValues,
  23415. int qualityOptionIndex);
  23416. juce_UseDebuggingNewOperator
  23417. };
  23418. #endif
  23419. #endif // __JUCE_OGGVORBISAUDIOFORMAT_JUCEHEADER__
  23420. /*** End of inlined file: juce_OggVorbisAudioFormat.h ***/
  23421. #endif
  23422. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23423. /*** Start of inlined file: juce_QuickTimeAudioFormat.h ***/
  23424. #ifndef __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23425. #define __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23426. #if JUCE_QUICKTIME
  23427. /**
  23428. Uses QuickTime to read the audio track a movie or media file.
  23429. As well as QuickTime movies, this should also manage to open other audio
  23430. files that quicktime can understand, like mp3, m4a, etc.
  23431. @see AudioFormat
  23432. */
  23433. class JUCE_API QuickTimeAudioFormat : public AudioFormat
  23434. {
  23435. public:
  23436. /** Creates a format object. */
  23437. QuickTimeAudioFormat();
  23438. /** Destructor. */
  23439. ~QuickTimeAudioFormat();
  23440. const Array <int> getPossibleSampleRates();
  23441. const Array <int> getPossibleBitDepths();
  23442. bool canDoStereo();
  23443. bool canDoMono();
  23444. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23445. const bool deleteStreamIfOpeningFails);
  23446. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23447. double sampleRateToUse,
  23448. unsigned int numberOfChannels,
  23449. int bitsPerSample,
  23450. const StringPairArray& metadataValues,
  23451. int qualityOptionIndex);
  23452. juce_UseDebuggingNewOperator
  23453. };
  23454. #endif
  23455. #endif // __JUCE_QUICKTIMEAUDIOFORMAT_JUCEHEADER__
  23456. /*** End of inlined file: juce_QuickTimeAudioFormat.h ***/
  23457. #endif
  23458. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23459. /*** Start of inlined file: juce_WavAudioFormat.h ***/
  23460. #ifndef __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23461. #define __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23462. /**
  23463. Reads and Writes WAV format audio files.
  23464. @see AudioFormat
  23465. */
  23466. class JUCE_API WavAudioFormat : public AudioFormat
  23467. {
  23468. public:
  23469. /** Creates a format object. */
  23470. WavAudioFormat();
  23471. /** Destructor. */
  23472. ~WavAudioFormat();
  23473. /** Metadata property name used by wav readers and writers for adding
  23474. a BWAV chunk to the file.
  23475. @see AudioFormatReader::metadataValues, createWriterFor
  23476. */
  23477. static const char* const bwavDescription;
  23478. /** Metadata property name used by wav readers and writers for adding
  23479. a BWAV chunk to the file.
  23480. @see AudioFormatReader::metadataValues, createWriterFor
  23481. */
  23482. static const char* const bwavOriginator;
  23483. /** Metadata property name used by wav readers and writers for adding
  23484. a BWAV chunk to the file.
  23485. @see AudioFormatReader::metadataValues, createWriterFor
  23486. */
  23487. static const char* const bwavOriginatorRef;
  23488. /** Metadata property name used by wav readers and writers for adding
  23489. a BWAV chunk to the file.
  23490. Date format is: yyyy-mm-dd
  23491. @see AudioFormatReader::metadataValues, createWriterFor
  23492. */
  23493. static const char* const bwavOriginationDate;
  23494. /** Metadata property name used by wav readers and writers for adding
  23495. a BWAV chunk to the file.
  23496. Time format is: hh-mm-ss
  23497. @see AudioFormatReader::metadataValues, createWriterFor
  23498. */
  23499. static const char* const bwavOriginationTime;
  23500. /** Metadata property name used by wav readers and writers for adding
  23501. a BWAV chunk to the file.
  23502. This is the number of samples from the start of an edit that the
  23503. file is supposed to begin at. Seems like an obvious mistake to
  23504. only allow a file to occur in an edit once, but that's the way
  23505. it is..
  23506. @see AudioFormatReader::metadataValues, createWriterFor
  23507. */
  23508. static const char* const bwavTimeReference;
  23509. /** Metadata property name used by wav readers and writers for adding
  23510. a BWAV chunk to the file.
  23511. This is a
  23512. @see AudioFormatReader::metadataValues, createWriterFor
  23513. */
  23514. static const char* const bwavCodingHistory;
  23515. /** Utility function to fill out the appropriate metadata for a BWAV file.
  23516. This just makes it easier than using the property names directly, and it
  23517. fills out the time and date in the right format.
  23518. */
  23519. static const StringPairArray createBWAVMetadata (const String& description,
  23520. const String& originator,
  23521. const String& originatorRef,
  23522. const Time& dateAndTime,
  23523. const int64 timeReferenceSamples,
  23524. const String& codingHistory);
  23525. const Array <int> getPossibleSampleRates();
  23526. const Array <int> getPossibleBitDepths();
  23527. bool canDoStereo();
  23528. bool canDoMono();
  23529. AudioFormatReader* createReaderFor (InputStream* sourceStream,
  23530. const bool deleteStreamIfOpeningFails);
  23531. AudioFormatWriter* createWriterFor (OutputStream* streamToWriteTo,
  23532. double sampleRateToUse,
  23533. unsigned int numberOfChannels,
  23534. int bitsPerSample,
  23535. const StringPairArray& metadataValues,
  23536. int qualityOptionIndex);
  23537. /** Utility function to replace the metadata in a wav file with a new set of values.
  23538. If possible, this cheats by overwriting just the metadata region of the file, rather
  23539. than by copying the whole file again.
  23540. */
  23541. bool replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata);
  23542. juce_UseDebuggingNewOperator
  23543. };
  23544. #endif // __JUCE_WAVAUDIOFORMAT_JUCEHEADER__
  23545. /*** End of inlined file: juce_WavAudioFormat.h ***/
  23546. #endif
  23547. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23548. /*** Start of inlined file: juce_AudioFormatReaderSource.h ***/
  23549. #ifndef __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23550. #define __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23551. /*** Start of inlined file: juce_PositionableAudioSource.h ***/
  23552. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23553. #define __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23554. /**
  23555. A type of AudioSource which can be repositioned.
  23556. The basic AudioSource just streams continuously with no idea of a current
  23557. time or length, so the PositionableAudioSource is used for a finite stream
  23558. that has a current read position.
  23559. @see AudioSource, AudioTransportSource
  23560. */
  23561. class JUCE_API PositionableAudioSource : public AudioSource
  23562. {
  23563. protected:
  23564. /** Creates the PositionableAudioSource. */
  23565. PositionableAudioSource() throw() {}
  23566. public:
  23567. /** Destructor */
  23568. ~PositionableAudioSource() {}
  23569. /** Tells the stream to move to a new position.
  23570. Calling this indicates that the next call to AudioSource::getNextAudioBlock()
  23571. should return samples from this position.
  23572. Note that this may be called on a different thread to getNextAudioBlock(),
  23573. so the subclass should make sure it's synchronised.
  23574. */
  23575. virtual void setNextReadPosition (int newPosition) = 0;
  23576. /** Returns the position from which the next block will be returned.
  23577. @see setNextReadPosition
  23578. */
  23579. virtual int getNextReadPosition() const = 0;
  23580. /** Returns the total length of the stream (in samples). */
  23581. virtual int getTotalLength() const = 0;
  23582. /** Returns true if this source is actually playing in a loop. */
  23583. virtual bool isLooping() const = 0;
  23584. };
  23585. #endif // __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  23586. /*** End of inlined file: juce_PositionableAudioSource.h ***/
  23587. /**
  23588. A type of AudioSource that will read from an AudioFormatReader.
  23589. @see PositionableAudioSource, AudioTransportSource, BufferingAudioSource
  23590. */
  23591. class JUCE_API AudioFormatReaderSource : public PositionableAudioSource
  23592. {
  23593. public:
  23594. /** Creates an AudioFormatReaderSource for a given reader.
  23595. @param sourceReader the reader to use as the data source
  23596. @param deleteReaderWhenThisIsDeleted if true, the reader passed-in will be deleted
  23597. when this object is deleted; if false it will be
  23598. left up to the caller to manage its lifetime
  23599. */
  23600. AudioFormatReaderSource (AudioFormatReader* const sourceReader,
  23601. const bool deleteReaderWhenThisIsDeleted);
  23602. /** Destructor. */
  23603. ~AudioFormatReaderSource();
  23604. /** Toggles loop-mode.
  23605. If set to true, it will continuously loop the input source. If false,
  23606. it will just emit silence after the source has finished.
  23607. @see isLooping
  23608. */
  23609. void setLooping (const bool shouldLoop) throw();
  23610. /** Returns whether loop-mode is turned on or not. */
  23611. bool isLooping() const { return looping; }
  23612. /** Returns the reader that's being used. */
  23613. AudioFormatReader* getAudioFormatReader() const throw() { return reader; }
  23614. /** Implementation of the AudioSource method. */
  23615. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23616. /** Implementation of the AudioSource method. */
  23617. void releaseResources();
  23618. /** Implementation of the AudioSource method. */
  23619. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23620. /** Implements the PositionableAudioSource method. */
  23621. void setNextReadPosition (int newPosition);
  23622. /** Implements the PositionableAudioSource method. */
  23623. int getNextReadPosition() const;
  23624. /** Implements the PositionableAudioSource method. */
  23625. int getTotalLength() const;
  23626. juce_UseDebuggingNewOperator
  23627. private:
  23628. AudioFormatReader* reader;
  23629. bool deleteReader;
  23630. int volatile nextPlayPos;
  23631. bool volatile looping;
  23632. void readBufferSection (int start, int length, AudioSampleBuffer& buffer, int startSample);
  23633. AudioFormatReaderSource (const AudioFormatReaderSource&);
  23634. AudioFormatReaderSource& operator= (const AudioFormatReaderSource&);
  23635. };
  23636. #endif // __JUCE_AUDIOFORMATREADERSOURCE_JUCEHEADER__
  23637. /*** End of inlined file: juce_AudioFormatReaderSource.h ***/
  23638. #endif
  23639. #ifndef __JUCE_AUDIOSOURCE_JUCEHEADER__
  23640. #endif
  23641. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23642. /*** Start of inlined file: juce_AudioSourcePlayer.h ***/
  23643. #ifndef __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23644. #define __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23645. /*** Start of inlined file: juce_AudioIODevice.h ***/
  23646. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23647. #define __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23648. class AudioIODevice;
  23649. /**
  23650. One of these is passed to an AudioIODevice object to stream the audio data
  23651. in and out.
  23652. The AudioIODevice will repeatedly call this class's audioDeviceIOCallback()
  23653. method on its own high-priority audio thread, when it needs to send or receive
  23654. the next block of data.
  23655. @see AudioIODevice, AudioDeviceManager
  23656. */
  23657. class JUCE_API AudioIODeviceCallback
  23658. {
  23659. public:
  23660. /** Destructor. */
  23661. virtual ~AudioIODeviceCallback() {}
  23662. /** Processes a block of incoming and outgoing audio data.
  23663. The subclass's implementation should use the incoming audio for whatever
  23664. purposes it needs to, and must fill all the output channels with the next
  23665. block of output data before returning.
  23666. The channel data is arranged with the same array indices as the channel name
  23667. array returned by AudioIODevice::getOutputChannelNames(), but those channels
  23668. that aren't specified in AudioIODevice::open() will have a null pointer for their
  23669. associated channel, so remember to check for this.
  23670. @param inputChannelData a set of arrays containing the audio data for each
  23671. incoming channel - this data is valid until the function
  23672. returns. There will be one channel of data for each input
  23673. channel that was enabled when the audio device was opened
  23674. (see AudioIODevice::open())
  23675. @param numInputChannels the number of pointers to channel data in the
  23676. inputChannelData array.
  23677. @param outputChannelData a set of arrays which need to be filled with the data
  23678. that should be sent to each outgoing channel of the device.
  23679. There will be one channel of data for each output channel
  23680. that was enabled when the audio device was opened (see
  23681. AudioIODevice::open())
  23682. The initial contents of the array is undefined, so the
  23683. callback function must fill all the channels with zeros if
  23684. its output is silence. Failing to do this could cause quite
  23685. an unpleasant noise!
  23686. @param numOutputChannels the number of pointers to channel data in the
  23687. outputChannelData array.
  23688. @param numSamples the number of samples in each channel of the input and
  23689. output arrays. The number of samples will depend on the
  23690. audio device's buffer size and will usually remain constant,
  23691. although this isn't guaranteed, so make sure your code can
  23692. cope with reasonable changes in the buffer size from one
  23693. callback to the next.
  23694. */
  23695. virtual void audioDeviceIOCallback (const float** inputChannelData,
  23696. int numInputChannels,
  23697. float** outputChannelData,
  23698. int numOutputChannels,
  23699. int numSamples) = 0;
  23700. /** Called to indicate that the device is about to start calling back.
  23701. This will be called just before the audio callbacks begin, either when this
  23702. callback has just been added to an audio device, or after the device has been
  23703. restarted because of a sample-rate or block-size change.
  23704. You can use this opportunity to find out the sample rate and block size
  23705. that the device is going to use by calling the AudioIODevice::getCurrentSampleRate()
  23706. and AudioIODevice::getCurrentBufferSizeSamples() on the supplied pointer.
  23707. @param device the audio IO device that will be used to drive the callback.
  23708. Note that if you're going to store this this pointer, it is
  23709. only valid until the next time that audioDeviceStopped is called.
  23710. */
  23711. virtual void audioDeviceAboutToStart (AudioIODevice* device) = 0;
  23712. /** Called to indicate that the device has stopped.
  23713. */
  23714. virtual void audioDeviceStopped() = 0;
  23715. };
  23716. /**
  23717. Base class for an audio device with synchronised input and output channels.
  23718. Subclasses of this are used to implement different protocols such as DirectSound,
  23719. ASIO, CoreAudio, etc.
  23720. To create one of these, you'll need to use the AudioIODeviceType class - see the
  23721. documentation for that class for more info.
  23722. For an easier way of managing audio devices and their settings, have a look at the
  23723. AudioDeviceManager class.
  23724. @see AudioIODeviceType, AudioDeviceManager
  23725. */
  23726. class JUCE_API AudioIODevice
  23727. {
  23728. public:
  23729. /** Destructor. */
  23730. virtual ~AudioIODevice();
  23731. /** Returns the device's name, (as set in the constructor). */
  23732. const String& getName() const throw() { return name; }
  23733. /** Returns the type of the device.
  23734. E.g. "CoreAudio", "ASIO", etc. - this comes from the AudioIODeviceType that created it.
  23735. */
  23736. const String& getTypeName() const throw() { return typeName; }
  23737. /** Returns the names of all the available output channels on this device.
  23738. To find out which of these are currently in use, call getActiveOutputChannels().
  23739. */
  23740. virtual const StringArray getOutputChannelNames() = 0;
  23741. /** Returns the names of all the available input channels on this device.
  23742. To find out which of these are currently in use, call getActiveInputChannels().
  23743. */
  23744. virtual const StringArray getInputChannelNames() = 0;
  23745. /** Returns the number of sample-rates this device supports.
  23746. To find out which rates are available on this device, use this method to
  23747. find out how many there are, and getSampleRate() to get the rates.
  23748. @see getSampleRate
  23749. */
  23750. virtual int getNumSampleRates() = 0;
  23751. /** Returns one of the sample-rates this device supports.
  23752. To find out which rates are available on this device, use getNumSampleRates() to
  23753. find out how many there are, and getSampleRate() to get the individual rates.
  23754. The sample rate is set by the open() method.
  23755. (Note that for DirectSound some rates might not work, depending on combinations
  23756. of i/o channels that are being opened).
  23757. @see getNumSampleRates
  23758. */
  23759. virtual double getSampleRate (int index) = 0;
  23760. /** Returns the number of sizes of buffer that are available.
  23761. @see getBufferSizeSamples, getDefaultBufferSize
  23762. */
  23763. virtual int getNumBufferSizesAvailable() = 0;
  23764. /** Returns one of the possible buffer-sizes.
  23765. @param index the index of the buffer-size to use, from 0 to getNumBufferSizesAvailable() - 1
  23766. @returns a number of samples
  23767. @see getNumBufferSizesAvailable, getDefaultBufferSize
  23768. */
  23769. virtual int getBufferSizeSamples (int index) = 0;
  23770. /** Returns the default buffer-size to use.
  23771. @returns a number of samples
  23772. @see getNumBufferSizesAvailable, getBufferSizeSamples
  23773. */
  23774. virtual int getDefaultBufferSize() = 0;
  23775. /** Tries to open the device ready to play.
  23776. @param inputChannels a BigInteger in which a set bit indicates that the corresponding
  23777. input channel should be enabled
  23778. @param outputChannels a BigInteger in which a set bit indicates that the corresponding
  23779. output channel should be enabled
  23780. @param sampleRate the sample rate to try to use - to find out which rates are
  23781. available, see getNumSampleRates() and getSampleRate()
  23782. @param bufferSizeSamples the size of i/o buffer to use - to find out the available buffer
  23783. sizes, see getNumBufferSizesAvailable() and getBufferSizeSamples()
  23784. @returns an error description if there's a problem, or an empty string if it succeeds in
  23785. opening the device
  23786. @see close
  23787. */
  23788. virtual const String open (const BigInteger& inputChannels,
  23789. const BigInteger& outputChannels,
  23790. double sampleRate,
  23791. int bufferSizeSamples) = 0;
  23792. /** Closes and releases the device if it's open. */
  23793. virtual void close() = 0;
  23794. /** Returns true if the device is still open.
  23795. A device might spontaneously close itself if something goes wrong, so this checks if
  23796. it's still open.
  23797. */
  23798. virtual bool isOpen() = 0;
  23799. /** Starts the device actually playing.
  23800. This must be called after the device has been opened.
  23801. @param callback the callback to use for streaming the data.
  23802. @see AudioIODeviceCallback, open
  23803. */
  23804. virtual void start (AudioIODeviceCallback* callback) = 0;
  23805. /** Stops the device playing.
  23806. Once a device has been started, this will stop it. Any pending calls to the
  23807. callback class will be flushed before this method returns.
  23808. */
  23809. virtual void stop() = 0;
  23810. /** Returns true if the device is still calling back.
  23811. The device might mysteriously stop, so this checks whether it's
  23812. still playing.
  23813. */
  23814. virtual bool isPlaying() = 0;
  23815. /** Returns the last error that happened if anything went wrong. */
  23816. virtual const String getLastError() = 0;
  23817. /** Returns the buffer size that the device is currently using.
  23818. If the device isn't actually open, this value doesn't really mean much.
  23819. */
  23820. virtual int getCurrentBufferSizeSamples() = 0;
  23821. /** Returns the sample rate that the device is currently using.
  23822. If the device isn't actually open, this value doesn't really mean much.
  23823. */
  23824. virtual double getCurrentSampleRate() = 0;
  23825. /** Returns the device's current physical bit-depth.
  23826. If the device isn't actually open, this value doesn't really mean much.
  23827. */
  23828. virtual int getCurrentBitDepth() = 0;
  23829. /** Returns a mask showing which of the available output channels are currently
  23830. enabled.
  23831. @see getOutputChannelNames
  23832. */
  23833. virtual const BigInteger getActiveOutputChannels() const = 0;
  23834. /** Returns a mask showing which of the available input channels are currently
  23835. enabled.
  23836. @see getInputChannelNames
  23837. */
  23838. virtual const BigInteger getActiveInputChannels() const = 0;
  23839. /** Returns the device's output latency.
  23840. This is the delay in samples between a callback getting a block of data, and
  23841. that data actually getting played.
  23842. */
  23843. virtual int getOutputLatencyInSamples() = 0;
  23844. /** Returns the device's input latency.
  23845. This is the delay in samples between some audio actually arriving at the soundcard,
  23846. and the callback getting passed this block of data.
  23847. */
  23848. virtual int getInputLatencyInSamples() = 0;
  23849. /** True if this device can show a pop-up control panel for editing its settings.
  23850. This is generally just true of ASIO devices. If true, you can call showControlPanel()
  23851. to display it.
  23852. */
  23853. virtual bool hasControlPanel() const;
  23854. /** Shows a device-specific control panel if there is one.
  23855. This should only be called for devices which return true from hasControlPanel().
  23856. */
  23857. virtual bool showControlPanel();
  23858. protected:
  23859. /** Creates a device, setting its name and type member variables. */
  23860. AudioIODevice (const String& deviceName,
  23861. const String& typeName);
  23862. /** @internal */
  23863. String name, typeName;
  23864. };
  23865. #endif // __JUCE_AUDIOIODEVICE_JUCEHEADER__
  23866. /*** End of inlined file: juce_AudioIODevice.h ***/
  23867. /**
  23868. Wrapper class to continuously stream audio from an audio source to an
  23869. AudioIODevice.
  23870. This object acts as an AudioIODeviceCallback, so can be attached to an
  23871. output device, and will stream audio from an AudioSource.
  23872. */
  23873. class JUCE_API AudioSourcePlayer : public AudioIODeviceCallback
  23874. {
  23875. public:
  23876. /** Creates an empty AudioSourcePlayer. */
  23877. AudioSourcePlayer();
  23878. /** Destructor.
  23879. Make sure this object isn't still being used by an AudioIODevice before
  23880. deleting it!
  23881. */
  23882. virtual ~AudioSourcePlayer();
  23883. /** Changes the current audio source to play from.
  23884. If the source passed in is already being used, this method will do nothing.
  23885. If the source is not null, its prepareToPlay() method will be called
  23886. before it starts being used for playback.
  23887. If there's another source currently playing, its releaseResources() method
  23888. will be called after it has been swapped for the new one.
  23889. @param newSource the new source to use - this will NOT be deleted
  23890. by this object when no longer needed, so it's the
  23891. caller's responsibility to manage it.
  23892. */
  23893. void setSource (AudioSource* newSource);
  23894. /** Returns the source that's playing.
  23895. May return 0 if there's no source.
  23896. */
  23897. AudioSource* getCurrentSource() const throw() { return source; }
  23898. /** Sets a gain to apply to the audio data.
  23899. @see getGain
  23900. */
  23901. void setGain (const float newGain) throw();
  23902. /** Returns the current gain.
  23903. @see setGain
  23904. */
  23905. float getGain() const throw() { return gain; }
  23906. /** Implementation of the AudioIODeviceCallback method. */
  23907. void audioDeviceIOCallback (const float** inputChannelData,
  23908. int totalNumInputChannels,
  23909. float** outputChannelData,
  23910. int totalNumOutputChannels,
  23911. int numSamples);
  23912. /** Implementation of the AudioIODeviceCallback method. */
  23913. void audioDeviceAboutToStart (AudioIODevice* device);
  23914. /** Implementation of the AudioIODeviceCallback method. */
  23915. void audioDeviceStopped();
  23916. juce_UseDebuggingNewOperator
  23917. private:
  23918. CriticalSection readLock;
  23919. AudioSource* source;
  23920. double sampleRate;
  23921. int bufferSize;
  23922. float* channels [128];
  23923. float* outputChans [128];
  23924. const float* inputChans [128];
  23925. AudioSampleBuffer tempBuffer;
  23926. float lastGain, gain;
  23927. AudioSourcePlayer (const AudioSourcePlayer&);
  23928. AudioSourcePlayer& operator= (const AudioSourcePlayer&);
  23929. };
  23930. #endif // __JUCE_AUDIOSOURCEPLAYER_JUCEHEADER__
  23931. /*** End of inlined file: juce_AudioSourcePlayer.h ***/
  23932. #endif
  23933. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23934. /*** Start of inlined file: juce_AudioTransportSource.h ***/
  23935. #ifndef __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23936. #define __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  23937. /*** Start of inlined file: juce_BufferingAudioSource.h ***/
  23938. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23939. #define __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23940. /**
  23941. An AudioSource which takes another source as input, and buffers it using a thread.
  23942. Create this as a wrapper around another thread, and it will read-ahead with
  23943. a background thread to smooth out playback. You can either create one of these
  23944. directly, or use it indirectly using an AudioTransportSource.
  23945. @see PositionableAudioSource, AudioTransportSource
  23946. */
  23947. class JUCE_API BufferingAudioSource : public PositionableAudioSource
  23948. {
  23949. public:
  23950. /** Creates a BufferingAudioSource.
  23951. @param source the input source to read from
  23952. @param deleteSourceWhenDeleted if true, then the input source object will
  23953. be deleted when this object is deleted
  23954. @param numberOfSamplesToBuffer the size of buffer to use for reading ahead
  23955. */
  23956. BufferingAudioSource (PositionableAudioSource* source,
  23957. const bool deleteSourceWhenDeleted,
  23958. int numberOfSamplesToBuffer);
  23959. /** Destructor.
  23960. The input source may be deleted depending on whether the deleteSourceWhenDeleted
  23961. flag was set in the constructor.
  23962. */
  23963. ~BufferingAudioSource();
  23964. /** Implementation of the AudioSource method. */
  23965. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  23966. /** Implementation of the AudioSource method. */
  23967. void releaseResources();
  23968. /** Implementation of the AudioSource method. */
  23969. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  23970. /** Implements the PositionableAudioSource method. */
  23971. void setNextReadPosition (int newPosition);
  23972. /** Implements the PositionableAudioSource method. */
  23973. int getNextReadPosition() const;
  23974. /** Implements the PositionableAudioSource method. */
  23975. int getTotalLength() const { return source->getTotalLength(); }
  23976. /** Implements the PositionableAudioSource method. */
  23977. bool isLooping() const { return source->isLooping(); }
  23978. juce_UseDebuggingNewOperator
  23979. private:
  23980. PositionableAudioSource* source;
  23981. bool deleteSourceWhenDeleted;
  23982. int numberOfSamplesToBuffer;
  23983. AudioSampleBuffer buffer;
  23984. CriticalSection bufferStartPosLock;
  23985. int volatile bufferValidStart, bufferValidEnd, nextPlayPos;
  23986. bool wasSourceLooping;
  23987. double volatile sampleRate;
  23988. friend class SharedBufferingAudioSourceThread;
  23989. bool readNextBufferChunk();
  23990. void readBufferSection (int start, int length, int bufferOffset);
  23991. BufferingAudioSource (const BufferingAudioSource&);
  23992. BufferingAudioSource& operator= (const BufferingAudioSource&);
  23993. };
  23994. #endif // __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  23995. /*** End of inlined file: juce_BufferingAudioSource.h ***/
  23996. /*** Start of inlined file: juce_ResamplingAudioSource.h ***/
  23997. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23998. #define __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  23999. /**
  24000. A type of AudioSource that takes an input source and changes its sample rate.
  24001. @see AudioSource
  24002. */
  24003. class JUCE_API ResamplingAudioSource : public AudioSource
  24004. {
  24005. public:
  24006. /** Creates a ResamplingAudioSource for a given input source.
  24007. @param inputSource the input source to read from
  24008. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24009. this object is deleted
  24010. @param numChannels the number of channels to process
  24011. */
  24012. ResamplingAudioSource (AudioSource* const inputSource,
  24013. const bool deleteInputWhenDeleted,
  24014. int numChannels = 2);
  24015. /** Destructor. */
  24016. ~ResamplingAudioSource();
  24017. /** Changes the resampling ratio.
  24018. (This value can be changed at any time, even while the source is running).
  24019. @param samplesInPerOutputSample if set to 1.0, the input is passed through; higher
  24020. values will speed it up; lower values will slow it
  24021. down. The ratio must be greater than 0
  24022. */
  24023. void setResamplingRatio (const double samplesInPerOutputSample);
  24024. /** Returns the current resampling ratio.
  24025. This is the value that was set by setResamplingRatio().
  24026. */
  24027. double getResamplingRatio() const throw() { return ratio; }
  24028. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24029. void releaseResources();
  24030. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24031. juce_UseDebuggingNewOperator
  24032. private:
  24033. AudioSource* const input;
  24034. const bool deleteInputWhenDeleted;
  24035. double ratio, lastRatio;
  24036. AudioSampleBuffer buffer;
  24037. int bufferPos, sampsInBuffer;
  24038. double subSampleOffset;
  24039. double coefficients[6];
  24040. CriticalSection ratioLock;
  24041. const int numChannels;
  24042. HeapBlock<float*> destBuffers, srcBuffers;
  24043. void setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6);
  24044. void createLowPass (const double proportionalRate);
  24045. struct FilterState
  24046. {
  24047. double x1, x2, y1, y2;
  24048. };
  24049. HeapBlock<FilterState> filterStates;
  24050. void resetFilters();
  24051. void applyFilter (float* samples, int num, FilterState& fs);
  24052. ResamplingAudioSource (const ResamplingAudioSource&);
  24053. ResamplingAudioSource& operator= (const ResamplingAudioSource&);
  24054. };
  24055. #endif // __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24056. /*** End of inlined file: juce_ResamplingAudioSource.h ***/
  24057. /**
  24058. An AudioSource that takes a PositionableAudioSource and allows it to be
  24059. played, stopped, started, etc.
  24060. This can also be told use a buffer and background thread to read ahead, and
  24061. if can correct for different sample-rates.
  24062. You may want to use one of these along with an AudioSourcePlayer and AudioIODevice
  24063. to control playback of an audio file.
  24064. @see AudioSource, AudioSourcePlayer
  24065. */
  24066. class JUCE_API AudioTransportSource : public PositionableAudioSource,
  24067. public ChangeBroadcaster
  24068. {
  24069. public:
  24070. /** Creates an AudioTransportSource.
  24071. After creating one of these, use the setSource() method to select an input source.
  24072. */
  24073. AudioTransportSource();
  24074. /** Destructor. */
  24075. ~AudioTransportSource();
  24076. /** Sets the reader that is being used as the input source.
  24077. This will stop playback, reset the position to 0 and change to the new reader.
  24078. The source passed in will not be deleted by this object, so must be managed by
  24079. the caller.
  24080. @param newSource the new input source to use. This may be zero
  24081. @param readAheadBufferSize a size of buffer to use for reading ahead. If this
  24082. is zero, no reading ahead will be done; if it's
  24083. greater than zero, a BufferingAudioSource will be used
  24084. to do the reading-ahead
  24085. @param sourceSampleRateToCorrectFor if this is non-zero, it specifies the sample
  24086. rate of the source, and playback will be sample-rate
  24087. adjusted to maintain playback at the correct pitch. If
  24088. this is 0, no sample-rate adjustment will be performed
  24089. */
  24090. void setSource (PositionableAudioSource* const newSource,
  24091. int readAheadBufferSize = 0,
  24092. double sourceSampleRateToCorrectFor = 0.0);
  24093. /** Changes the current playback position in the source stream.
  24094. The next time the getNextAudioBlock() method is called, this
  24095. is the time from which it'll read data.
  24096. @see getPosition
  24097. */
  24098. void setPosition (double newPosition);
  24099. /** Returns the position that the next data block will be read from
  24100. This is a time in seconds.
  24101. */
  24102. double getCurrentPosition() const;
  24103. /** Returns true if the player has stopped because its input stream ran out of data.
  24104. */
  24105. bool hasStreamFinished() const throw() { return inputStreamEOF; }
  24106. /** Starts playing (if a source has been selected).
  24107. If it starts playing, this will send a message to any ChangeListeners
  24108. that are registered with this object.
  24109. */
  24110. void start();
  24111. /** Stops playing.
  24112. If it's actually playing, this will send a message to any ChangeListeners
  24113. that are registered with this object.
  24114. */
  24115. void stop();
  24116. /** Returns true if it's currently playing. */
  24117. bool isPlaying() const throw() { return playing; }
  24118. /** Changes the gain to apply to the output.
  24119. @param newGain a factor by which to multiply the outgoing samples,
  24120. so 1.0 = 0dB, 0.5 = -6dB, 2.0 = 6dB, etc.
  24121. */
  24122. void setGain (const float newGain) throw();
  24123. /** Returns the current gain setting.
  24124. @see setGain
  24125. */
  24126. float getGain() const throw() { return gain; }
  24127. /** Implementation of the AudioSource method. */
  24128. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24129. /** Implementation of the AudioSource method. */
  24130. void releaseResources();
  24131. /** Implementation of the AudioSource method. */
  24132. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24133. /** Implements the PositionableAudioSource method. */
  24134. void setNextReadPosition (int newPosition);
  24135. /** Implements the PositionableAudioSource method. */
  24136. int getNextReadPosition() const;
  24137. /** Implements the PositionableAudioSource method. */
  24138. int getTotalLength() const;
  24139. /** Implements the PositionableAudioSource method. */
  24140. bool isLooping() const;
  24141. juce_UseDebuggingNewOperator
  24142. private:
  24143. PositionableAudioSource* source;
  24144. ResamplingAudioSource* resamplerSource;
  24145. BufferingAudioSource* bufferingSource;
  24146. PositionableAudioSource* positionableSource;
  24147. AudioSource* masterSource;
  24148. CriticalSection callbackLock;
  24149. float volatile gain, lastGain;
  24150. bool volatile playing, stopped;
  24151. double sampleRate, sourceSampleRate;
  24152. int blockSize, readAheadBufferSize;
  24153. bool isPrepared, inputStreamEOF;
  24154. AudioTransportSource (const AudioTransportSource&);
  24155. AudioTransportSource& operator= (const AudioTransportSource&);
  24156. };
  24157. #endif // __JUCE_AUDIOTRANSPORTSOURCE_JUCEHEADER__
  24158. /*** End of inlined file: juce_AudioTransportSource.h ***/
  24159. #endif
  24160. #ifndef __JUCE_BUFFERINGAUDIOSOURCE_JUCEHEADER__
  24161. #endif
  24162. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24163. /*** Start of inlined file: juce_ChannelRemappingAudioSource.h ***/
  24164. #ifndef __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24165. #define __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24166. /**
  24167. An AudioSource that takes the audio from another source, and re-maps its
  24168. input and output channels to a different arrangement.
  24169. You can use this to increase or decrease the number of channels that an
  24170. audio source uses, or to re-order those channels.
  24171. Call the reset() method before using it to set up a default mapping, and then
  24172. the setInputChannelMapping() and setOutputChannelMapping() methods to
  24173. create an appropriate mapping, otherwise no channels will be connected and
  24174. it'll produce silence.
  24175. @see AudioSource
  24176. */
  24177. class ChannelRemappingAudioSource : public AudioSource
  24178. {
  24179. public:
  24180. /** Creates a remapping source that will pass on audio from the given input.
  24181. @param source the input source to use. Make sure that this doesn't
  24182. get deleted before the ChannelRemappingAudioSource object
  24183. @param deleteSourceWhenDeleted if true, the input source will be deleted
  24184. when this object is deleted, if false, the caller is
  24185. responsible for its deletion
  24186. */
  24187. ChannelRemappingAudioSource (AudioSource* const source,
  24188. const bool deleteSourceWhenDeleted);
  24189. /** Destructor. */
  24190. ~ChannelRemappingAudioSource();
  24191. /** Specifies a number of channels that this audio source must produce from its
  24192. getNextAudioBlock() callback.
  24193. */
  24194. void setNumberOfChannelsToProduce (const int requiredNumberOfChannels) throw();
  24195. /** Clears any mapped channels.
  24196. After this, no channels are mapped, so this object will produce silence. Create
  24197. some mappings with setInputChannelMapping() and setOutputChannelMapping().
  24198. */
  24199. void clearAllMappings() throw();
  24200. /** Creates an input channel mapping.
  24201. When the getNextAudioBlock() method is called, the data in channel sourceChannelIndex of the incoming
  24202. data will be sent to destChannelIndex of our input source.
  24203. @param destChannelIndex the index of an input channel in our input audio source (i.e. the
  24204. source specified when this object was created).
  24205. @param sourceChannelIndex the index of the input channel in the incoming audio data buffer
  24206. during our getNextAudioBlock() callback
  24207. */
  24208. void setInputChannelMapping (const int destChannelIndex,
  24209. const int sourceChannelIndex) throw();
  24210. /** Creates an output channel mapping.
  24211. When the getNextAudioBlock() method is called, the data returned in channel sourceChannelIndex by
  24212. our input audio source will be copied to channel destChannelIndex of the final buffer.
  24213. @param sourceChannelIndex the index of an output channel coming from our input audio source
  24214. (i.e. the source specified when this object was created).
  24215. @param destChannelIndex the index of the output channel in the incoming audio data buffer
  24216. during our getNextAudioBlock() callback
  24217. */
  24218. void setOutputChannelMapping (const int sourceChannelIndex,
  24219. const int destChannelIndex) throw();
  24220. /** Returns the channel from our input that will be sent to channel inputChannelIndex of
  24221. our input audio source.
  24222. */
  24223. int getRemappedInputChannel (const int inputChannelIndex) const throw();
  24224. /** Returns the output channel to which channel outputChannelIndex of our input audio
  24225. source will be sent to.
  24226. */
  24227. int getRemappedOutputChannel (const int outputChannelIndex) const throw();
  24228. /** Returns an XML object to encapsulate the state of the mappings.
  24229. @see restoreFromXml
  24230. */
  24231. XmlElement* createXml() const throw();
  24232. /** Restores the mappings from an XML object created by createXML().
  24233. @see createXml
  24234. */
  24235. void restoreFromXml (const XmlElement& e) throw();
  24236. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24237. void releaseResources();
  24238. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24239. juce_UseDebuggingNewOperator
  24240. private:
  24241. int requiredNumberOfChannels;
  24242. Array <int> remappedInputs, remappedOutputs;
  24243. AudioSource* const source;
  24244. const bool deleteSourceWhenDeleted;
  24245. AudioSampleBuffer buffer;
  24246. AudioSourceChannelInfo remappedInfo;
  24247. CriticalSection lock;
  24248. ChannelRemappingAudioSource (const ChannelRemappingAudioSource&);
  24249. ChannelRemappingAudioSource& operator= (const ChannelRemappingAudioSource&);
  24250. };
  24251. #endif // __JUCE_CHANNELREMAPPINGAUDIOSOURCE_JUCEHEADER__
  24252. /*** End of inlined file: juce_ChannelRemappingAudioSource.h ***/
  24253. #endif
  24254. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24255. /*** Start of inlined file: juce_IIRFilterAudioSource.h ***/
  24256. #ifndef __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24257. #define __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24258. /*** Start of inlined file: juce_IIRFilter.h ***/
  24259. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  24260. #define __JUCE_IIRFILTER_JUCEHEADER__
  24261. /**
  24262. An IIR filter that can perform low, high, or band-pass filtering on an
  24263. audio signal.
  24264. @see IIRFilterAudioSource
  24265. */
  24266. class JUCE_API IIRFilter
  24267. {
  24268. public:
  24269. /** Creates a filter.
  24270. Initially the filter is inactive, so will have no effect on samples that
  24271. you process with it. Use the appropriate method to turn it into the type
  24272. of filter needed.
  24273. */
  24274. IIRFilter();
  24275. /** Creates a copy of another filter. */
  24276. IIRFilter (const IIRFilter& other);
  24277. /** Destructor. */
  24278. ~IIRFilter();
  24279. /** Resets the filter's processing pipeline, ready to start a new stream of data.
  24280. Note that this clears the processing state, but the type of filter and
  24281. its coefficients aren't changed. To put a filter into an inactive state, use
  24282. the makeInactive() method.
  24283. */
  24284. void reset() throw();
  24285. /** Performs the filter operation on the given set of samples.
  24286. */
  24287. void processSamples (float* samples,
  24288. int numSamples) throw();
  24289. /** Processes a single sample, without any locking or checking.
  24290. Use this if you need fast processing of a single value, but be aware that
  24291. this isn't thread-safe in the way that processSamples() is.
  24292. */
  24293. float processSingleSampleRaw (float sample) throw();
  24294. /** Sets the filter up to act as a low-pass filter.
  24295. */
  24296. void makeLowPass (double sampleRate,
  24297. double frequency) throw();
  24298. /** Sets the filter up to act as a high-pass filter.
  24299. */
  24300. void makeHighPass (double sampleRate,
  24301. double frequency) throw();
  24302. /** Sets the filter up to act as a low-pass shelf filter with variable Q and gain.
  24303. The gain is a scale factor that the low frequencies are multiplied by, so values
  24304. greater than 1.0 will boost the low frequencies, values less than 1.0 will
  24305. attenuate them.
  24306. */
  24307. void makeLowShelf (double sampleRate,
  24308. double cutOffFrequency,
  24309. double Q,
  24310. float gainFactor) throw();
  24311. /** Sets the filter up to act as a high-pass shelf filter with variable Q and gain.
  24312. The gain is a scale factor that the high frequencies are multiplied by, so values
  24313. greater than 1.0 will boost the high frequencies, values less than 1.0 will
  24314. attenuate them.
  24315. */
  24316. void makeHighShelf (double sampleRate,
  24317. double cutOffFrequency,
  24318. double Q,
  24319. float gainFactor) throw();
  24320. /** Sets the filter up to act as a band pass filter centred around a
  24321. frequency, with a variable Q and gain.
  24322. The gain is a scale factor that the centre frequencies are multiplied by, so
  24323. values greater than 1.0 will boost the centre frequencies, values less than
  24324. 1.0 will attenuate them.
  24325. */
  24326. void makeBandPass (double sampleRate,
  24327. double centreFrequency,
  24328. double Q,
  24329. float gainFactor) throw();
  24330. /** Clears the filter's coefficients so that it becomes inactive.
  24331. */
  24332. void makeInactive() throw();
  24333. /** Makes this filter duplicate the set-up of another one.
  24334. */
  24335. void copyCoefficientsFrom (const IIRFilter& other) throw();
  24336. juce_UseDebuggingNewOperator
  24337. protected:
  24338. CriticalSection processLock;
  24339. void setCoefficients (double c1, double c2, double c3,
  24340. double c4, double c5, double c6) throw();
  24341. bool active;
  24342. float coefficients[6];
  24343. float x1, x2, y1, y2;
  24344. // (use the copyCoefficientsFrom() method instead of this operator)
  24345. IIRFilter& operator= (const IIRFilter&);
  24346. };
  24347. #endif // __JUCE_IIRFILTER_JUCEHEADER__
  24348. /*** End of inlined file: juce_IIRFilter.h ***/
  24349. /**
  24350. An AudioSource that performs an IIR filter on another source.
  24351. */
  24352. class JUCE_API IIRFilterAudioSource : public AudioSource
  24353. {
  24354. public:
  24355. /** Creates a IIRFilterAudioSource for a given input source.
  24356. @param inputSource the input source to read from
  24357. @param deleteInputWhenDeleted if true, the input source will be deleted when
  24358. this object is deleted
  24359. */
  24360. IIRFilterAudioSource (AudioSource* const inputSource,
  24361. const bool deleteInputWhenDeleted);
  24362. /** Destructor. */
  24363. ~IIRFilterAudioSource();
  24364. /** Changes the filter to use the same parameters as the one being passed in.
  24365. */
  24366. void setFilterParameters (const IIRFilter& newSettings);
  24367. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24368. void releaseResources();
  24369. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24370. juce_UseDebuggingNewOperator
  24371. private:
  24372. AudioSource* const input;
  24373. const bool deleteInputWhenDeleted;
  24374. OwnedArray <IIRFilter> iirFilters;
  24375. IIRFilterAudioSource (const IIRFilterAudioSource&);
  24376. IIRFilterAudioSource& operator= (const IIRFilterAudioSource&);
  24377. };
  24378. #endif // __JUCE_IIRFILTERAUDIOSOURCE_JUCEHEADER__
  24379. /*** End of inlined file: juce_IIRFilterAudioSource.h ***/
  24380. #endif
  24381. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24382. /*** Start of inlined file: juce_MixerAudioSource.h ***/
  24383. #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24384. #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24385. /**
  24386. An AudioSource that mixes together the output of a set of other AudioSources.
  24387. Input sources can be added and removed while the mixer is running as long as their
  24388. prepareToPlay() and releaseResources() methods are called before and after adding
  24389. them to the mixer.
  24390. */
  24391. class JUCE_API MixerAudioSource : public AudioSource
  24392. {
  24393. public:
  24394. /** Creates a MixerAudioSource.
  24395. */
  24396. MixerAudioSource();
  24397. /** Destructor. */
  24398. ~MixerAudioSource();
  24399. /** Adds an input source to the mixer.
  24400. If the mixer is running you'll need to make sure that the input source
  24401. is ready to play by calling its prepareToPlay() method before adding it.
  24402. If the mixer is stopped, then its input sources will be automatically
  24403. prepared when the mixer's prepareToPlay() method is called.
  24404. @param newInput the source to add to the mixer
  24405. @param deleteWhenRemoved if true, then this source will be deleted when
  24406. the mixer is deleted or when removeAllInputs() is
  24407. called (unless the source is previously removed
  24408. with the removeInputSource method)
  24409. */
  24410. void addInputSource (AudioSource* newInput,
  24411. const bool deleteWhenRemoved);
  24412. /** Removes an input source.
  24413. If the mixer is running, this will remove the source but not call its
  24414. releaseResources() method, so the caller might want to do this manually.
  24415. @param input the source to remove
  24416. @param deleteSource whether to delete this source after it's been removed
  24417. */
  24418. void removeInputSource (AudioSource* input,
  24419. const bool deleteSource);
  24420. /** Removes all the input sources.
  24421. If the mixer is running, this will remove the sources but not call their
  24422. releaseResources() method, so the caller might want to do this manually.
  24423. Any sources which were added with the deleteWhenRemoved flag set will be
  24424. deleted by this method.
  24425. */
  24426. void removeAllInputs();
  24427. /** Implementation of the AudioSource method.
  24428. This will call prepareToPlay() on all its input sources.
  24429. */
  24430. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24431. /** Implementation of the AudioSource method.
  24432. This will call releaseResources() on all its input sources.
  24433. */
  24434. void releaseResources();
  24435. /** Implementation of the AudioSource method. */
  24436. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24437. juce_UseDebuggingNewOperator
  24438. private:
  24439. Array <AudioSource*> inputs;
  24440. BigInteger inputsToDelete;
  24441. CriticalSection lock;
  24442. AudioSampleBuffer tempBuffer;
  24443. double currentSampleRate;
  24444. int bufferSizeExpected;
  24445. MixerAudioSource (const MixerAudioSource&);
  24446. MixerAudioSource& operator= (const MixerAudioSource&);
  24447. };
  24448. #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
  24449. /*** End of inlined file: juce_MixerAudioSource.h ***/
  24450. #endif
  24451. #ifndef __JUCE_POSITIONABLEAUDIOSOURCE_JUCEHEADER__
  24452. #endif
  24453. #ifndef __JUCE_RESAMPLINGAUDIOSOURCE_JUCEHEADER__
  24454. #endif
  24455. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24456. /*** Start of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24457. #ifndef __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24458. #define __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24459. /**
  24460. A simple AudioSource that generates a sine wave.
  24461. */
  24462. class JUCE_API ToneGeneratorAudioSource : public AudioSource
  24463. {
  24464. public:
  24465. /** Creates a ToneGeneratorAudioSource. */
  24466. ToneGeneratorAudioSource();
  24467. /** Destructor. */
  24468. ~ToneGeneratorAudioSource();
  24469. /** Sets the signal's amplitude. */
  24470. void setAmplitude (const float newAmplitude);
  24471. /** Sets the signal's frequency. */
  24472. void setFrequency (const double newFrequencyHz);
  24473. /** Implementation of the AudioSource method. */
  24474. void prepareToPlay (int samplesPerBlockExpected, double sampleRate);
  24475. /** Implementation of the AudioSource method. */
  24476. void releaseResources();
  24477. /** Implementation of the AudioSource method. */
  24478. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill);
  24479. juce_UseDebuggingNewOperator
  24480. private:
  24481. double frequency, sampleRate;
  24482. double currentPhase, phasePerSample;
  24483. float amplitude;
  24484. ToneGeneratorAudioSource (const ToneGeneratorAudioSource&);
  24485. ToneGeneratorAudioSource& operator= (const ToneGeneratorAudioSource&);
  24486. };
  24487. #endif // __JUCE_TONEGENERATORAUDIOSOURCE_JUCEHEADER__
  24488. /*** End of inlined file: juce_ToneGeneratorAudioSource.h ***/
  24489. #endif
  24490. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24491. /*** Start of inlined file: juce_AudioDeviceManager.h ***/
  24492. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24493. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24494. /*** Start of inlined file: juce_AudioIODeviceType.h ***/
  24495. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24496. #define __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24497. class AudioDeviceManager;
  24498. class Component;
  24499. /**
  24500. Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
  24501. To get a list of available audio driver types, use the AudioDeviceManager::createAudioDeviceTypes()
  24502. method. Each of the objects returned can then be used to list the available
  24503. devices of that type. E.g.
  24504. @code
  24505. OwnedArray <AudioIODeviceType> types;
  24506. myAudioDeviceManager.createAudioDeviceTypes (types);
  24507. for (int i = 0; i < types.size(); ++i)
  24508. {
  24509. String typeName (types[i]->getTypeName()); // This will be things like "DirectSound", "CoreAudio", etc.
  24510. types[i]->scanForDevices(); // This must be called before getting the list of devices
  24511. StringArray deviceNames (types[i]->getDeviceNames()); // This will now return a list of available devices of this type
  24512. for (int j = 0; j < deviceNames.size(); ++j)
  24513. {
  24514. AudioIODevice* device = types[i]->createDevice (deviceNames [j]);
  24515. ...
  24516. }
  24517. }
  24518. @endcode
  24519. For an easier way of managing audio devices and their settings, have a look at the
  24520. AudioDeviceManager class.
  24521. @see AudioIODevice, AudioDeviceManager
  24522. */
  24523. class JUCE_API AudioIODeviceType
  24524. {
  24525. public:
  24526. /** Returns the name of this type of driver that this object manages.
  24527. This will be something like "DirectSound", "ASIO", "CoreAudio", "ALSA", etc.
  24528. */
  24529. const String& getTypeName() const throw() { return typeName; }
  24530. /** Refreshes the object's cached list of known devices.
  24531. This must be called at least once before calling getDeviceNames() or any of
  24532. the other device creation methods.
  24533. */
  24534. virtual void scanForDevices() = 0;
  24535. /** Returns the list of available devices of this type.
  24536. The scanForDevices() method must have been called to create this list.
  24537. @param wantInputNames only really used by DirectSound where devices are split up
  24538. into inputs and outputs, this indicates whether to use
  24539. the input or output name to refer to a pair of devices.
  24540. */
  24541. virtual const StringArray getDeviceNames (bool wantInputNames = false) const = 0;
  24542. /** Returns the name of the default device.
  24543. This will be one of the names from the getDeviceNames() list.
  24544. @param forInput if true, this means that a default input device should be
  24545. returned; if false, it should return the default output
  24546. */
  24547. virtual int getDefaultDeviceIndex (bool forInput) const = 0;
  24548. /** Returns the index of a given device in the list of device names.
  24549. If asInput is true, it shows the index in the inputs list, otherwise it
  24550. looks for it in the outputs list.
  24551. */
  24552. virtual int getIndexOfDevice (AudioIODevice* device, bool asInput) const = 0;
  24553. /** Returns true if two different devices can be used for the input and output.
  24554. */
  24555. virtual bool hasSeparateInputsAndOutputs() const = 0;
  24556. /** Creates one of the devices of this type.
  24557. The deviceName must be one of the strings returned by getDeviceNames(), and
  24558. scanForDevices() must have been called before this method is used.
  24559. */
  24560. virtual AudioIODevice* createDevice (const String& outputDeviceName,
  24561. const String& inputDeviceName) = 0;
  24562. struct DeviceSetupDetails
  24563. {
  24564. AudioDeviceManager* manager;
  24565. int minNumInputChannels, maxNumInputChannels;
  24566. int minNumOutputChannels, maxNumOutputChannels;
  24567. bool useStereoPairs;
  24568. };
  24569. /** Destructor. */
  24570. virtual ~AudioIODeviceType();
  24571. protected:
  24572. explicit AudioIODeviceType (const String& typeName);
  24573. private:
  24574. String typeName;
  24575. AudioIODeviceType (const AudioIODeviceType&);
  24576. AudioIODeviceType& operator= (const AudioIODeviceType&);
  24577. };
  24578. #endif // __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  24579. /*** End of inlined file: juce_AudioIODeviceType.h ***/
  24580. /*** Start of inlined file: juce_MidiInput.h ***/
  24581. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  24582. #define __JUCE_MIDIINPUT_JUCEHEADER__
  24583. /*** Start of inlined file: juce_MidiMessage.h ***/
  24584. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  24585. #define __JUCE_MIDIMESSAGE_JUCEHEADER__
  24586. /**
  24587. Encapsulates a MIDI message.
  24588. @see MidiMessageSequence, MidiOutput, MidiInput
  24589. */
  24590. class JUCE_API MidiMessage
  24591. {
  24592. public:
  24593. /** Creates a 3-byte short midi message.
  24594. @param byte1 message byte 1
  24595. @param byte2 message byte 2
  24596. @param byte3 message byte 3
  24597. @param timeStamp the time to give the midi message - this value doesn't
  24598. use any particular units, so will be application-specific
  24599. */
  24600. MidiMessage (int byte1, int byte2, int byte3, double timeStamp = 0) throw();
  24601. /** Creates a 2-byte short midi message.
  24602. @param byte1 message byte 1
  24603. @param byte2 message byte 2
  24604. @param timeStamp the time to give the midi message - this value doesn't
  24605. use any particular units, so will be application-specific
  24606. */
  24607. MidiMessage (int byte1, int byte2, double timeStamp = 0) throw();
  24608. /** Creates a 1-byte short midi message.
  24609. @param byte1 message byte 1
  24610. @param timeStamp the time to give the midi message - this value doesn't
  24611. use any particular units, so will be application-specific
  24612. */
  24613. MidiMessage (int byte1, double timeStamp = 0) throw();
  24614. /** Creates a midi message from a block of data. */
  24615. MidiMessage (const void* data, int numBytes, double timeStamp = 0);
  24616. /** Reads the next midi message from some data.
  24617. This will read as many bytes from a data stream as it needs to make a
  24618. complete message, and will return the number of bytes it used. This lets
  24619. you read a sequence of midi messages from a file or stream.
  24620. @param data the data to read from
  24621. @param maxBytesToUse the maximum number of bytes it's allowed to read
  24622. @param numBytesUsed returns the number of bytes that were actually needed
  24623. @param lastStatusByte in a sequence of midi messages, the initial byte
  24624. can be dropped from a message if it's the same as the
  24625. first byte of the previous message, so this lets you
  24626. supply the byte to use if the first byte of the message
  24627. has in fact been dropped.
  24628. @param timeStamp the time to give the midi message - this value doesn't
  24629. use any particular units, so will be application-specific
  24630. */
  24631. MidiMessage (const void* data, int maxBytesToUse,
  24632. int& numBytesUsed, uint8 lastStatusByte,
  24633. double timeStamp = 0);
  24634. /** Creates a copy of another midi message. */
  24635. MidiMessage (const MidiMessage& other);
  24636. /** Creates a copy of another midi message, with a different timestamp. */
  24637. MidiMessage (const MidiMessage& other, double newTimeStamp);
  24638. /** Destructor. */
  24639. ~MidiMessage();
  24640. /** Copies this message from another one. */
  24641. MidiMessage& operator= (const MidiMessage& other);
  24642. /** Returns a pointer to the raw midi data.
  24643. @see getRawDataSize
  24644. */
  24645. uint8* getRawData() const throw() { return data; }
  24646. /** Returns the number of bytes of data in the message.
  24647. @see getRawData
  24648. */
  24649. int getRawDataSize() const throw() { return size; }
  24650. /** Returns the timestamp associated with this message.
  24651. The exact meaning of this time and its units will vary, as messages are used in
  24652. a variety of different contexts.
  24653. If you're getting the message from a midi file, this could be a time in seconds, or
  24654. a number of ticks - see MidiFile::convertTimestampTicksToSeconds().
  24655. If the message is being used in a MidiBuffer, it might indicate the number of
  24656. audio samples from the start of the buffer.
  24657. If the message was created by a MidiInput, see MidiInputCallback::handleIncomingMidiMessage()
  24658. for details of the way that it initialises this value.
  24659. @see setTimeStamp, addToTimeStamp
  24660. */
  24661. double getTimeStamp() const throw() { return timeStamp; }
  24662. /** Changes the message's associated timestamp.
  24663. The units for the timestamp will be application-specific - see the notes for getTimeStamp().
  24664. @see addToTimeStamp, getTimeStamp
  24665. */
  24666. void setTimeStamp (double newTimestamp) throw() { timeStamp = newTimestamp; }
  24667. /** Adds a value to the message's timestamp.
  24668. The units for the timestamp will be application-specific.
  24669. */
  24670. void addToTimeStamp (double delta) throw() { timeStamp += delta; }
  24671. /** Returns the midi channel associated with the message.
  24672. @returns a value 1 to 16 if the message has a channel, or 0 if it hasn't (e.g.
  24673. if it's a sysex)
  24674. @see isForChannel, setChannel
  24675. */
  24676. int getChannel() const throw();
  24677. /** Returns true if the message applies to the given midi channel.
  24678. @param channelNumber the channel number to look for, in the range 1 to 16
  24679. @see getChannel, setChannel
  24680. */
  24681. bool isForChannel (int channelNumber) const throw();
  24682. /** Changes the message's midi channel.
  24683. This won't do anything for non-channel messages like sysexes.
  24684. @param newChannelNumber the channel number to change it to, in the range 1 to 16
  24685. */
  24686. void setChannel (int newChannelNumber) throw();
  24687. /** Returns true if this is a system-exclusive message.
  24688. */
  24689. bool isSysEx() const throw();
  24690. /** Returns a pointer to the sysex data inside the message.
  24691. If this event isn't a sysex event, it'll return 0.
  24692. @see getSysExDataSize
  24693. */
  24694. const uint8* getSysExData() const throw();
  24695. /** Returns the size of the sysex data.
  24696. This value excludes the 0xf0 header byte and the 0xf7 at the end.
  24697. @see getSysExData
  24698. */
  24699. int getSysExDataSize() const throw();
  24700. /** Returns true if this message is a 'key-down' event.
  24701. @param returnTrueForVelocity0 if true, then if this event is a note-on with
  24702. velocity 0, it will still be considered to be a note-on and the
  24703. method will return true. If returnTrueForVelocity0 is false, then
  24704. if this is a note-on event with velocity 0, it'll be regarded as
  24705. a note-off, and the method will return false
  24706. @see isNoteOff, getNoteNumber, getVelocity, noteOn
  24707. */
  24708. bool isNoteOn (bool returnTrueForVelocity0 = false) const throw();
  24709. /** Creates a key-down message (using a floating-point velocity).
  24710. @param channel the midi channel, in the range 1 to 16
  24711. @param noteNumber the key number, 0 to 127
  24712. @param velocity in the range 0 to 1.0
  24713. @see isNoteOn
  24714. */
  24715. static const MidiMessage noteOn (int channel, int noteNumber, float velocity) throw();
  24716. /** Creates a key-down message (using an integer velocity).
  24717. @param channel the midi channel, in the range 1 to 16
  24718. @param noteNumber the key number, 0 to 127
  24719. @param velocity in the range 0 to 127
  24720. @see isNoteOn
  24721. */
  24722. static const MidiMessage noteOn (int channel, int noteNumber, uint8 velocity) throw();
  24723. /** Returns true if this message is a 'key-up' event.
  24724. If returnTrueForNoteOnVelocity0 is true, then his will also return true
  24725. for a note-on event with a velocity of 0.
  24726. @see isNoteOn, getNoteNumber, getVelocity, noteOff
  24727. */
  24728. bool isNoteOff (bool returnTrueForNoteOnVelocity0 = true) const throw();
  24729. /** Creates a key-up message.
  24730. @param channel the midi channel, in the range 1 to 16
  24731. @param noteNumber the key number, 0 to 127
  24732. @see isNoteOff
  24733. */
  24734. static const MidiMessage noteOff (int channel, int noteNumber) throw();
  24735. /** Returns true if this message is a 'key-down' or 'key-up' event.
  24736. @see isNoteOn, isNoteOff
  24737. */
  24738. bool isNoteOnOrOff() const throw();
  24739. /** Returns the midi note number for note-on and note-off messages.
  24740. If the message isn't a note-on or off, the value returned will be
  24741. meaningless.
  24742. @see isNoteOff, getMidiNoteName, getMidiNoteInHertz, setNoteNumber
  24743. */
  24744. int getNoteNumber() const throw();
  24745. /** Changes the midi note number of a note-on or note-off message.
  24746. If the message isn't a note on or off, this will do nothing.
  24747. */
  24748. void setNoteNumber (int newNoteNumber) throw();
  24749. /** Returns the velocity of a note-on or note-off message.
  24750. The value returned will be in the range 0 to 127.
  24751. If the message isn't a note-on or off event, it will return 0.
  24752. @see getFloatVelocity
  24753. */
  24754. uint8 getVelocity() const throw();
  24755. /** Returns the velocity of a note-on or note-off message.
  24756. The value returned will be in the range 0 to 1.0
  24757. If the message isn't a note-on or off event, it will return 0.
  24758. @see getVelocity, setVelocity
  24759. */
  24760. float getFloatVelocity() const throw();
  24761. /** Changes the velocity of a note-on or note-off message.
  24762. If the message isn't a note on or off, this will do nothing.
  24763. @param newVelocity the new velocity, in the range 0 to 1.0
  24764. @see getFloatVelocity, multiplyVelocity
  24765. */
  24766. void setVelocity (float newVelocity) throw();
  24767. /** Multiplies the velocity of a note-on or note-off message by a given amount.
  24768. If the message isn't a note on or off, this will do nothing.
  24769. @param scaleFactor the value by which to multiply the velocity
  24770. @see setVelocity
  24771. */
  24772. void multiplyVelocity (float scaleFactor) throw();
  24773. /** Returns true if the message is a program (patch) change message.
  24774. @see getProgramChangeNumber, getGMInstrumentName
  24775. */
  24776. bool isProgramChange() const throw();
  24777. /** Returns the new program number of a program change message.
  24778. If the message isn't a program change, the value returned will be
  24779. nonsense.
  24780. @see isProgramChange, getGMInstrumentName
  24781. */
  24782. int getProgramChangeNumber() const throw();
  24783. /** Creates a program-change message.
  24784. @param channel the midi channel, in the range 1 to 16
  24785. @param programNumber the midi program number, 0 to 127
  24786. @see isProgramChange, getGMInstrumentName
  24787. */
  24788. static const MidiMessage programChange (int channel, int programNumber) throw();
  24789. /** Returns true if the message is a pitch-wheel move.
  24790. @see getPitchWheelValue, pitchWheel
  24791. */
  24792. bool isPitchWheel() const throw();
  24793. /** Returns the pitch wheel position from a pitch-wheel move message.
  24794. The value returned is a 14-bit number from 0 to 0x3fff, indicating the wheel position.
  24795. If called for messages which aren't pitch wheel events, the number returned will be
  24796. nonsense.
  24797. @see isPitchWheel
  24798. */
  24799. int getPitchWheelValue() const throw();
  24800. /** Creates a pitch-wheel move message.
  24801. @param channel the midi channel, in the range 1 to 16
  24802. @param position the wheel position, in the range 0 to 16383
  24803. @see isPitchWheel
  24804. */
  24805. static const MidiMessage pitchWheel (int channel, int position) throw();
  24806. /** Returns true if the message is an aftertouch event.
  24807. For aftertouch events, use the getNoteNumber() method to find out the key
  24808. that it applies to, and getAftertouchValue() to find out the amount. Use
  24809. getChannel() to find out the channel.
  24810. @see getAftertouchValue, getNoteNumber
  24811. */
  24812. bool isAftertouch() const throw();
  24813. /** Returns the amount of aftertouch from an aftertouch messages.
  24814. The value returned is in the range 0 to 127, and will be nonsense for messages
  24815. other than aftertouch messages.
  24816. @see isAftertouch
  24817. */
  24818. int getAfterTouchValue() const throw();
  24819. /** Creates an aftertouch message.
  24820. @param channel the midi channel, in the range 1 to 16
  24821. @param noteNumber the key number, 0 to 127
  24822. @param aftertouchAmount the amount of aftertouch, 0 to 127
  24823. @see isAftertouch
  24824. */
  24825. static const MidiMessage aftertouchChange (int channel,
  24826. int noteNumber,
  24827. int aftertouchAmount) throw();
  24828. /** Returns true if the message is a channel-pressure change event.
  24829. This is like aftertouch, but common to the whole channel rather than a specific
  24830. note. Use getChannelPressureValue() to find out the pressure, and getChannel()
  24831. to find out the channel.
  24832. @see channelPressureChange
  24833. */
  24834. bool isChannelPressure() const throw();
  24835. /** Returns the pressure from a channel pressure change message.
  24836. @returns the pressure, in the range 0 to 127
  24837. @see isChannelPressure, channelPressureChange
  24838. */
  24839. int getChannelPressureValue() const throw();
  24840. /** Creates a channel-pressure change event.
  24841. @param channel the midi channel: 1 to 16
  24842. @param pressure the pressure, 0 to 127
  24843. @see isChannelPressure
  24844. */
  24845. static const MidiMessage channelPressureChange (int channel, int pressure) throw();
  24846. /** Returns true if this is a midi controller message.
  24847. @see getControllerNumber, getControllerValue, controllerEvent
  24848. */
  24849. bool isController() const throw();
  24850. /** Returns the controller number of a controller message.
  24851. The name of the controller can be looked up using the getControllerName() method.
  24852. Note that the value returned is invalid for messages that aren't controller changes.
  24853. @see isController, getControllerName, getControllerValue
  24854. */
  24855. int getControllerNumber() const throw();
  24856. /** Returns the controller value from a controller message.
  24857. A value 0 to 127 is returned to indicate the new controller position.
  24858. Note that the value returned is invalid for messages that aren't controller changes.
  24859. @see isController, getControllerNumber
  24860. */
  24861. int getControllerValue() const throw();
  24862. /** Creates a controller message.
  24863. @param channel the midi channel, in the range 1 to 16
  24864. @param controllerType the type of controller
  24865. @param value the controller value
  24866. @see isController
  24867. */
  24868. static const MidiMessage controllerEvent (int channel,
  24869. int controllerType,
  24870. int value) throw();
  24871. /** Checks whether this message is an all-notes-off message.
  24872. @see allNotesOff
  24873. */
  24874. bool isAllNotesOff() const throw();
  24875. /** Checks whether this message is an all-sound-off message.
  24876. @see allSoundOff
  24877. */
  24878. bool isAllSoundOff() const throw();
  24879. /** Creates an all-notes-off message.
  24880. @param channel the midi channel, in the range 1 to 16
  24881. @see isAllNotesOff
  24882. */
  24883. static const MidiMessage allNotesOff (int channel) throw();
  24884. /** Creates an all-sound-off message.
  24885. @param channel the midi channel, in the range 1 to 16
  24886. @see isAllSoundOff
  24887. */
  24888. static const MidiMessage allSoundOff (int channel) throw();
  24889. /** Creates an all-controllers-off message.
  24890. @param channel the midi channel, in the range 1 to 16
  24891. */
  24892. static const MidiMessage allControllersOff (int channel) throw();
  24893. /** Returns true if this event is a meta-event.
  24894. Meta-events are things like tempo changes, track names, etc.
  24895. @see getMetaEventType, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24896. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24897. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24898. */
  24899. bool isMetaEvent() const throw();
  24900. /** Returns a meta-event's type number.
  24901. If the message isn't a meta-event, this will return -1.
  24902. @see isMetaEvent, isTrackMetaEvent, isEndOfTrackMetaEvent,
  24903. isTextMetaEvent, isTrackNameEvent, isTempoMetaEvent, isTimeSignatureMetaEvent,
  24904. isKeySignatureMetaEvent, isMidiChannelMetaEvent
  24905. */
  24906. int getMetaEventType() const throw();
  24907. /** Returns a pointer to the data in a meta-event.
  24908. @see isMetaEvent, getMetaEventLength
  24909. */
  24910. const uint8* getMetaEventData() const throw();
  24911. /** Returns the length of the data for a meta-event.
  24912. @see isMetaEvent, getMetaEventData
  24913. */
  24914. int getMetaEventLength() const throw();
  24915. /** Returns true if this is a 'track' meta-event. */
  24916. bool isTrackMetaEvent() const throw();
  24917. /** Returns true if this is an 'end-of-track' meta-event. */
  24918. bool isEndOfTrackMetaEvent() const throw();
  24919. /** Creates an end-of-track meta-event.
  24920. @see isEndOfTrackMetaEvent
  24921. */
  24922. static const MidiMessage endOfTrack() throw();
  24923. /** Returns true if this is an 'track name' meta-event.
  24924. You can use the getTextFromTextMetaEvent() method to get the track's name.
  24925. */
  24926. bool isTrackNameEvent() const throw();
  24927. /** Returns true if this is a 'text' meta-event.
  24928. @see getTextFromTextMetaEvent
  24929. */
  24930. bool isTextMetaEvent() const throw();
  24931. /** Returns the text from a text meta-event.
  24932. @see isTextMetaEvent
  24933. */
  24934. const String getTextFromTextMetaEvent() const;
  24935. /** Returns true if this is a 'tempo' meta-event.
  24936. @see getTempoMetaEventTickLength, getTempoSecondsPerQuarterNote
  24937. */
  24938. bool isTempoMetaEvent() const throw();
  24939. /** Returns the tick length from a tempo meta-event.
  24940. @param timeFormat the 16-bit time format value from the midi file's header.
  24941. @returns the tick length (in seconds).
  24942. @see isTempoMetaEvent
  24943. */
  24944. double getTempoMetaEventTickLength (short timeFormat) const throw();
  24945. /** Calculates the seconds-per-quarter-note from a tempo meta-event.
  24946. @see isTempoMetaEvent, getTempoMetaEventTickLength
  24947. */
  24948. double getTempoSecondsPerQuarterNote() const throw();
  24949. /** Creates a tempo meta-event.
  24950. @see isTempoMetaEvent
  24951. */
  24952. static const MidiMessage tempoMetaEvent (int microsecondsPerQuarterNote) throw();
  24953. /** Returns true if this is a 'time-signature' meta-event.
  24954. @see getTimeSignatureInfo
  24955. */
  24956. bool isTimeSignatureMetaEvent() const throw();
  24957. /** Returns the time-signature values from a time-signature meta-event.
  24958. @see isTimeSignatureMetaEvent
  24959. */
  24960. void getTimeSignatureInfo (int& numerator, int& denominator) const throw();
  24961. /** Creates a time-signature meta-event.
  24962. @see isTimeSignatureMetaEvent
  24963. */
  24964. static const MidiMessage timeSignatureMetaEvent (int numerator, int denominator);
  24965. /** Returns true if this is a 'key-signature' meta-event.
  24966. @see getKeySignatureNumberOfSharpsOrFlats
  24967. */
  24968. bool isKeySignatureMetaEvent() const throw();
  24969. /** Returns the key from a key-signature meta-event.
  24970. @see isKeySignatureMetaEvent
  24971. */
  24972. int getKeySignatureNumberOfSharpsOrFlats() const throw();
  24973. /** Returns true if this is a 'channel' meta-event.
  24974. A channel meta-event specifies the midi channel that should be used
  24975. for subsequent meta-events.
  24976. @see getMidiChannelMetaEventChannel
  24977. */
  24978. bool isMidiChannelMetaEvent() const throw();
  24979. /** Returns the channel number from a channel meta-event.
  24980. @returns the channel, in the range 1 to 16.
  24981. @see isMidiChannelMetaEvent
  24982. */
  24983. int getMidiChannelMetaEventChannel() const throw();
  24984. /** Creates a midi channel meta-event.
  24985. @param channel the midi channel, in the range 1 to 16
  24986. @see isMidiChannelMetaEvent
  24987. */
  24988. static const MidiMessage midiChannelMetaEvent (int channel) throw();
  24989. /** Returns true if this is an active-sense message. */
  24990. bool isActiveSense() const throw();
  24991. /** Returns true if this is a midi start event.
  24992. @see midiStart
  24993. */
  24994. bool isMidiStart() const throw();
  24995. /** Creates a midi start event. */
  24996. static const MidiMessage midiStart() throw();
  24997. /** Returns true if this is a midi continue event.
  24998. @see midiContinue
  24999. */
  25000. bool isMidiContinue() const throw();
  25001. /** Creates a midi continue event. */
  25002. static const MidiMessage midiContinue() throw();
  25003. /** Returns true if this is a midi stop event.
  25004. @see midiStop
  25005. */
  25006. bool isMidiStop() const throw();
  25007. /** Creates a midi stop event. */
  25008. static const MidiMessage midiStop() throw();
  25009. /** Returns true if this is a midi clock event.
  25010. @see midiClock, songPositionPointer
  25011. */
  25012. bool isMidiClock() const throw();
  25013. /** Creates a midi clock event. */
  25014. static const MidiMessage midiClock() throw();
  25015. /** Returns true if this is a song-position-pointer message.
  25016. @see getSongPositionPointerMidiBeat, songPositionPointer
  25017. */
  25018. bool isSongPositionPointer() const throw();
  25019. /** Returns the midi beat-number of a song-position-pointer message.
  25020. @see isSongPositionPointer, songPositionPointer
  25021. */
  25022. int getSongPositionPointerMidiBeat() const throw();
  25023. /** Creates a song-position-pointer message.
  25024. The position is a number of midi beats from the start of the song, where 1 midi
  25025. beat is 6 midi clocks, and there are 24 midi clocks in a quarter-note. So there
  25026. are 4 midi beats in a quarter-note.
  25027. @see isSongPositionPointer, getSongPositionPointerMidiBeat
  25028. */
  25029. static const MidiMessage songPositionPointer (int positionInMidiBeats) throw();
  25030. /** Returns true if this is a quarter-frame midi timecode message.
  25031. @see quarterFrame, getQuarterFrameSequenceNumber, getQuarterFrameValue
  25032. */
  25033. bool isQuarterFrame() const throw();
  25034. /** Returns the sequence number of a quarter-frame midi timecode message.
  25035. This will be a value between 0 and 7.
  25036. @see isQuarterFrame, getQuarterFrameValue, quarterFrame
  25037. */
  25038. int getQuarterFrameSequenceNumber() const throw();
  25039. /** Returns the value from a quarter-frame message.
  25040. This will be the lower nybble of the message's data-byte, a value
  25041. between 0 and 15
  25042. */
  25043. int getQuarterFrameValue() const throw();
  25044. /** Creates a quarter-frame MTC message.
  25045. @param sequenceNumber a value 0 to 7 for the upper nybble of the message's data byte
  25046. @param value a value 0 to 15 for the lower nybble of the message's data byte
  25047. */
  25048. static const MidiMessage quarterFrame (int sequenceNumber, int value) throw();
  25049. /** SMPTE timecode types.
  25050. Used by the getFullFrameParameters() and fullFrame() methods.
  25051. */
  25052. enum SmpteTimecodeType
  25053. {
  25054. fps24 = 0,
  25055. fps25 = 1,
  25056. fps30drop = 2,
  25057. fps30 = 3
  25058. };
  25059. /** Returns true if this is a full-frame midi timecode message.
  25060. */
  25061. bool isFullFrame() const throw();
  25062. /** Extracts the timecode information from a full-frame midi timecode message.
  25063. You should only call this on messages where you've used isFullFrame() to
  25064. check that they're the right kind.
  25065. */
  25066. void getFullFrameParameters (int& hours,
  25067. int& minutes,
  25068. int& seconds,
  25069. int& frames,
  25070. SmpteTimecodeType& timecodeType) const throw();
  25071. /** Creates a full-frame MTC message.
  25072. */
  25073. static const MidiMessage fullFrame (int hours,
  25074. int minutes,
  25075. int seconds,
  25076. int frames,
  25077. SmpteTimecodeType timecodeType);
  25078. /** Types of MMC command.
  25079. @see isMidiMachineControlMessage, getMidiMachineControlCommand, midiMachineControlCommand
  25080. */
  25081. enum MidiMachineControlCommand
  25082. {
  25083. mmc_stop = 1,
  25084. mmc_play = 2,
  25085. mmc_deferredplay = 3,
  25086. mmc_fastforward = 4,
  25087. mmc_rewind = 5,
  25088. mmc_recordStart = 6,
  25089. mmc_recordStop = 7,
  25090. mmc_pause = 9
  25091. };
  25092. /** Checks whether this is an MMC message.
  25093. If it is, you can use the getMidiMachineControlCommand() to find out its type.
  25094. */
  25095. bool isMidiMachineControlMessage() const throw();
  25096. /** For an MMC message, this returns its type.
  25097. Make sure it's actually an MMC message with isMidiMachineControlMessage() before
  25098. calling this method.
  25099. */
  25100. MidiMachineControlCommand getMidiMachineControlCommand() const throw();
  25101. /** Creates an MMC message.
  25102. */
  25103. static const MidiMessage midiMachineControlCommand (MidiMachineControlCommand command);
  25104. /** Checks whether this is an MMC "goto" message.
  25105. If it is, the parameters passed-in are set to the time that the message contains.
  25106. @see midiMachineControlGoto
  25107. */
  25108. bool isMidiMachineControlGoto (int& hours,
  25109. int& minutes,
  25110. int& seconds,
  25111. int& frames) const throw();
  25112. /** Creates an MMC "goto" message.
  25113. This messages tells the device to go to a specific frame.
  25114. @see isMidiMachineControlGoto
  25115. */
  25116. static const MidiMessage midiMachineControlGoto (int hours,
  25117. int minutes,
  25118. int seconds,
  25119. int frames);
  25120. /** Creates a master-volume change message.
  25121. @param volume the volume, 0 to 1.0
  25122. */
  25123. static const MidiMessage masterVolume (float volume);
  25124. /** Creates a system-exclusive message.
  25125. The data passed in is wrapped with header and tail bytes of 0xf0 and 0xf7.
  25126. */
  25127. static const MidiMessage createSysExMessage (const uint8* sysexData,
  25128. int dataSize);
  25129. /** Reads a midi variable-length integer.
  25130. @param data the data to read the number from
  25131. @param numBytesUsed on return, this will be set to the number of bytes that were read
  25132. */
  25133. static int readVariableLengthVal (const uint8* data,
  25134. int& numBytesUsed) throw();
  25135. /** Based on the first byte of a short midi message, this uses a lookup table
  25136. to return the message length (either 1, 2, or 3 bytes).
  25137. The value passed in must be 0x80 or higher.
  25138. */
  25139. static int getMessageLengthFromFirstByte (const uint8 firstByte) throw();
  25140. /** Returns the name of a midi note number.
  25141. E.g "C", "D#", etc.
  25142. @param noteNumber the midi note number, 0 to 127
  25143. @param useSharps if true, sharpened notes are used, e.g. "C#", otherwise
  25144. they'll be flattened, e.g. "Db"
  25145. @param includeOctaveNumber if true, the octave number will be appended to the string,
  25146. e.g. "C#4"
  25147. @param octaveNumForMiddleC if an octave number is being appended, this indicates the
  25148. number that will be used for middle C's octave
  25149. @see getMidiNoteInHertz
  25150. */
  25151. static const String getMidiNoteName (int noteNumber,
  25152. bool useSharps,
  25153. bool includeOctaveNumber,
  25154. int octaveNumForMiddleC) throw();
  25155. /** Returns the frequency of a midi note number.
  25156. @see getMidiNoteName
  25157. */
  25158. static const double getMidiNoteInHertz (int noteNumber) throw();
  25159. /** Returns the standard name of a GM instrument.
  25160. @param midiInstrumentNumber the program number 0 to 127
  25161. @see getProgramChangeNumber
  25162. */
  25163. static const String getGMInstrumentName (int midiInstrumentNumber) throw();
  25164. /** Returns the name of a bank of GM instruments.
  25165. @param midiBankNumber the bank, 0 to 15
  25166. */
  25167. static const String getGMInstrumentBankName (int midiBankNumber) throw();
  25168. /** Returns the standard name of a channel 10 percussion sound.
  25169. @param midiNoteNumber the key number, 35 to 81
  25170. */
  25171. static const String getRhythmInstrumentName (int midiNoteNumber) throw();
  25172. /** Returns the name of a controller type number.
  25173. @see getControllerNumber
  25174. */
  25175. static const String getControllerName (int controllerNumber) throw();
  25176. juce_UseDebuggingNewOperator
  25177. private:
  25178. double timeStamp;
  25179. uint8* data;
  25180. int size;
  25181. union
  25182. {
  25183. uint8 asBytes[4];
  25184. uint32 asInt32;
  25185. } preallocatedData;
  25186. };
  25187. #endif // __JUCE_MIDIMESSAGE_JUCEHEADER__
  25188. /*** End of inlined file: juce_MidiMessage.h ***/
  25189. class MidiInput;
  25190. /**
  25191. Receives midi messages from a midi input device.
  25192. This class is overridden to handle incoming midi messages. See the MidiInput
  25193. class for more details.
  25194. @see MidiInput
  25195. */
  25196. class JUCE_API MidiInputCallback
  25197. {
  25198. public:
  25199. /** Destructor. */
  25200. virtual ~MidiInputCallback() {}
  25201. /** Receives an incoming message.
  25202. A MidiInput object will call this method when a midi event arrives. It'll be
  25203. called on a high-priority system thread, so avoid doing anything time-consuming
  25204. in here, and avoid making any UI calls. You might find the MidiBuffer class helpful
  25205. for queueing incoming messages for use later.
  25206. @param source the MidiInput object that generated the message
  25207. @param message the incoming message. The message's timestamp is set to a value
  25208. equivalent to (Time::getMillisecondCounter() / 1000.0) to specify the
  25209. time when the message arrived.
  25210. */
  25211. virtual void handleIncomingMidiMessage (MidiInput* source,
  25212. const MidiMessage& message) = 0;
  25213. /** Notification sent each time a packet of a multi-packet sysex message arrives.
  25214. If a long sysex message is broken up into multiple packets, this callback is made
  25215. for each packet that arrives until the message is finished, at which point
  25216. the normal handleIncomingMidiMessage() callback will be made with the entire
  25217. message.
  25218. The message passed in will contain the start of a sysex, but won't be finished
  25219. with the terminating 0xf7 byte.
  25220. */
  25221. virtual void handlePartialSysexMessage (MidiInput* source,
  25222. const uint8* messageData,
  25223. const int numBytesSoFar,
  25224. const double timestamp)
  25225. {
  25226. // (this bit is just to avoid compiler warnings about unused variables)
  25227. (void) source; (void) messageData; (void) numBytesSoFar; (void) timestamp;
  25228. }
  25229. };
  25230. /**
  25231. Represents a midi input device.
  25232. To create one of these, use the static getDevices() method to find out what inputs are
  25233. available, and then use the openDevice() method to try to open one.
  25234. @see MidiOutput
  25235. */
  25236. class JUCE_API MidiInput
  25237. {
  25238. public:
  25239. /** Returns a list of the available midi input devices.
  25240. You can open one of the devices by passing its index into the
  25241. openDevice() method.
  25242. @see getDefaultDeviceIndex, openDevice
  25243. */
  25244. static const StringArray getDevices();
  25245. /** Returns the index of the default midi input device to use.
  25246. This refers to the index in the list returned by getDevices().
  25247. */
  25248. static int getDefaultDeviceIndex();
  25249. /** Tries to open one of the midi input devices.
  25250. This will return a MidiInput object if it manages to open it. You can then
  25251. call start() and stop() on this device, and delete it when no longer needed.
  25252. If the device can't be opened, this will return a null pointer.
  25253. @param deviceIndex the index of a device from the list returned by getDevices()
  25254. @param callback the object that will receive the midi messages from this device.
  25255. @see MidiInputCallback, getDevices
  25256. */
  25257. static MidiInput* openDevice (int deviceIndex,
  25258. MidiInputCallback* callback);
  25259. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25260. /** This will try to create a new midi input device (Not available on Windows).
  25261. This will attempt to create a new midi input device with the specified name,
  25262. for other apps to connect to.
  25263. Returns 0 if a device can't be created.
  25264. @param deviceName the name to use for the new device
  25265. @param callback the object that will receive the midi messages from this device.
  25266. */
  25267. static MidiInput* createNewDevice (const String& deviceName,
  25268. MidiInputCallback* callback);
  25269. #endif
  25270. /** Destructor. */
  25271. virtual ~MidiInput();
  25272. /** Returns the name of this device.
  25273. */
  25274. virtual const String getName() const throw() { return name; }
  25275. /** Allows you to set a custom name for the device, in case you don't like the name
  25276. it was given when created.
  25277. */
  25278. virtual void setName (const String& newName) throw() { name = newName; }
  25279. /** Starts the device running.
  25280. After calling this, the device will start sending midi messages to the
  25281. MidiInputCallback object that was specified when the openDevice() method
  25282. was called.
  25283. @see stop
  25284. */
  25285. virtual void start();
  25286. /** Stops the device running.
  25287. @see start
  25288. */
  25289. virtual void stop();
  25290. juce_UseDebuggingNewOperator
  25291. protected:
  25292. String name;
  25293. void* internal;
  25294. explicit MidiInput (const String& name);
  25295. private:
  25296. MidiInput (const MidiInput&);
  25297. MidiInput& operator= (const MidiInput&);
  25298. };
  25299. #endif // __JUCE_MIDIINPUT_JUCEHEADER__
  25300. /*** End of inlined file: juce_MidiInput.h ***/
  25301. /*** Start of inlined file: juce_MidiOutput.h ***/
  25302. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  25303. #define __JUCE_MIDIOUTPUT_JUCEHEADER__
  25304. /*** Start of inlined file: juce_MidiBuffer.h ***/
  25305. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  25306. #define __JUCE_MIDIBUFFER_JUCEHEADER__
  25307. /**
  25308. Holds a sequence of time-stamped midi events.
  25309. Analogous to the AudioSampleBuffer, this holds a set of midi events with
  25310. integer time-stamps. The buffer is kept sorted in order of the time-stamps.
  25311. @see MidiMessage
  25312. */
  25313. class JUCE_API MidiBuffer
  25314. {
  25315. public:
  25316. /** Creates an empty MidiBuffer. */
  25317. MidiBuffer() throw();
  25318. /** Creates a MidiBuffer containing a single midi message. */
  25319. explicit MidiBuffer (const MidiMessage& message) throw();
  25320. /** Creates a copy of another MidiBuffer. */
  25321. MidiBuffer (const MidiBuffer& other) throw();
  25322. /** Makes a copy of another MidiBuffer. */
  25323. MidiBuffer& operator= (const MidiBuffer& other) throw();
  25324. /** Destructor */
  25325. ~MidiBuffer() throw();
  25326. /** Removes all events from the buffer. */
  25327. void clear() throw();
  25328. /** Removes all events between two times from the buffer.
  25329. All events for which (start <= event position < start + numSamples) will
  25330. be removed.
  25331. */
  25332. void clear (const int start,
  25333. const int numSamples) throw();
  25334. /** Returns true if the buffer is empty.
  25335. To actually retrieve the events, use a MidiBuffer::Iterator object
  25336. */
  25337. bool isEmpty() const throw();
  25338. /** Counts the number of events in the buffer.
  25339. This is actually quite a slow operation, as it has to iterate through all
  25340. the events, so you might prefer to call isEmpty() if that's all you need
  25341. to know.
  25342. */
  25343. int getNumEvents() const throw();
  25344. /** Adds an event to the buffer.
  25345. The sample number will be used to determine the position of the event in
  25346. the buffer, which is always kept sorted. The MidiMessage's timestamp is
  25347. ignored.
  25348. If an event is added whose sample position is the same as one or more events
  25349. already in the buffer, the new event will be placed after the existing ones.
  25350. To retrieve events, use a MidiBuffer::Iterator object
  25351. */
  25352. void addEvent (const MidiMessage& midiMessage,
  25353. const int sampleNumber) throw();
  25354. /** Adds an event to the buffer from raw midi data.
  25355. The sample number will be used to determine the position of the event in
  25356. the buffer, which is always kept sorted.
  25357. If an event is added whose sample position is the same as one or more events
  25358. already in the buffer, the new event will be placed after the existing ones.
  25359. The event data will be inspected to calculate the number of bytes in length that
  25360. the midi event really takes up, so maxBytesOfMidiData may be longer than the data
  25361. that actually gets stored. E.g. if you pass in a note-on and a length of 4 bytes,
  25362. it'll actually only store 3 bytes. If the midi data is invalid, it might not
  25363. add an event at all.
  25364. To retrieve events, use a MidiBuffer::Iterator object
  25365. */
  25366. void addEvent (const uint8* const rawMidiData,
  25367. const int maxBytesOfMidiData,
  25368. const int sampleNumber) throw();
  25369. /** Adds some events from another buffer to this one.
  25370. @param otherBuffer the buffer containing the events you want to add
  25371. @param startSample the lowest sample number in the source buffer for which
  25372. events should be added. Any source events whose timestamp is
  25373. less than this will be ignored
  25374. @param numSamples the valid range of samples from the source buffer for which
  25375. events should be added - i.e. events in the source buffer whose
  25376. timestamp is greater than or equal to (startSample + numSamples)
  25377. will be ignored. If this value is less than 0, all events after
  25378. startSample will be taken.
  25379. @param sampleDeltaToAdd a value which will be added to the source timestamps of the events
  25380. that are added to this buffer
  25381. */
  25382. void addEvents (const MidiBuffer& otherBuffer,
  25383. const int startSample,
  25384. const int numSamples,
  25385. const int sampleDeltaToAdd) throw();
  25386. /** Returns the sample number of the first event in the buffer.
  25387. If the buffer's empty, this will just return 0.
  25388. */
  25389. int getFirstEventTime() const throw();
  25390. /** Returns the sample number of the last event in the buffer.
  25391. If the buffer's empty, this will just return 0.
  25392. */
  25393. int getLastEventTime() const throw();
  25394. /** Exchanges the contents of this buffer with another one.
  25395. This is a quick operation, because no memory allocating or copying is done, it
  25396. just swaps the internal state of the two buffers.
  25397. */
  25398. void swapWith (MidiBuffer& other);
  25399. /** Preallocates some memory for the buffer to use.
  25400. This helps to avoid needing to reallocate space when the buffer has messages
  25401. added to it.
  25402. */
  25403. void ensureSize (size_t minimumNumBytes);
  25404. /**
  25405. Used to iterate through the events in a MidiBuffer.
  25406. Note that altering the buffer while an iterator is using it isn't a
  25407. safe operation.
  25408. @see MidiBuffer
  25409. */
  25410. class Iterator
  25411. {
  25412. public:
  25413. /** Creates an Iterator for this MidiBuffer. */
  25414. Iterator (const MidiBuffer& buffer) throw();
  25415. /** Destructor. */
  25416. ~Iterator() throw();
  25417. /** Repositions the iterator so that the next event retrieved will be the first
  25418. one whose sample position is at greater than or equal to the given position.
  25419. */
  25420. void setNextSamplePosition (const int samplePosition) throw();
  25421. /** Retrieves a copy of the next event from the buffer.
  25422. @param result on return, this will be the message (the MidiMessage's timestamp
  25423. is not set)
  25424. @param samplePosition on return, this will be the position of the event
  25425. @returns true if an event was found, or false if the iterator has reached
  25426. the end of the buffer
  25427. */
  25428. bool getNextEvent (MidiMessage& result,
  25429. int& samplePosition) throw();
  25430. /** Retrieves the next event from the buffer.
  25431. @param midiData on return, this pointer will be set to a block of data containing
  25432. the midi message. Note that to make it fast, this is a pointer
  25433. directly into the MidiBuffer's internal data, so is only valid
  25434. temporarily until the MidiBuffer is altered.
  25435. @param numBytesOfMidiData on return, this is the number of bytes of data used by the
  25436. midi message
  25437. @param samplePosition on return, this will be the position of the event
  25438. @returns true if an event was found, or false if the iterator has reached
  25439. the end of the buffer
  25440. */
  25441. bool getNextEvent (const uint8* &midiData,
  25442. int& numBytesOfMidiData,
  25443. int& samplePosition) throw();
  25444. juce_UseDebuggingNewOperator
  25445. private:
  25446. const MidiBuffer& buffer;
  25447. const uint8* data;
  25448. Iterator (const Iterator&);
  25449. Iterator& operator= (const Iterator&);
  25450. };
  25451. juce_UseDebuggingNewOperator
  25452. private:
  25453. friend class MidiBuffer::Iterator;
  25454. MemoryBlock data;
  25455. int bytesUsed;
  25456. uint8* getData() const throw();
  25457. uint8* findEventAfter (uint8* d, const int samplePosition) const throw();
  25458. static int getEventTime (const void* d) throw();
  25459. static uint16 getEventDataSize (const void* d) throw();
  25460. static uint16 getEventTotalSize (const void* d) throw();
  25461. };
  25462. #endif // __JUCE_MIDIBUFFER_JUCEHEADER__
  25463. /*** End of inlined file: juce_MidiBuffer.h ***/
  25464. /**
  25465. Represents a midi output device.
  25466. To create one of these, use the static getDevices() method to find out what
  25467. outputs are available, then use the openDevice() method to try to open one.
  25468. @see MidiInput
  25469. */
  25470. class JUCE_API MidiOutput : private Thread
  25471. {
  25472. public:
  25473. /** Returns a list of the available midi output devices.
  25474. You can open one of the devices by passing its index into the
  25475. openDevice() method.
  25476. @see getDefaultDeviceIndex, openDevice
  25477. */
  25478. static const StringArray getDevices();
  25479. /** Returns the index of the default midi output device to use.
  25480. This refers to the index in the list returned by getDevices().
  25481. */
  25482. static int getDefaultDeviceIndex();
  25483. /** Tries to open one of the midi output devices.
  25484. This will return a MidiOutput object if it manages to open it. You can then
  25485. send messages to this device, and delete it when no longer needed.
  25486. If the device can't be opened, this will return a null pointer.
  25487. @param deviceIndex the index of a device from the list returned by getDevices()
  25488. @see getDevices
  25489. */
  25490. static MidiOutput* openDevice (int deviceIndex);
  25491. #if JUCE_LINUX || JUCE_MAC || DOXYGEN
  25492. /** This will try to create a new midi output device (Not available on Windows).
  25493. This will attempt to create a new midi output device that other apps can connect
  25494. to and use as their midi input.
  25495. Returns 0 if a device can't be created.
  25496. @param deviceName the name to use for the new device
  25497. */
  25498. static MidiOutput* createNewDevice (const String& deviceName);
  25499. #endif
  25500. /** Destructor. */
  25501. virtual ~MidiOutput();
  25502. /** Makes this device output a midi message.
  25503. @see MidiMessage
  25504. */
  25505. virtual void sendMessageNow (const MidiMessage& message);
  25506. /** Sends a midi reset to the device. */
  25507. virtual void reset();
  25508. /** Returns the current volume setting for this device. */
  25509. virtual bool getVolume (float& leftVol,
  25510. float& rightVol);
  25511. /** Changes the overall volume for this device. */
  25512. virtual void setVolume (float leftVol,
  25513. float rightVol);
  25514. /** This lets you supply a block of messages that will be sent out at some point
  25515. in the future.
  25516. The MidiOutput class has an internal thread that can send out timestamped
  25517. messages - this appends a set of messages to its internal buffer, ready for
  25518. sending.
  25519. This will only work if you've already started the thread with startBackgroundThread().
  25520. A time is supplied, at which the block of messages should be sent. This time uses
  25521. the same time base as Time::getMillisecondCounter(), and must be in the future.
  25522. The samplesPerSecondForBuffer parameter indicates the number of samples per second
  25523. used by the MidiBuffer. Each event in a MidiBuffer has a sample position, and the
  25524. samplesPerSecondForBuffer value is needed to convert this sample position to a
  25525. real time.
  25526. */
  25527. virtual void sendBlockOfMessages (const MidiBuffer& buffer,
  25528. double millisecondCounterToStartAt,
  25529. double samplesPerSecondForBuffer);
  25530. /** Gets rid of any midi messages that had been added by sendBlockOfMessages().
  25531. */
  25532. virtual void clearAllPendingMessages();
  25533. /** Starts up a background thread so that the device can send blocks of data.
  25534. Call this to get the device ready, before using sendBlockOfMessages().
  25535. */
  25536. virtual void startBackgroundThread();
  25537. /** Stops the background thread, and clears any pending midi events.
  25538. @see startBackgroundThread
  25539. */
  25540. virtual void stopBackgroundThread();
  25541. juce_UseDebuggingNewOperator
  25542. protected:
  25543. void* internal;
  25544. struct PendingMessage
  25545. {
  25546. PendingMessage (const uint8* data, int len, double sampleNumber);
  25547. MidiMessage message;
  25548. PendingMessage* next;
  25549. juce_UseDebuggingNewOperator
  25550. };
  25551. CriticalSection lock;
  25552. PendingMessage* firstMessage;
  25553. MidiOutput();
  25554. void run();
  25555. private:
  25556. MidiOutput (const MidiOutput&);
  25557. MidiOutput& operator= (const MidiOutput&);
  25558. };
  25559. #endif // __JUCE_MIDIOUTPUT_JUCEHEADER__
  25560. /*** End of inlined file: juce_MidiOutput.h ***/
  25561. /*** Start of inlined file: juce_ComboBox.h ***/
  25562. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  25563. #define __JUCE_COMBOBOX_JUCEHEADER__
  25564. /*** Start of inlined file: juce_Label.h ***/
  25565. #ifndef __JUCE_LABEL_JUCEHEADER__
  25566. #define __JUCE_LABEL_JUCEHEADER__
  25567. /*** Start of inlined file: juce_TextEditor.h ***/
  25568. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  25569. #define __JUCE_TEXTEDITOR_JUCEHEADER__
  25570. /*** Start of inlined file: juce_Viewport.h ***/
  25571. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  25572. #define __JUCE_VIEWPORT_JUCEHEADER__
  25573. /*** Start of inlined file: juce_ScrollBar.h ***/
  25574. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  25575. #define __JUCE_SCROLLBAR_JUCEHEADER__
  25576. /*** Start of inlined file: juce_Button.h ***/
  25577. #ifndef __JUCE_BUTTON_JUCEHEADER__
  25578. #define __JUCE_BUTTON_JUCEHEADER__
  25579. /*** Start of inlined file: juce_TooltipWindow.h ***/
  25580. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25581. #define __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25582. /*** Start of inlined file: juce_TooltipClient.h ***/
  25583. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25584. #define __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25585. /**
  25586. Components that want to use pop-up tooltips should implement this interface.
  25587. A TooltipWindow will wait for the mouse to hover over a component that
  25588. implements the TooltipClient interface, and when it finds one, it will display
  25589. the tooltip returned by its getTooltip() method.
  25590. @see TooltipWindow, SettableTooltipClient
  25591. */
  25592. class JUCE_API TooltipClient
  25593. {
  25594. public:
  25595. /** Destructor. */
  25596. virtual ~TooltipClient() {}
  25597. /** Returns the string that this object wants to show as its tooltip. */
  25598. virtual const String getTooltip() = 0;
  25599. };
  25600. /**
  25601. An implementation of TooltipClient that stores the tooltip string and a method
  25602. for changing it.
  25603. This makes it easy to add a tooltip to a custom component, by simply adding this
  25604. as a base class and calling setTooltip().
  25605. Many of the Juce widgets already use this as a base class to implement their
  25606. tooltips.
  25607. @see TooltipClient, TooltipWindow
  25608. */
  25609. class JUCE_API SettableTooltipClient : public TooltipClient
  25610. {
  25611. public:
  25612. /** Destructor. */
  25613. virtual ~SettableTooltipClient() {}
  25614. virtual void setTooltip (const String& newTooltip) { tooltipString = newTooltip; }
  25615. virtual const String getTooltip() { return tooltipString; }
  25616. juce_UseDebuggingNewOperator
  25617. protected:
  25618. String tooltipString;
  25619. };
  25620. #endif // __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  25621. /*** End of inlined file: juce_TooltipClient.h ***/
  25622. /**
  25623. A window that displays a pop-up tooltip when the mouse hovers over another component.
  25624. To enable tooltips in your app, just create a single instance of a TooltipWindow
  25625. object.
  25626. The TooltipWindow object will then stay invisible, waiting until the mouse
  25627. hovers for the specified length of time - it will then see if it's currently
  25628. over a component which implements the TooltipClient interface, and if so,
  25629. it will make itself visible to show the tooltip in the appropriate place.
  25630. @see TooltipClient, SettableTooltipClient
  25631. */
  25632. class JUCE_API TooltipWindow : public Component,
  25633. private Timer
  25634. {
  25635. public:
  25636. /** Creates a tooltip window.
  25637. Make sure your app only creates one instance of this class, otherwise you'll
  25638. get multiple overlaid tooltips appearing. The window will initially be invisible
  25639. and will make itself visible when it needs to display a tip.
  25640. To change the style of tooltips, see the LookAndFeel class for its tooltip
  25641. methods.
  25642. @param parentComponent if set to 0, the TooltipWindow will appear on the desktop,
  25643. otherwise the tooltip will be added to the given parent
  25644. component.
  25645. @param millisecondsBeforeTipAppears the time for which the mouse has to stay still
  25646. before a tooltip will be shown
  25647. @see TooltipClient, LookAndFeel::drawTooltip, LookAndFeel::getTooltipSize
  25648. */
  25649. explicit TooltipWindow (Component* parentComponent = 0,
  25650. int millisecondsBeforeTipAppears = 700);
  25651. /** Destructor. */
  25652. ~TooltipWindow();
  25653. /** Changes the time before the tip appears.
  25654. This lets you change the value that was set in the constructor.
  25655. */
  25656. void setMillisecondsBeforeTipAppears (int newTimeMs = 700) throw();
  25657. /** A set of colour IDs to use to change the colour of various aspects of the tooltip.
  25658. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  25659. methods.
  25660. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  25661. */
  25662. enum ColourIds
  25663. {
  25664. backgroundColourId = 0x1001b00, /**< The colour to fill the background with. */
  25665. textColourId = 0x1001c00, /**< The colour to use for the text. */
  25666. outlineColourId = 0x1001c10 /**< The colour to use to draw an outline around the tooltip. */
  25667. };
  25668. juce_UseDebuggingNewOperator
  25669. private:
  25670. int millisecondsBeforeTipAppears;
  25671. Point<int> lastMousePos;
  25672. int mouseClicks;
  25673. unsigned int lastCompChangeTime, lastHideTime;
  25674. Component* lastComponentUnderMouse;
  25675. bool changedCompsSinceShown;
  25676. String tipShowing, lastTipUnderMouse;
  25677. void paint (Graphics& g);
  25678. void mouseEnter (const MouseEvent& e);
  25679. void timerCallback();
  25680. static const String getTipFor (Component* c);
  25681. void showFor (const String& tip);
  25682. void hide();
  25683. TooltipWindow (const TooltipWindow&);
  25684. TooltipWindow& operator= (const TooltipWindow&);
  25685. };
  25686. #endif // __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  25687. /*** End of inlined file: juce_TooltipWindow.h ***/
  25688. class Button;
  25689. /**
  25690. Used to receive callbacks when a button is clicked.
  25691. @see Button::addButtonListener, Button::removeButtonListener
  25692. */
  25693. class JUCE_API ButtonListener
  25694. {
  25695. public:
  25696. /** Destructor. */
  25697. virtual ~ButtonListener() {}
  25698. /** Called when the button is clicked. */
  25699. virtual void buttonClicked (Button* button) = 0;
  25700. /** Called when the button's state changes. */
  25701. virtual void buttonStateChanged (Button*) {}
  25702. };
  25703. /**
  25704. A base class for buttons.
  25705. This contains all the logic for button behaviours such as enabling/disabling,
  25706. responding to shortcut keystrokes, auto-repeating when held down, toggle-buttons
  25707. and radio groups, etc.
  25708. @see TextButton, DrawableButton, ToggleButton
  25709. */
  25710. class JUCE_API Button : public Component,
  25711. public SettableTooltipClient,
  25712. public ApplicationCommandManagerListener,
  25713. public Value::Listener,
  25714. private KeyListener
  25715. {
  25716. protected:
  25717. /** Creates a button.
  25718. @param buttonName the text to put in the button (the component's name is also
  25719. initially set to this string, but these can be changed later
  25720. using the setName() and setButtonText() methods)
  25721. */
  25722. explicit Button (const String& buttonName);
  25723. public:
  25724. /** Destructor. */
  25725. virtual ~Button();
  25726. /** Changes the button's text.
  25727. @see getButtonText
  25728. */
  25729. void setButtonText (const String& newText);
  25730. /** Returns the text displayed in the button.
  25731. @see setButtonText
  25732. */
  25733. const String getButtonText() const { return text; }
  25734. /** Returns true if the button is currently being held down by the mouse.
  25735. @see isOver
  25736. */
  25737. bool isDown() const throw();
  25738. /** Returns true if the mouse is currently over the button.
  25739. This will be also be true if the mouse is being held down.
  25740. @see isDown
  25741. */
  25742. bool isOver() const throw();
  25743. /** A button has an on/off state associated with it, and this changes that.
  25744. By default buttons are 'off' and for simple buttons that you click to perform
  25745. an action you won't change this. Toggle buttons, however will want to
  25746. change their state when turned on or off.
  25747. @param shouldBeOn whether to set the button's toggle state to be on or
  25748. off. If it's a member of a button group, this will
  25749. always try to turn it on, and to turn off any other
  25750. buttons in the group
  25751. @param sendChangeNotification if true, a callback will be made to clicked(); if false
  25752. the button will be repainted but no notification will
  25753. be sent
  25754. @see getToggleState, setRadioGroupId
  25755. */
  25756. void setToggleState (bool shouldBeOn,
  25757. bool sendChangeNotification);
  25758. /** Returns true if the button in 'on'.
  25759. By default buttons are 'off' and for simple buttons that you click to perform
  25760. an action you won't change this. Toggle buttons, however will want to
  25761. change their state when turned on or off.
  25762. @see setToggleState
  25763. */
  25764. bool getToggleState() const throw() { return isOn.getValue(); }
  25765. /** Returns the Value object that represents the botton's toggle state.
  25766. You can use this Value object to connect the button's state to external values or setters,
  25767. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  25768. your own Value object.
  25769. @see getToggleState, Value
  25770. */
  25771. Value& getToggleStateValue() { return isOn; }
  25772. /** This tells the button to automatically flip the toggle state when
  25773. the button is clicked.
  25774. If set to true, then before the clicked() callback occurs, the toggle-state
  25775. of the button is flipped.
  25776. */
  25777. void setClickingTogglesState (bool shouldToggle) throw();
  25778. /** Returns true if this button is set to be an automatic toggle-button.
  25779. This returns the last value that was passed to setClickingTogglesState().
  25780. */
  25781. bool getClickingTogglesState() const throw();
  25782. /** Enables the button to act as a member of a mutually-exclusive group
  25783. of 'radio buttons'.
  25784. If the group ID is set to a non-zero number, then this button will
  25785. act as part of a group of buttons with the same ID, only one of
  25786. which can be 'on' at the same time. Note that when it's part of
  25787. a group, clicking a toggle-button that's 'on' won't turn it off.
  25788. To find other buttons with the same ID, this button will search through
  25789. its sibling components for ToggleButtons, so all the buttons for a
  25790. particular group must be placed inside the same parent component.
  25791. Set the group ID back to zero if you want it to act as a normal toggle
  25792. button again.
  25793. @see getRadioGroupId
  25794. */
  25795. void setRadioGroupId (int newGroupId);
  25796. /** Returns the ID of the group to which this button belongs.
  25797. (See setRadioGroupId() for an explanation of this).
  25798. */
  25799. int getRadioGroupId() const throw() { return radioGroupId; }
  25800. /** Registers a listener to receive events when this button's state changes.
  25801. If the listener is already registered, this will not register it again.
  25802. @see removeButtonListener
  25803. */
  25804. void addButtonListener (ButtonListener* newListener);
  25805. /** Removes a previously-registered button listener
  25806. @see addButtonListener
  25807. */
  25808. void removeButtonListener (ButtonListener* listener);
  25809. /** Causes the button to act as if it's been clicked.
  25810. This will asynchronously make the button draw itself going down and up, and
  25811. will then call back the clicked() method as if mouse was clicked on it.
  25812. @see clicked
  25813. */
  25814. virtual void triggerClick();
  25815. /** Sets a command ID for this button to automatically invoke when it's clicked.
  25816. When the button is pressed, it will use the given manager to trigger the
  25817. command ID.
  25818. Obviously be careful that the ApplicationCommandManager doesn't get deleted
  25819. before this button is. To disable the command triggering, call this method and
  25820. pass 0 for the parameters.
  25821. If generateTooltip is true, then the button's tooltip will be automatically
  25822. generated based on the name of this command and its current shortcut key.
  25823. @see addShortcut, getCommandID
  25824. */
  25825. void setCommandToTrigger (ApplicationCommandManager* commandManagerToUse,
  25826. int commandID,
  25827. bool generateTooltip);
  25828. /** Returns the command ID that was set by setCommandToTrigger().
  25829. */
  25830. int getCommandID() const throw() { return commandID; }
  25831. /** Assigns a shortcut key to trigger the button.
  25832. The button registers itself with its top-level parent component for keypresses.
  25833. Note that a different way of linking buttons to keypresses is by using the
  25834. setCommandToTrigger() method to invoke a command.
  25835. @see clearShortcuts
  25836. */
  25837. void addShortcut (const KeyPress& key);
  25838. /** Removes all key shortcuts that had been set for this button.
  25839. @see addShortcut
  25840. */
  25841. void clearShortcuts();
  25842. /** Returns true if the given keypress is a shortcut for this button.
  25843. @see addShortcut
  25844. */
  25845. bool isRegisteredForShortcut (const KeyPress& key) const;
  25846. /** Sets an auto-repeat speed for the button when it is held down.
  25847. (Auto-repeat is disabled by default).
  25848. @param initialDelayInMillisecs how long to wait after the mouse is pressed before
  25849. triggering the next click. If this is zero, auto-repeat
  25850. is disabled
  25851. @param repeatDelayInMillisecs the frequently subsequent repeated clicks should be
  25852. triggered
  25853. @param minimumDelayInMillisecs if this is greater than 0, the auto-repeat speed will
  25854. get faster, the longer the button is held down, up to the
  25855. minimum interval specified here
  25856. */
  25857. void setRepeatSpeed (int initialDelayInMillisecs,
  25858. int repeatDelayInMillisecs,
  25859. int minimumDelayInMillisecs = -1) throw();
  25860. /** Sets whether the button click should happen when the mouse is pressed or released.
  25861. By default the button is only considered to have been clicked when the mouse is
  25862. released, but setting this to true will make it call the clicked() method as soon
  25863. as the button is pressed.
  25864. This is useful if the button is being used to show a pop-up menu, as it allows
  25865. the click to be used as a drag onto the menu.
  25866. */
  25867. void setTriggeredOnMouseDown (bool isTriggeredOnMouseDown) throw();
  25868. /** Returns the number of milliseconds since the last time the button
  25869. went into the 'down' state.
  25870. */
  25871. uint32 getMillisecondsSinceButtonDown() const throw();
  25872. /** (overridden from Component to do special stuff). */
  25873. void setVisible (bool shouldBeVisible);
  25874. /** Sets the tooltip for this button.
  25875. @see TooltipClient, TooltipWindow
  25876. */
  25877. void setTooltip (const String& newTooltip);
  25878. // (implementation of the TooltipClient method)
  25879. const String getTooltip();
  25880. /** A combination of these flags are used by setConnectedEdges().
  25881. */
  25882. enum ConnectedEdgeFlags
  25883. {
  25884. ConnectedOnLeft = 1,
  25885. ConnectedOnRight = 2,
  25886. ConnectedOnTop = 4,
  25887. ConnectedOnBottom = 8
  25888. };
  25889. /** Hints about which edges of the button might be connected to adjoining buttons.
  25890. The value passed in is a bitwise combination of any of the values in the
  25891. ConnectedEdgeFlags enum.
  25892. E.g. if you are placing two buttons adjacent to each other, you could use this to
  25893. indicate which edges are touching, and the LookAndFeel might choose to drawn them
  25894. without rounded corners on the edges that connect. It's only a hint, so the
  25895. LookAndFeel can choose to ignore it if it's not relevent for this type of
  25896. button.
  25897. */
  25898. void setConnectedEdges (int connectedEdgeFlags);
  25899. /** Returns the set of flags passed into setConnectedEdges(). */
  25900. int getConnectedEdgeFlags() const throw() { return connectedEdgeFlags; }
  25901. /** Indicates whether the button adjoins another one on its left edge.
  25902. @see setConnectedEdges
  25903. */
  25904. bool isConnectedOnLeft() const throw() { return (connectedEdgeFlags & ConnectedOnLeft) != 0; }
  25905. /** Indicates whether the button adjoins another one on its right edge.
  25906. @see setConnectedEdges
  25907. */
  25908. bool isConnectedOnRight() const throw() { return (connectedEdgeFlags & ConnectedOnRight) != 0; }
  25909. /** Indicates whether the button adjoins another one on its top edge.
  25910. @see setConnectedEdges
  25911. */
  25912. bool isConnectedOnTop() const throw() { return (connectedEdgeFlags & ConnectedOnTop) != 0; }
  25913. /** Indicates whether the button adjoins another one on its bottom edge.
  25914. @see setConnectedEdges
  25915. */
  25916. bool isConnectedOnBottom() const throw() { return (connectedEdgeFlags & ConnectedOnBottom) != 0; }
  25917. /** Used by setState(). */
  25918. enum ButtonState
  25919. {
  25920. buttonNormal,
  25921. buttonOver,
  25922. buttonDown
  25923. };
  25924. /** Can be used to force the button into a particular state.
  25925. This only changes the button's appearance, it won't trigger a click, or stop any mouse-clicks
  25926. from happening.
  25927. The state that you set here will only last until it is automatically changed when the mouse
  25928. enters or exits the button, or the mouse-button is pressed or released.
  25929. */
  25930. void setState (const ButtonState newState);
  25931. juce_UseDebuggingNewOperator
  25932. protected:
  25933. /** This method is called when the button has been clicked.
  25934. Subclasses can override this to perform whatever they actions they need
  25935. to do.
  25936. Alternatively, a ButtonListener can be added to the button, and these listeners
  25937. will be called when the click occurs.
  25938. @see triggerClick
  25939. */
  25940. virtual void clicked();
  25941. /** This method is called when the button has been clicked.
  25942. By default it just calls clicked(), but you might want to override it to handle
  25943. things like clicking when a modifier key is pressed, etc.
  25944. @see ModifierKeys
  25945. */
  25946. virtual void clicked (const ModifierKeys& modifiers);
  25947. /** Subclasses should override this to actually paint the button's contents.
  25948. It's better to use this than the paint method, because it gives you information
  25949. about the over/down state of the button.
  25950. @param g the graphics context to use
  25951. @param isMouseOverButton true if the button is either in the 'over' or
  25952. 'down' state
  25953. @param isButtonDown true if the button should be drawn in the 'down' position
  25954. */
  25955. virtual void paintButton (Graphics& g,
  25956. bool isMouseOverButton,
  25957. bool isButtonDown) = 0;
  25958. /** Called when the button's up/down/over state changes.
  25959. Subclasses can override this if they need to do something special when the button
  25960. goes up or down.
  25961. @see isDown, isOver
  25962. */
  25963. virtual void buttonStateChanged();
  25964. /** @internal */
  25965. virtual void internalClickCallback (const ModifierKeys& modifiers);
  25966. /** @internal */
  25967. void handleCommandMessage (int commandId);
  25968. /** @internal */
  25969. void mouseEnter (const MouseEvent& e);
  25970. /** @internal */
  25971. void mouseExit (const MouseEvent& e);
  25972. /** @internal */
  25973. void mouseDown (const MouseEvent& e);
  25974. /** @internal */
  25975. void mouseDrag (const MouseEvent& e);
  25976. /** @internal */
  25977. void mouseUp (const MouseEvent& e);
  25978. /** @internal */
  25979. bool keyPressed (const KeyPress& key);
  25980. /** @internal */
  25981. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  25982. /** @internal */
  25983. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  25984. /** @internal */
  25985. void paint (Graphics& g);
  25986. /** @internal */
  25987. void parentHierarchyChanged();
  25988. /** @internal */
  25989. void focusGained (FocusChangeType cause);
  25990. /** @internal */
  25991. void focusLost (FocusChangeType cause);
  25992. /** @internal */
  25993. void enablementChanged();
  25994. /** @internal */
  25995. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo&);
  25996. /** @internal */
  25997. void applicationCommandListChanged();
  25998. /** @internal */
  25999. void valueChanged (Value& value);
  26000. private:
  26001. Array <KeyPress> shortcuts;
  26002. Component::SafePointer<Component> keySource;
  26003. String text;
  26004. ListenerList <ButtonListener> buttonListeners;
  26005. class RepeatTimer;
  26006. friend class RepeatTimer;
  26007. friend class ScopedPointer <RepeatTimer>;
  26008. ScopedPointer <RepeatTimer> repeatTimer;
  26009. uint32 buttonPressTime, lastTimeCallbackTime;
  26010. ApplicationCommandManager* commandManagerToUse;
  26011. int autoRepeatDelay, autoRepeatSpeed, autoRepeatMinimumDelay;
  26012. int radioGroupId, commandID, connectedEdgeFlags;
  26013. ButtonState buttonState;
  26014. Value isOn;
  26015. bool lastToggleState : 1;
  26016. bool clickTogglesState : 1;
  26017. bool needsToRelease : 1;
  26018. bool needsRepainting : 1;
  26019. bool isKeyDown : 1;
  26020. bool triggerOnMouseDown : 1;
  26021. bool generateTooltip : 1;
  26022. void repeatTimerCallback();
  26023. RepeatTimer& getRepeatTimer();
  26024. ButtonState updateState (const MouseEvent* const e);
  26025. bool isShortcutPressed() const;
  26026. void turnOffOtherButtonsInGroup (const bool sendChangeNotification);
  26027. void flashButtonState();
  26028. void sendClickMessage (const ModifierKeys& modifiers);
  26029. void sendStateMessage();
  26030. Button (const Button&);
  26031. Button& operator= (const Button&);
  26032. };
  26033. #endif // __JUCE_BUTTON_JUCEHEADER__
  26034. /*** End of inlined file: juce_Button.h ***/
  26035. class ScrollBar;
  26036. /**
  26037. A class for receiving events from a ScrollBar.
  26038. You can register a ScrollBarListener with a ScrollBar using the ScrollBar::addListener()
  26039. method, and it will be called when the bar's position changes.
  26040. @see ScrollBar::addListener, ScrollBar::removeListener
  26041. */
  26042. class JUCE_API ScrollBarListener
  26043. {
  26044. public:
  26045. /** Destructor. */
  26046. virtual ~ScrollBarListener() {}
  26047. /** Called when a ScrollBar is moved.
  26048. @param scrollBarThatHasMoved the bar that has moved
  26049. @param newRangeStart the new range start of this bar
  26050. */
  26051. virtual void scrollBarMoved (ScrollBar* scrollBarThatHasMoved,
  26052. double newRangeStart) = 0;
  26053. };
  26054. /**
  26055. A scrollbar component.
  26056. To use a scrollbar, set up its total range using the setRangeLimits() method - this
  26057. sets the range of values it can represent. Then you can use setCurrentRange() to
  26058. change the position and size of the scrollbar's 'thumb'.
  26059. Registering a ScrollBarListener with the scrollbar will allow you to find out when
  26060. the user moves it, and you can use the getCurrentRangeStart() to find out where
  26061. they moved it to.
  26062. The scrollbar will adjust its own visibility according to whether its thumb size
  26063. allows it to actually be scrolled.
  26064. For most purposes, it's probably easier to use a ViewportContainer or ListBox
  26065. instead of handling a scrollbar directly.
  26066. @see ScrollBarListener
  26067. */
  26068. class JUCE_API ScrollBar : public Component,
  26069. public AsyncUpdater,
  26070. private Timer
  26071. {
  26072. public:
  26073. /** Creates a Scrollbar.
  26074. @param isVertical whether it should be a vertical or horizontal bar
  26075. @param buttonsAreVisible whether to show the up/down or left/right buttons
  26076. */
  26077. ScrollBar (bool isVertical,
  26078. bool buttonsAreVisible = true);
  26079. /** Destructor. */
  26080. ~ScrollBar();
  26081. /** Returns true if the scrollbar is vertical, false if it's horizontal. */
  26082. bool isVertical() const throw() { return vertical; }
  26083. /** Changes the scrollbar's direction.
  26084. You'll also need to resize the bar appropriately - this just changes its internal
  26085. layout.
  26086. @param shouldBeVertical true makes it vertical; false makes it horizontal.
  26087. */
  26088. void setOrientation (bool shouldBeVertical);
  26089. /** Shows or hides the scrollbar's buttons. */
  26090. void setButtonVisibility (bool buttonsAreVisible);
  26091. /** Tells the scrollbar whether to make itself invisible when not needed.
  26092. The default behaviour is for a scrollbar to become invisible when the thumb
  26093. fills the whole of its range (i.e. when it can't be moved). Setting this
  26094. value to false forces the bar to always be visible.
  26095. @see autoHides()
  26096. */
  26097. void setAutoHide (bool shouldHideWhenFullRange);
  26098. /** Returns true if this scrollbar is set to auto-hide when its thumb is as big
  26099. as its maximum range.
  26100. @see setAutoHide
  26101. */
  26102. bool autoHides() const throw();
  26103. /** Sets the minimum and maximum values that the bar will move between.
  26104. The bar's thumb will always be constrained so that the entire thumb lies
  26105. within this range.
  26106. @see setCurrentRange
  26107. */
  26108. void setRangeLimits (const Range<double>& newRangeLimit);
  26109. /** Sets the minimum and maximum values that the bar will move between.
  26110. The bar's thumb will always be constrained so that the entire thumb lies
  26111. within this range.
  26112. @see setCurrentRange
  26113. */
  26114. void setRangeLimits (double minimum, double maximum);
  26115. /** Returns the current limits on the thumb position.
  26116. @see setRangeLimits
  26117. */
  26118. const Range<double> getRangeLimit() const throw() { return totalRange; }
  26119. /** Returns the lower value that the thumb can be set to.
  26120. This is the value set by setRangeLimits().
  26121. */
  26122. double getMinimumRangeLimit() const throw() { return totalRange.getStart(); }
  26123. /** Returns the upper value that the thumb can be set to.
  26124. This is the value set by setRangeLimits().
  26125. */
  26126. double getMaximumRangeLimit() const throw() { return totalRange.getEnd(); }
  26127. /** Changes the position of the scrollbar's 'thumb'.
  26128. If this method call actually changes the scrollbar's position, it will trigger an
  26129. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  26130. are registered.
  26131. @see getCurrentRange. setCurrentRangeStart
  26132. */
  26133. void setCurrentRange (const Range<double>& newRange);
  26134. /** Changes the position of the scrollbar's 'thumb'.
  26135. This sets both the position and size of the thumb - to just set the position without
  26136. changing the size, you can use setCurrentRangeStart().
  26137. If this method call actually changes the scrollbar's position, it will trigger an
  26138. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  26139. are registered.
  26140. @param newStart the top (or left) of the thumb, in the range
  26141. getMinimumRangeLimit() <= newStart <= getMaximumRangeLimit(). If the
  26142. value is beyond these limits, it will be clipped.
  26143. @param newSize the size of the thumb, such that
  26144. getMinimumRangeLimit() <= newStart + newSize <= getMaximumRangeLimit(). If the
  26145. size is beyond these limits, it will be clipped.
  26146. @see setCurrentRangeStart, getCurrentRangeStart, getCurrentRangeSize
  26147. */
  26148. void setCurrentRange (double newStart, double newSize);
  26149. /** Moves the bar's thumb position.
  26150. This will move the thumb position without changing the thumb size. Note
  26151. that the maximum thumb start position is (getMaximumRangeLimit() - getCurrentRangeSize()).
  26152. If this method call actually changes the scrollbar's position, it will trigger an
  26153. asynchronous call to ScrollBarListener::scrollBarMoved() for all the listeners that
  26154. are registered.
  26155. @see setCurrentRange
  26156. */
  26157. void setCurrentRangeStart (double newStart);
  26158. /** Returns the current thumb range.
  26159. @see getCurrentRange, setCurrentRange
  26160. */
  26161. const Range<double> getCurrentRange() const throw() { return visibleRange; }
  26162. /** Returns the position of the top of the thumb.
  26163. @see getCurrentRange, setCurrentRangeStart
  26164. */
  26165. double getCurrentRangeStart() const throw() { return visibleRange.getStart(); }
  26166. /** Returns the current size of the thumb.
  26167. @see getCurrentRange, setCurrentRange
  26168. */
  26169. double getCurrentRangeSize() const throw() { return visibleRange.getLength(); }
  26170. /** Sets the amount by which the up and down buttons will move the bar.
  26171. The value here is in terms of the total range, and is added or subtracted
  26172. from the thumb position when the user clicks an up/down (or left/right) button.
  26173. */
  26174. void setSingleStepSize (double newSingleStepSize);
  26175. /** Moves the scrollbar by a number of single-steps.
  26176. This will move the bar by a multiple of its single-step interval (as
  26177. specified using the setSingleStepSize() method).
  26178. A positive value here will move the bar down or to the right, a negative
  26179. value moves it up or to the left.
  26180. */
  26181. void moveScrollbarInSteps (int howManySteps);
  26182. /** Moves the scroll bar up or down in pages.
  26183. This will move the bar by a multiple of its current thumb size, effectively
  26184. doing a page-up or down.
  26185. A positive value here will move the bar down or to the right, a negative
  26186. value moves it up or to the left.
  26187. */
  26188. void moveScrollbarInPages (int howManyPages);
  26189. /** Scrolls to the top (or left).
  26190. This is the same as calling setCurrentRangeStart (getMinimumRangeLimit());
  26191. */
  26192. void scrollToTop();
  26193. /** Scrolls to the bottom (or right).
  26194. This is the same as calling setCurrentRangeStart (getMaximumRangeLimit() - getCurrentRangeSize());
  26195. */
  26196. void scrollToBottom();
  26197. /** Changes the delay before the up and down buttons autorepeat when they are held
  26198. down.
  26199. For an explanation of what the parameters are for, see Button::setRepeatSpeed().
  26200. @see Button::setRepeatSpeed
  26201. */
  26202. void setButtonRepeatSpeed (int initialDelayInMillisecs,
  26203. int repeatDelayInMillisecs,
  26204. int minimumDelayInMillisecs = -1);
  26205. /** A set of colour IDs to use to change the colour of various aspects of the component.
  26206. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26207. methods.
  26208. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26209. */
  26210. enum ColourIds
  26211. {
  26212. backgroundColourId = 0x1000300, /**< The background colour of the scrollbar. */
  26213. thumbColourId = 0x1000400, /**< A base colour to use for the thumb. The look and feel will probably use variations on this colour. */
  26214. 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. */
  26215. };
  26216. /** Registers a listener that will be called when the scrollbar is moved. */
  26217. void addListener (ScrollBarListener* listener);
  26218. /** Deregisters a previously-registered listener. */
  26219. void removeListener (ScrollBarListener* listener);
  26220. /** @internal */
  26221. bool keyPressed (const KeyPress& key);
  26222. /** @internal */
  26223. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26224. /** @internal */
  26225. void lookAndFeelChanged();
  26226. /** @internal */
  26227. void handleAsyncUpdate();
  26228. /** @internal */
  26229. void mouseDown (const MouseEvent& e);
  26230. /** @internal */
  26231. void mouseDrag (const MouseEvent& e);
  26232. /** @internal */
  26233. void mouseUp (const MouseEvent& e);
  26234. /** @internal */
  26235. void paint (Graphics& g);
  26236. /** @internal */
  26237. void resized();
  26238. juce_UseDebuggingNewOperator
  26239. private:
  26240. Range <double> totalRange, visibleRange;
  26241. double singleStepSize, dragStartRange;
  26242. int thumbAreaStart, thumbAreaSize, thumbStart, thumbSize;
  26243. int dragStartMousePos, lastMousePos;
  26244. int initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs;
  26245. bool vertical, isDraggingThumb, autohides;
  26246. class ScrollbarButton;
  26247. friend class ScopedPointer<ScrollbarButton>;
  26248. ScopedPointer<ScrollbarButton> upButton, downButton;
  26249. ListenerList <ScrollBarListener> listeners;
  26250. void updateThumbPosition();
  26251. void timerCallback();
  26252. ScrollBar (const ScrollBar&);
  26253. ScrollBar& operator= (const ScrollBar&);
  26254. };
  26255. #endif // __JUCE_SCROLLBAR_JUCEHEADER__
  26256. /*** End of inlined file: juce_ScrollBar.h ***/
  26257. /**
  26258. A Viewport is used to contain a larger child component, and allows the child
  26259. to be automatically scrolled around.
  26260. To use a Viewport, just create one and set the component that goes inside it
  26261. using the setViewedComponent() method. When the child component changes size,
  26262. the Viewport will adjust its scrollbars accordingly.
  26263. A subclass of the viewport can be created which will receive calls to its
  26264. visibleAreaChanged() method when the subcomponent changes position or size.
  26265. */
  26266. class JUCE_API Viewport : public Component,
  26267. private ComponentListener,
  26268. private ScrollBarListener
  26269. {
  26270. public:
  26271. /** Creates a Viewport.
  26272. The viewport is initially empty - use the setViewedComponent() method to
  26273. add a child component for it to manage.
  26274. */
  26275. explicit Viewport (const String& componentName = String::empty);
  26276. /** Destructor. */
  26277. ~Viewport();
  26278. /** Sets the component that this viewport will contain and scroll around.
  26279. This will add the given component to this Viewport and position it at
  26280. (0, 0).
  26281. (Don't add or remove any child components directly using the normal
  26282. Component::addChildComponent() methods).
  26283. @param newViewedComponent the component to add to this viewport (this pointer
  26284. may be null). The component passed in will be deleted
  26285. by the Viewport when it's no longer needed
  26286. @see getViewedComponent
  26287. */
  26288. void setViewedComponent (Component* newViewedComponent);
  26289. /** Returns the component that's currently being used inside the Viewport.
  26290. @see setViewedComponent
  26291. */
  26292. Component* getViewedComponent() const throw() { return contentComp; }
  26293. /** Changes the position of the viewed component.
  26294. The inner component will be moved so that the pixel at the top left of
  26295. the viewport will be the pixel at position (xPixelsOffset, yPixelsOffset)
  26296. within the inner component.
  26297. This will update the scrollbars and might cause a call to visibleAreaChanged().
  26298. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  26299. */
  26300. void setViewPosition (int xPixelsOffset, int yPixelsOffset);
  26301. /** Changes the position of the viewed component.
  26302. The inner component will be moved so that the pixel at the top left of
  26303. the viewport will be the pixel at the specified coordinates within the
  26304. inner component.
  26305. This will update the scrollbars and might cause a call to visibleAreaChanged().
  26306. @see getViewPositionX, getViewPositionY, setViewPositionProportionately
  26307. */
  26308. void setViewPosition (const Point<int>& newPosition);
  26309. /** Changes the view position as a proportion of the distance it can move.
  26310. The values here are from 0.0 to 1.0 - where (0, 0) would put the
  26311. visible area in the top-left, and (1, 1) would put it as far down and
  26312. to the right as it's possible to go whilst keeping the child component
  26313. on-screen.
  26314. */
  26315. void setViewPositionProportionately (double proportionX, double proportionY);
  26316. /** If the specified position is at the edges of the viewport, this method scrolls
  26317. the viewport to bring that position nearer to the centre.
  26318. Call this if you're dragging an object inside a viewport and want to make it scroll
  26319. when the user approaches an edge. You might also find Component::beginDragAutoRepeat()
  26320. useful when auto-scrolling.
  26321. @param mouseX the x position, relative to the Viewport's top-left
  26322. @param mouseY the y position, relative to the Viewport's top-left
  26323. @param distanceFromEdge specifies how close to an edge the position needs to be
  26324. before the viewport should scroll in that direction
  26325. @param maximumSpeed the maximum number of pixels that the viewport is allowed
  26326. to scroll by.
  26327. @returns true if the viewport was scrolled
  26328. */
  26329. bool autoScroll (int mouseX, int mouseY, int distanceFromEdge, int maximumSpeed);
  26330. /** Returns the position within the child component of the top-left of its visible area.
  26331. */
  26332. const Point<int> getViewPosition() const throw() { return lastVisibleArea.getPosition(); }
  26333. /** Returns the position within the child component of the top-left of its visible area.
  26334. @see getViewWidth, setViewPosition
  26335. */
  26336. int getViewPositionX() const throw() { return lastVisibleArea.getX(); }
  26337. /** Returns the position within the child component of the top-left of its visible area.
  26338. @see getViewHeight, setViewPosition
  26339. */
  26340. int getViewPositionY() const throw() { return lastVisibleArea.getY(); }
  26341. /** Returns the width of the visible area of the child component.
  26342. This may be less than the width of this Viewport if there's a vertical scrollbar
  26343. or if the child component is itself smaller.
  26344. */
  26345. int getViewWidth() const throw() { return lastVisibleArea.getWidth(); }
  26346. /** Returns the height of the visible area of the child component.
  26347. This may be less than the height of this Viewport if there's a horizontal scrollbar
  26348. or if the child component is itself smaller.
  26349. */
  26350. int getViewHeight() const throw() { return lastVisibleArea.getHeight(); }
  26351. /** Returns the width available within this component for the contents.
  26352. This will be the width of the viewport component minus the width of a
  26353. vertical scrollbar (if visible).
  26354. */
  26355. int getMaximumVisibleWidth() const;
  26356. /** Returns the height available within this component for the contents.
  26357. This will be the height of the viewport component minus the space taken up
  26358. by a horizontal scrollbar (if visible).
  26359. */
  26360. int getMaximumVisibleHeight() const;
  26361. /** Callback method that is called when the visible area changes.
  26362. This will be called when the visible area is moved either be scrolling or
  26363. by calls to setViewPosition(), etc.
  26364. */
  26365. virtual void visibleAreaChanged (int visibleX, int visibleY,
  26366. int visibleW, int visibleH);
  26367. /** Turns scrollbars on or off.
  26368. If set to false, the scrollbars won't ever appear. When true (the default)
  26369. they will appear only when needed.
  26370. */
  26371. void setScrollBarsShown (bool showVerticalScrollbarIfNeeded,
  26372. bool showHorizontalScrollbarIfNeeded);
  26373. /** True if the vertical scrollbar is enabled.
  26374. @see setScrollBarsShown
  26375. */
  26376. bool isVerticalScrollBarShown() const throw() { return showVScrollbar; }
  26377. /** True if the horizontal scrollbar is enabled.
  26378. @see setScrollBarsShown
  26379. */
  26380. bool isHorizontalScrollBarShown() const throw() { return showHScrollbar; }
  26381. /** Changes the width of the scrollbars.
  26382. If this isn't specified, the default width from the LookAndFeel class will be used.
  26383. @see LookAndFeel::getDefaultScrollbarWidth
  26384. */
  26385. void setScrollBarThickness (int thickness);
  26386. /** Returns the thickness of the scrollbars.
  26387. @see setScrollBarThickness
  26388. */
  26389. int getScrollBarThickness() const;
  26390. /** Changes the distance that a single-step click on a scrollbar button
  26391. will move the viewport.
  26392. */
  26393. void setSingleStepSizes (int stepX, int stepY);
  26394. /** Shows or hides the buttons on any scrollbars that are used.
  26395. @see ScrollBar::setButtonVisibility
  26396. */
  26397. void setScrollBarButtonVisibility (bool buttonsVisible);
  26398. /** Returns a pointer to the scrollbar component being used.
  26399. Handy if you need to customise the bar somehow.
  26400. */
  26401. ScrollBar* getVerticalScrollBar() throw() { return &verticalScrollBar; }
  26402. /** Returns a pointer to the scrollbar component being used.
  26403. Handy if you need to customise the bar somehow.
  26404. */
  26405. ScrollBar* getHorizontalScrollBar() throw() { return &horizontalScrollBar; }
  26406. juce_UseDebuggingNewOperator
  26407. /** @internal */
  26408. void resized();
  26409. /** @internal */
  26410. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  26411. /** @internal */
  26412. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26413. /** @internal */
  26414. bool keyPressed (const KeyPress& key);
  26415. /** @internal */
  26416. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  26417. /** @internal */
  26418. bool useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  26419. private:
  26420. Component::SafePointer<Component> contentComp;
  26421. Rectangle<int> lastVisibleArea;
  26422. int scrollBarThickness;
  26423. int singleStepX, singleStepY;
  26424. bool showHScrollbar, showVScrollbar;
  26425. Component contentHolder;
  26426. ScrollBar verticalScrollBar;
  26427. ScrollBar horizontalScrollBar;
  26428. void updateVisibleArea();
  26429. Viewport (const Viewport&);
  26430. Viewport& operator= (const Viewport&);
  26431. };
  26432. #endif // __JUCE_VIEWPORT_JUCEHEADER__
  26433. /*** End of inlined file: juce_Viewport.h ***/
  26434. /*** Start of inlined file: juce_PopupMenu.h ***/
  26435. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  26436. #define __JUCE_POPUPMENU_JUCEHEADER__
  26437. class PopupMenuCustomComponent;
  26438. /** Creates and displays a popup-menu.
  26439. To show a popup-menu, you create one of these, add some items to it, then
  26440. call its show() method, which returns the id of the item the user selects.
  26441. E.g. @code
  26442. void MyWidget::mouseDown (const MouseEvent& e)
  26443. {
  26444. PopupMenu m;
  26445. m.addItem (1, "item 1");
  26446. m.addItem (2, "item 2");
  26447. const int result = m.show();
  26448. if (result == 0)
  26449. {
  26450. // user dismissed the menu without picking anything
  26451. }
  26452. else if (result == 1)
  26453. {
  26454. // user picked item 1
  26455. }
  26456. else if (result == 2)
  26457. {
  26458. // user picked item 2
  26459. }
  26460. }
  26461. @endcode
  26462. Submenus are easy too: @code
  26463. void MyWidget::mouseDown (const MouseEvent& e)
  26464. {
  26465. PopupMenu subMenu;
  26466. subMenu.addItem (1, "item 1");
  26467. subMenu.addItem (2, "item 2");
  26468. PopupMenu mainMenu;
  26469. mainMenu.addItem (3, "item 3");
  26470. mainMenu.addSubMenu ("other choices", subMenu);
  26471. const int result = m.show();
  26472. ...etc
  26473. }
  26474. @endcode
  26475. */
  26476. class JUCE_API PopupMenu
  26477. {
  26478. public:
  26479. /** Creates an empty popup menu. */
  26480. PopupMenu();
  26481. /** Creates a copy of another menu. */
  26482. PopupMenu (const PopupMenu& other);
  26483. /** Destructor. */
  26484. ~PopupMenu();
  26485. /** Copies this menu from another one. */
  26486. PopupMenu& operator= (const PopupMenu& other);
  26487. /** Resets the menu, removing all its items. */
  26488. void clear();
  26489. /** Appends a new text item for this menu to show.
  26490. @param itemResultId the number that will be returned from the show() method
  26491. if the user picks this item. The value should never be
  26492. zero, because that's used to indicate that the user didn't
  26493. select anything.
  26494. @param itemText the text to show.
  26495. @param isActive if false, the item will be shown 'greyed-out' and can't be
  26496. picked
  26497. @param isTicked if true, the item will be shown with a tick next to it
  26498. @param iconToUse if this is non-zero, it should be an image that will be
  26499. displayed to the left of the item. This method will take its
  26500. own copy of the image passed-in, so there's no need to keep
  26501. it hanging around.
  26502. @see addSeparator, addColouredItem, addCustomItem, addSubMenu
  26503. */
  26504. void addItem (int itemResultId,
  26505. const String& itemText,
  26506. bool isActive = true,
  26507. bool isTicked = false,
  26508. const Image& iconToUse = Image());
  26509. /** Adds an item that represents one of the commands in a command manager object.
  26510. @param commandManager the manager to use to trigger the command and get information
  26511. about it
  26512. @param commandID the ID of the command
  26513. @param displayName if this is non-empty, then this string will be used instead of
  26514. the command's registered name
  26515. */
  26516. void addCommandItem (ApplicationCommandManager* commandManager,
  26517. int commandID,
  26518. const String& displayName = String::empty);
  26519. /** Appends a text item with a special colour.
  26520. This is the same as addItem(), but specifies a colour to use for the
  26521. text, which will override the default colours that are used by the
  26522. current look-and-feel. See addItem() for a description of the parameters.
  26523. */
  26524. void addColouredItem (int itemResultId,
  26525. const String& itemText,
  26526. const Colour& itemTextColour,
  26527. bool isActive = true,
  26528. bool isTicked = false,
  26529. const Image& iconToUse = Image());
  26530. /** Appends a custom menu item.
  26531. This will add a user-defined component to use as a menu item. The component
  26532. passed in will be deleted by this menu when it's no longer needed.
  26533. @see PopupMenuCustomComponent
  26534. */
  26535. void addCustomItem (int itemResultId, PopupMenuCustomComponent* customComponent);
  26536. /** Appends a custom menu item that can't be used to trigger a result.
  26537. This will add a user-defined component to use as a menu item. Unlike the
  26538. addCustomItem() method that takes a PopupMenuCustomComponent, this version
  26539. can't trigger a result from it, so doesn't take a menu ID. It also doesn't
  26540. delete the component when it's finished, so it's the caller's responsibility
  26541. to manage the component that is passed-in.
  26542. if triggerMenuItemAutomaticallyWhenClicked is true, the menu itself will handle
  26543. detection of a mouse-click on your component, and use that to trigger the
  26544. menu ID specified in itemResultId. If this is false, the menu item can't
  26545. be triggered, so itemResultId is not used.
  26546. @see PopupMenuCustomComponent
  26547. */
  26548. void addCustomItem (int itemResultId,
  26549. Component* customComponent,
  26550. int idealWidth, int idealHeight,
  26551. bool triggerMenuItemAutomaticallyWhenClicked);
  26552. /** Appends a sub-menu.
  26553. If the menu that's passed in is empty, it will appear as an inactive item.
  26554. */
  26555. void addSubMenu (const String& subMenuName,
  26556. const PopupMenu& subMenu,
  26557. bool isActive = true,
  26558. const Image& iconToUse = Image(),
  26559. bool isTicked = false);
  26560. /** Appends a separator to the menu, to help break it up into sections.
  26561. The menu class is smart enough not to display separators at the top or bottom
  26562. of the menu, and it will replace mutliple adjacent separators with a single
  26563. one, so your code can be quite free and easy about adding these, and it'll
  26564. always look ok.
  26565. */
  26566. void addSeparator();
  26567. /** Adds a non-clickable text item to the menu.
  26568. This is a bold-font items which can be used as a header to separate the items
  26569. into named groups.
  26570. */
  26571. void addSectionHeader (const String& title);
  26572. /** Returns the number of items that the menu currently contains.
  26573. (This doesn't count separators).
  26574. */
  26575. int getNumItems() const throw();
  26576. /** Returns true if the menu contains a command item that triggers the given command. */
  26577. bool containsCommandItem (int commandID) const;
  26578. /** Returns true if the menu contains any items that can be used. */
  26579. bool containsAnyActiveItems() const throw();
  26580. /** Displays the menu and waits for the user to pick something.
  26581. This will display the menu modally, and return the ID of the item that the
  26582. user picks. If they click somewhere off the menu to get rid of it without
  26583. choosing anything, this will return 0.
  26584. The current location of the mouse will be used as the position to show the
  26585. menu - to explicitly set the menu's position, use showAt() instead. Depending
  26586. on where this point is on the screen, the menu will appear above, below or
  26587. to the side of the point.
  26588. @param itemIdThatMustBeVisible if you set this to the ID of one of the menu items,
  26589. then when the menu first appears, it will make sure
  26590. that this item is visible. So if the menu has too many
  26591. items to fit on the screen, it will be scrolled to a
  26592. position where this item is visible.
  26593. @param minimumWidth a minimum width for the menu, in pixels. It may be wider
  26594. than this if some items are too long to fit.
  26595. @param maximumNumColumns if there are too many items to fit on-screen in a single
  26596. vertical column, the menu may be laid out as a series of
  26597. columns - this is the maximum number allowed. To use the
  26598. default value for this (probably about 7), you can pass
  26599. in zero.
  26600. @param standardItemHeight if this is non-zero, it will be used as the standard
  26601. height for menu items (apart from custom items)
  26602. @param callback if this is non-zero, the menu will be launched asynchronously,
  26603. returning immediately, and the callback will receive a
  26604. call when the menu is either dismissed or has an item
  26605. selected. This object will be owned and deleted by the
  26606. system, so make sure that it works safely and that any
  26607. pointers that it uses are safely within scope.
  26608. @see showAt
  26609. */
  26610. int show (int itemIdThatMustBeVisible = 0,
  26611. int minimumWidth = 0,
  26612. int maximumNumColumns = 0,
  26613. int standardItemHeight = 0,
  26614. ModalComponentManager::Callback* callback = 0);
  26615. /** Displays the menu at a specific location.
  26616. This is the same as show(), but uses a specific location (in global screen
  26617. co-ordinates) rather than the current mouse position.
  26618. Note that the co-ordinates don't specify the top-left of the menu - they
  26619. indicate a point of interest, and the menu will position itself nearby to
  26620. this point, trying to keep it fully on-screen.
  26621. @see show()
  26622. */
  26623. int showAt (int screenX,
  26624. int screenY,
  26625. int itemIdThatMustBeVisible = 0,
  26626. int minimumWidth = 0,
  26627. int maximumNumColumns = 0,
  26628. int standardItemHeight = 0,
  26629. ModalComponentManager::Callback* callback = 0);
  26630. /** Displays the menu as if it's attached to a component such as a button.
  26631. This is similar to showAt(), but will position it next to the given component, e.g.
  26632. so that the menu's edge is aligned with that of the component. This is intended for
  26633. things like buttons that trigger a pop-up menu.
  26634. */
  26635. int showAt (Component* componentToAttachTo,
  26636. int itemIdThatMustBeVisible = 0,
  26637. int minimumWidth = 0,
  26638. int maximumNumColumns = 0,
  26639. int standardItemHeight = 0,
  26640. ModalComponentManager::Callback* callback = 0);
  26641. /** Closes any menus that are currently open.
  26642. This might be useful if you have a situation where your window is being closed
  26643. by some means other than a user action, and you'd like to make sure that menus
  26644. aren't left hanging around.
  26645. */
  26646. static void JUCE_CALLTYPE dismissAllActiveMenus();
  26647. /** Specifies a look-and-feel for the menu and any sub-menus that it has.
  26648. This can be called before show() if you need a customised menu. Be careful
  26649. not to delete the LookAndFeel object before the menu has been deleted.
  26650. */
  26651. void setLookAndFeel (LookAndFeel* newLookAndFeel);
  26652. /** A set of colour IDs to use to change the colour of various aspects of the menu.
  26653. These constants can be used either via the LookAndFeel::setColour()
  26654. method for the look and feel that is set for this menu with setLookAndFeel()
  26655. @see setLookAndFeel, LookAndFeel::setColour, LookAndFeel::findColour
  26656. */
  26657. enum ColourIds
  26658. {
  26659. backgroundColourId = 0x1000700, /**< The colour to fill the menu's background with. */
  26660. textColourId = 0x1000600, /**< The colour for normal menu item text, (unless the
  26661. colour is specified when the item is added). */
  26662. headerTextColourId = 0x1000601, /**< The colour for section header item text (see the
  26663. addSectionHeader() method). */
  26664. highlightedBackgroundColourId = 0x1000900, /**< The colour to fill the background of the currently
  26665. highlighted menu item. */
  26666. highlightedTextColourId = 0x1000800, /**< The colour to use for the text of the currently
  26667. highlighted item. */
  26668. };
  26669. /**
  26670. Allows you to iterate through the items in a pop-up menu, and examine
  26671. their properties.
  26672. To use this, just create one and repeatedly call its next() method. When this
  26673. returns true, all the member variables of the iterator are filled-out with
  26674. information describing the menu item. When it returns false, the end of the
  26675. list has been reached.
  26676. */
  26677. class JUCE_API MenuItemIterator
  26678. {
  26679. public:
  26680. /** Creates an iterator that will scan through the items in the specified
  26681. menu.
  26682. Be careful not to add any items to a menu while it is being iterated,
  26683. or things could get out of step.
  26684. */
  26685. MenuItemIterator (const PopupMenu& menu);
  26686. /** Destructor. */
  26687. ~MenuItemIterator();
  26688. /** Returns true if there is another item, and sets up all this object's
  26689. member variables to reflect that item's properties.
  26690. */
  26691. bool next();
  26692. String itemName;
  26693. const PopupMenu* subMenu;
  26694. int itemId;
  26695. bool isSeparator;
  26696. bool isTicked;
  26697. bool isEnabled;
  26698. bool isCustomComponent;
  26699. bool isSectionHeader;
  26700. const Colour* customColour;
  26701. Image customImage;
  26702. ApplicationCommandManager* commandManager;
  26703. juce_UseDebuggingNewOperator
  26704. private:
  26705. const PopupMenu& menu;
  26706. int index;
  26707. MenuItemIterator (const MenuItemIterator&);
  26708. MenuItemIterator& operator= (const MenuItemIterator&);
  26709. };
  26710. juce_UseDebuggingNewOperator
  26711. private:
  26712. class Item;
  26713. class ItemComponent;
  26714. class Window;
  26715. friend class MenuItemIterator;
  26716. friend class ItemComponent;
  26717. friend class Window;
  26718. friend class PopupMenuCustomComponent;
  26719. friend class MenuBarComponent;
  26720. friend class OwnedArray <Item>;
  26721. friend class ScopedPointer <Window>;
  26722. OwnedArray <Item> items;
  26723. LookAndFeel* lookAndFeel;
  26724. bool separatorPending;
  26725. void addSeparatorIfPending();
  26726. int showMenu (const Rectangle<int>& target,
  26727. int itemIdThatMustBeVisible,
  26728. int minimumWidth,
  26729. int maximumNumColumns,
  26730. int standardItemHeight,
  26731. bool alignToRectangle,
  26732. Component* componentAttachedTo,
  26733. ModalComponentManager::Callback* callback);
  26734. };
  26735. #endif // __JUCE_POPUPMENU_JUCEHEADER__
  26736. /*** End of inlined file: juce_PopupMenu.h ***/
  26737. /*** Start of inlined file: juce_TextInputTarget.h ***/
  26738. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26739. #define __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26740. /** An abstract base class that is implemented by components that wish to be used
  26741. as text editors.
  26742. This class allows different types of text editor component to provide a uniform
  26743. interface, which can be used by things like OS-specific input methods, on-screen
  26744. keyboards, etc.
  26745. */
  26746. class JUCE_API TextInputTarget
  26747. {
  26748. public:
  26749. /** */
  26750. TextInputTarget() {}
  26751. /** Destructor. */
  26752. virtual ~TextInputTarget() {}
  26753. /** Returns true if this input target is currently accepting input.
  26754. For example, a text editor might return false if it's in read-only mode.
  26755. */
  26756. virtual bool isTextInputActive() const = 0;
  26757. /** Returns the extents of the selected text region, or an empty range if
  26758. nothing is selected,
  26759. */
  26760. virtual const Range<int> getHighlightedRegion() const = 0;
  26761. /** Sets the currently-selected text region.
  26762. */
  26763. virtual void setHighlightedRegion (const Range<int>& newRange) = 0;
  26764. /** Returns a specified sub-section of the text.
  26765. */
  26766. virtual const String getTextInRange (const Range<int>& range) const = 0;
  26767. /** Inserts some text, overwriting the selected text region, if there is one. */
  26768. virtual void insertTextAtCaret (const String& textToInsert) = 0;
  26769. };
  26770. #endif // __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  26771. /*** End of inlined file: juce_TextInputTarget.h ***/
  26772. class TextEditor;
  26773. /**
  26774. Receives callbacks from a TextEditor component when it changes.
  26775. @see TextEditor::addListener
  26776. */
  26777. class JUCE_API TextEditorListener
  26778. {
  26779. public:
  26780. /** Destructor. */
  26781. virtual ~TextEditorListener() {}
  26782. /** Called when the user changes the text in some way. */
  26783. virtual void textEditorTextChanged (TextEditor& editor) = 0;
  26784. /** Called when the user presses the return key. */
  26785. virtual void textEditorReturnKeyPressed (TextEditor& editor) = 0;
  26786. /** Called when the user presses the escape key. */
  26787. virtual void textEditorEscapeKeyPressed (TextEditor& editor) = 0;
  26788. /** Called when the text editor loses focus. */
  26789. virtual void textEditorFocusLost (TextEditor& editor) = 0;
  26790. };
  26791. /**
  26792. A component containing text that can be edited.
  26793. A TextEditor can either be in single- or multi-line mode, and supports mixed
  26794. fonts and colours.
  26795. @see TextEditorListener, Label
  26796. */
  26797. class JUCE_API TextEditor : public Component,
  26798. public TextInputTarget,
  26799. public SettableTooltipClient
  26800. {
  26801. public:
  26802. /** Creates a new, empty text editor.
  26803. @param componentName the name to pass to the component for it to use as its name
  26804. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26805. for all characters that are drawn on screen - e.g. to create
  26806. a password-style textbox containing circular blobs instead of text,
  26807. you could set this value to 0x25cf, which is the unicode character
  26808. for a black splodge (not all fonts include this, though), or 0x2022,
  26809. which is a bullet (probably the best choice for linux).
  26810. */
  26811. explicit TextEditor (const String& componentName = String::empty,
  26812. juce_wchar passwordCharacter = 0);
  26813. /** Destructor. */
  26814. virtual ~TextEditor();
  26815. /** Puts the editor into either multi- or single-line mode.
  26816. By default, the editor will be in single-line mode, so use this if you need a multi-line
  26817. editor.
  26818. See also the setReturnKeyStartsNewLine() method, which will also need to be turned
  26819. on if you want a multi-line editor with line-breaks.
  26820. @see isMultiLine, setReturnKeyStartsNewLine
  26821. */
  26822. void setMultiLine (bool shouldBeMultiLine,
  26823. bool shouldWordWrap = true);
  26824. /** Returns true if the editor is in multi-line mode.
  26825. */
  26826. bool isMultiLine() const;
  26827. /** Changes the behaviour of the return key.
  26828. If set to true, the return key will insert a new-line into the text; if false
  26829. it will trigger a call to the TextEditorListener::textEditorReturnKeyPressed()
  26830. method. By default this is set to false, and when true it will only insert
  26831. new-lines when in multi-line mode (see setMultiLine()).
  26832. */
  26833. void setReturnKeyStartsNewLine (bool shouldStartNewLine);
  26834. /** Returns the value set by setReturnKeyStartsNewLine().
  26835. See setReturnKeyStartsNewLine() for more info.
  26836. */
  26837. bool getReturnKeyStartsNewLine() const { return returnKeyStartsNewLine; }
  26838. /** Indicates whether the tab key should be accepted and used to input a tab character,
  26839. or whether it gets ignored.
  26840. By default the tab key is ignored, so that it can be used to switch keyboard focus
  26841. between components.
  26842. */
  26843. void setTabKeyUsedAsCharacter (bool shouldTabKeyBeUsed);
  26844. /** Returns true if the tab key is being used for input.
  26845. @see setTabKeyUsedAsCharacter
  26846. */
  26847. bool isTabKeyUsedAsCharacter() const { return tabKeyUsed; }
  26848. /** Changes the editor to read-only mode.
  26849. By default, the text editor is not read-only. If you're making it read-only, you
  26850. might also want to call setCaretVisible (false) to get rid of the caret.
  26851. The text can still be highlighted and copied when in read-only mode.
  26852. @see isReadOnly, setCaretVisible
  26853. */
  26854. void setReadOnly (bool shouldBeReadOnly);
  26855. /** Returns true if the editor is in read-only mode.
  26856. */
  26857. bool isReadOnly() const;
  26858. /** Makes the caret visible or invisible.
  26859. By default the caret is visible.
  26860. @see setCaretColour, setCaretPosition
  26861. */
  26862. void setCaretVisible (bool shouldBeVisible);
  26863. /** Returns true if the caret is enabled.
  26864. @see setCaretVisible
  26865. */
  26866. bool isCaretVisible() const { return caretVisible; }
  26867. /** Enables/disables a vertical scrollbar.
  26868. (This only applies when in multi-line mode). When the text gets too long to fit
  26869. in the component, a scrollbar can appear to allow it to be scrolled. Even when
  26870. this is enabled, the scrollbar will be hidden unless it's needed.
  26871. By default the scrollbar is enabled.
  26872. */
  26873. void setScrollbarsShown (bool shouldBeEnabled);
  26874. /** Returns true if scrollbars are enabled.
  26875. @see setScrollbarsShown
  26876. */
  26877. bool areScrollbarsShown() const { return scrollbarVisible; }
  26878. /** Changes the password character used to disguise the text.
  26879. @param passwordCharacter if this is not zero, this character will be used as a replacement
  26880. for all characters that are drawn on screen - e.g. to create
  26881. a password-style textbox containing circular blobs instead of text,
  26882. you could set this value to 0x25cf, which is the unicode character
  26883. for a black splodge (not all fonts include this, though), or 0x2022,
  26884. which is a bullet (probably the best choice for linux).
  26885. */
  26886. void setPasswordCharacter (juce_wchar passwordCharacter);
  26887. /** Returns the current password character.
  26888. @see setPasswordCharacter
  26889. */
  26890. juce_wchar getPasswordCharacter() const { return passwordCharacter; }
  26891. /** Allows a right-click menu to appear for the editor.
  26892. (This defaults to being enabled).
  26893. If enabled, right-clicking (or command-clicking on the Mac) will pop up a menu
  26894. of options such as cut/copy/paste, undo/redo, etc.
  26895. */
  26896. void setPopupMenuEnabled (bool menuEnabled);
  26897. /** Returns true if the right-click menu is enabled.
  26898. @see setPopupMenuEnabled
  26899. */
  26900. bool isPopupMenuEnabled() const { return popupMenuEnabled; }
  26901. /** Returns true if a popup-menu is currently being displayed.
  26902. */
  26903. bool isPopupMenuCurrentlyActive() const { return menuActive; }
  26904. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  26905. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  26906. methods.
  26907. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  26908. */
  26909. enum ColourIds
  26910. {
  26911. backgroundColourId = 0x1000200, /**< The colour to use for the text component's background - this can be
  26912. transparent if necessary. */
  26913. textColourId = 0x1000201, /**< The colour that will be used when text is added to the editor. Note
  26914. that because the editor can contain multiple colours, calling this
  26915. method won't change the colour of existing text - to do that, call
  26916. applyFontToAllText() after calling this method.*/
  26917. highlightColourId = 0x1000202, /**< The colour with which to fill the background of highlighted sections of
  26918. the text - this can be transparent if you don't want to show any
  26919. highlighting.*/
  26920. highlightedTextColourId = 0x1000203, /**< The colour with which to draw the text in highlighted sections. */
  26921. caretColourId = 0x1000204, /**< The colour with which to draw the caret. */
  26922. outlineColourId = 0x1000205, /**< If this is non-transparent, it will be used to draw a box around
  26923. the edge of the component. */
  26924. focusedOutlineColourId = 0x1000206, /**< If this is non-transparent, it will be used to draw a box around
  26925. the edge of the component when it has focus. */
  26926. shadowColourId = 0x1000207, /**< If this is non-transparent, it'll be used to draw an inner shadow
  26927. around the edge of the editor. */
  26928. };
  26929. /** Sets the font to use for newly added text.
  26930. This will change the font that will be used next time any text is added or entered
  26931. into the editor. It won't change the font of any existing text - to do that, use
  26932. applyFontToAllText() instead.
  26933. @see applyFontToAllText
  26934. */
  26935. void setFont (const Font& newFont);
  26936. /** Applies a font to all the text in the editor.
  26937. This will also set the current font to use for any new text that's added.
  26938. @see setFont
  26939. */
  26940. void applyFontToAllText (const Font& newFont);
  26941. /** Returns the font that's currently being used for new text.
  26942. @see setFont
  26943. */
  26944. const Font getFont() const;
  26945. /** If set to true, focusing on the editor will highlight all its text.
  26946. (Set to false by default).
  26947. This is useful for boxes where you expect the user to re-enter all the
  26948. text when they focus on the component, rather than editing what's already there.
  26949. */
  26950. void setSelectAllWhenFocused (bool b);
  26951. /** Sets limits on the characters that can be entered.
  26952. @param maxTextLength if this is > 0, it sets a maximum length limit; if 0, no
  26953. limit is set
  26954. @param allowedCharacters if this is non-empty, then only characters that occur in
  26955. this string are allowed to be entered into the editor.
  26956. */
  26957. void setInputRestrictions (int maxTextLength,
  26958. const String& allowedCharacters = String::empty);
  26959. /** When the text editor is empty, it can be set to display a message.
  26960. This is handy for things like telling the user what to type in the box - the
  26961. string is only displayed, it's not taken to actually be the contents of
  26962. the editor.
  26963. */
  26964. void setTextToShowWhenEmpty (const String& text, const Colour& colourToUse);
  26965. /** Changes the size of the scrollbars that are used.
  26966. Handy if you need smaller scrollbars for a small text box.
  26967. */
  26968. void setScrollBarThickness (int newThicknessPixels);
  26969. /** Shows or hides the buttons on any scrollbars that are used.
  26970. @see ScrollBar::setButtonVisibility
  26971. */
  26972. void setScrollBarButtonVisibility (bool buttonsVisible);
  26973. /** Registers a listener to be told when things happen to the text.
  26974. @see removeListener
  26975. */
  26976. void addListener (TextEditorListener* newListener);
  26977. /** Deregisters a listener.
  26978. @see addListener
  26979. */
  26980. void removeListener (TextEditorListener* listenerToRemove);
  26981. /** Returns the entire contents of the editor. */
  26982. const String getText() const;
  26983. /** Returns a section of the contents of the editor. */
  26984. const String getTextInRange (const Range<int>& textRange) const;
  26985. /** Returns true if there are no characters in the editor.
  26986. This is more efficient than calling getText().isEmpty().
  26987. */
  26988. bool isEmpty() const;
  26989. /** Sets the entire content of the editor.
  26990. This will clear the editor and insert the given text (using the current text colour
  26991. and font). You can set the current text colour using
  26992. @code setColour (TextEditor::textColourId, ...);
  26993. @endcode
  26994. @param newText the text to add
  26995. @param sendTextChangeMessage if true, this will cause a change message to
  26996. be sent to all the listeners.
  26997. @see insertText
  26998. */
  26999. void setText (const String& newText,
  27000. bool sendTextChangeMessage = true);
  27001. /** Returns a Value object that can be used to get or set the text.
  27002. Bear in mind that this operate quite slowly if your text box contains large
  27003. amounts of text, as it needs to dynamically build the string that's involved. It's
  27004. best used for small text boxes.
  27005. */
  27006. Value& getTextValue();
  27007. /** Inserts some text at the current cursor position.
  27008. If a section of the text is highlighted, it will be replaced by
  27009. this string, otherwise it will be inserted.
  27010. To delete a section of text, you can use setHighlightedRegion() to
  27011. highlight it, and call insertTextAtCursor (String::empty).
  27012. @see setCaretPosition, getCaretPosition, setHighlightedRegion
  27013. */
  27014. void insertTextAtCaret (const String& textToInsert);
  27015. /** Deletes all the text from the editor. */
  27016. void clear();
  27017. /** Deletes the currently selected region, and puts it on the clipboard.
  27018. @see copy, paste, SystemClipboard
  27019. */
  27020. void cut();
  27021. /** Copies any currently selected region to the clipboard.
  27022. @see cut, paste, SystemClipboard
  27023. */
  27024. void copy();
  27025. /** Pastes the contents of the clipboard into the editor at the cursor position.
  27026. @see cut, copy, SystemClipboard
  27027. */
  27028. void paste();
  27029. /** Moves the caret to be in front of a given character.
  27030. @see getCaretPosition
  27031. */
  27032. void setCaretPosition (int newIndex);
  27033. /** Returns the current index of the caret.
  27034. @see setCaretPosition
  27035. */
  27036. int getCaretPosition() const;
  27037. /** Attempts to scroll the text editor so that the caret ends up at
  27038. a specified position.
  27039. This won't affect the caret's position within the text, it tries to scroll
  27040. the entire editor vertically and horizontally so that the caret is sitting
  27041. at the given position (relative to the top-left of this component).
  27042. Depending on the amount of text available, it might not be possible to
  27043. scroll far enough for the caret to reach this exact position, but it
  27044. will go as far as it can in that direction.
  27045. */
  27046. void scrollEditorToPositionCaret (int desiredCaretX, int desiredCaretY);
  27047. /** Get the graphical position of the caret.
  27048. The rectangle returned is relative to the component's top-left corner.
  27049. @see scrollEditorToPositionCaret
  27050. */
  27051. const Rectangle<int> getCaretRectangle();
  27052. /** Selects a section of the text. */
  27053. void setHighlightedRegion (const Range<int>& newSelection);
  27054. /** Returns the range of characters that are selected.
  27055. If nothing is selected, this will return an empty range.
  27056. @see setHighlightedRegion
  27057. */
  27058. const Range<int> getHighlightedRegion() const { return selection; }
  27059. /** Returns the section of text that is currently selected. */
  27060. const String getHighlightedText() const;
  27061. /** Finds the index of the character at a given position.
  27062. The co-ordinates are relative to the component's top-left.
  27063. */
  27064. int getTextIndexAt (int x, int y);
  27065. /** Counts the number of characters in the text.
  27066. This is quicker than getting the text as a string if you just need to know
  27067. the length.
  27068. */
  27069. int getTotalNumChars() const;
  27070. /** Returns the total width of the text, as it is currently laid-out.
  27071. This may be larger than the size of the TextEditor, and can change when
  27072. the TextEditor is resized or the text changes.
  27073. */
  27074. int getTextWidth() const;
  27075. /** Returns the maximum height of the text, as it is currently laid-out.
  27076. This may be larger than the size of the TextEditor, and can change when
  27077. the TextEditor is resized or the text changes.
  27078. */
  27079. int getTextHeight() const;
  27080. /** Changes the size of the gap at the top and left-edge of the editor.
  27081. By default there's a gap of 4 pixels.
  27082. */
  27083. void setIndents (int newLeftIndent, int newTopIndent);
  27084. /** Changes the size of border left around the edge of the component.
  27085. @see getBorder
  27086. */
  27087. void setBorder (const BorderSize& border);
  27088. /** Returns the size of border around the edge of the component.
  27089. @see setBorder
  27090. */
  27091. const BorderSize getBorder() const;
  27092. /** Used to disable the auto-scrolling which keeps the cursor visible.
  27093. If true (the default), the editor will scroll when the cursor moves offscreen. If
  27094. set to false, it won't.
  27095. */
  27096. void setScrollToShowCursor (bool shouldScrollToShowCursor);
  27097. /** @internal */
  27098. void paint (Graphics& g);
  27099. /** @internal */
  27100. void paintOverChildren (Graphics& g);
  27101. /** @internal */
  27102. void mouseDown (const MouseEvent& e);
  27103. /** @internal */
  27104. void mouseUp (const MouseEvent& e);
  27105. /** @internal */
  27106. void mouseDrag (const MouseEvent& e);
  27107. /** @internal */
  27108. void mouseDoubleClick (const MouseEvent& e);
  27109. /** @internal */
  27110. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  27111. /** @internal */
  27112. bool keyPressed (const KeyPress& key);
  27113. /** @internal */
  27114. bool keyStateChanged (bool isKeyDown);
  27115. /** @internal */
  27116. void focusGained (FocusChangeType cause);
  27117. /** @internal */
  27118. void focusLost (FocusChangeType cause);
  27119. /** @internal */
  27120. void resized();
  27121. /** @internal */
  27122. void enablementChanged();
  27123. /** @internal */
  27124. void colourChanged();
  27125. /** @internal */
  27126. bool isTextInputActive() const;
  27127. /** This adds the items to the popup menu.
  27128. By default it adds the cut/copy/paste items, but you can override this if
  27129. you need to replace these with your own items.
  27130. If you want to add your own items to the existing ones, you can override this,
  27131. call the base class's addPopupMenuItems() method, then append your own items.
  27132. When the menu has been shown, performPopupMenuAction() will be called to
  27133. perform the item that the user has chosen.
  27134. The default menu items will be added using item IDs in the range
  27135. 0x7fff0000 - 0x7fff1000, so you should avoid those values for your own
  27136. menu IDs.
  27137. If this was triggered by a mouse-click, the mouseClickEvent parameter will be
  27138. a pointer to the info about it, or may be null if the menu is being triggered
  27139. by some other means.
  27140. @see performPopupMenuAction, setPopupMenuEnabled, isPopupMenuEnabled
  27141. */
  27142. virtual void addPopupMenuItems (PopupMenu& menuToAddTo,
  27143. const MouseEvent* mouseClickEvent);
  27144. /** This is called to perform one of the items that was shown on the popup menu.
  27145. If you've overridden addPopupMenuItems(), you should also override this
  27146. to perform the actions that you've added.
  27147. If you've overridden addPopupMenuItems() but have still left the default items
  27148. on the menu, remember to call the superclass's performPopupMenuAction()
  27149. so that it can perform the default actions if that's what the user clicked on.
  27150. @see addPopupMenuItems, setPopupMenuEnabled, isPopupMenuEnabled
  27151. */
  27152. virtual void performPopupMenuAction (int menuItemID);
  27153. juce_UseDebuggingNewOperator
  27154. protected:
  27155. /** Scrolls the minimum distance needed to get the caret into view. */
  27156. void scrollToMakeSureCursorIsVisible();
  27157. /** @internal */
  27158. void moveCaret (int newCaretPos);
  27159. /** @internal */
  27160. void moveCursorTo (int newPosition, bool isSelecting);
  27161. /** Used internally to dispatch a text-change message. */
  27162. void textChanged();
  27163. /** Begins a new transaction in the UndoManager.
  27164. */
  27165. void newTransaction();
  27166. /** Used internally to trigger an undo or redo. */
  27167. void doUndoRedo (bool isRedo);
  27168. /** Can be overridden to intercept return key presses directly */
  27169. virtual void returnPressed();
  27170. /** Can be overridden to intercept escape key presses directly */
  27171. virtual void escapePressed();
  27172. /** @internal */
  27173. void handleCommandMessage (int commandId);
  27174. private:
  27175. class Iterator;
  27176. class UniformTextSection;
  27177. class TextHolderComponent;
  27178. class InsertAction;
  27179. class RemoveAction;
  27180. friend class InsertAction;
  27181. friend class RemoveAction;
  27182. ScopedPointer <Viewport> viewport;
  27183. TextHolderComponent* textHolder;
  27184. BorderSize borderSize;
  27185. bool readOnly : 1;
  27186. bool multiline : 1;
  27187. bool wordWrap : 1;
  27188. bool returnKeyStartsNewLine : 1;
  27189. bool caretVisible : 1;
  27190. bool popupMenuEnabled : 1;
  27191. bool selectAllTextWhenFocused : 1;
  27192. bool scrollbarVisible : 1;
  27193. bool wasFocused : 1;
  27194. bool caretFlashState : 1;
  27195. bool keepCursorOnScreen : 1;
  27196. bool tabKeyUsed : 1;
  27197. bool menuActive : 1;
  27198. bool valueTextNeedsUpdating : 1;
  27199. UndoManager undoManager;
  27200. float cursorX, cursorY, cursorHeight;
  27201. int maxTextLength;
  27202. Range<int> selection;
  27203. int leftIndent, topIndent;
  27204. unsigned int lastTransactionTime;
  27205. Font currentFont;
  27206. mutable int totalNumChars;
  27207. int caretPosition;
  27208. Array <UniformTextSection*> sections;
  27209. String textToShowWhenEmpty;
  27210. Colour colourForTextWhenEmpty;
  27211. juce_wchar passwordCharacter;
  27212. Value textValue;
  27213. enum
  27214. {
  27215. notDragging,
  27216. draggingSelectionStart,
  27217. draggingSelectionEnd
  27218. } dragType;
  27219. String allowedCharacters;
  27220. ListenerList <TextEditorListener> listeners;
  27221. void coalesceSimilarSections();
  27222. void splitSection (int sectionIndex, int charToSplitAt);
  27223. void clearInternal (UndoManager* um);
  27224. void insert (const String& text, int insertIndex, const Font& font,
  27225. const Colour& colour, UndoManager* um, int caretPositionToMoveTo);
  27226. void reinsert (int insertIndex, const Array <UniformTextSection*>& sections);
  27227. void remove (const Range<int>& range, UndoManager* um, int caretPositionToMoveTo);
  27228. void getCharPosition (int index, float& x, float& y, float& lineHeight) const;
  27229. void updateCaretPosition();
  27230. void textWasChangedByValue();
  27231. int indexAtPosition (float x, float y);
  27232. int findWordBreakAfter (int position) const;
  27233. int findWordBreakBefore (int position) const;
  27234. friend class TextHolderComponent;
  27235. friend class TextEditorViewport;
  27236. void drawContent (Graphics& g);
  27237. void updateTextHolderSize();
  27238. float getWordWrapWidth() const;
  27239. void timerCallbackInt();
  27240. void repaintCaret();
  27241. void repaintText (const Range<int>& range);
  27242. UndoManager* getUndoManager() throw();
  27243. TextEditor (const TextEditor&);
  27244. TextEditor& operator= (const TextEditor&);
  27245. };
  27246. #endif // __JUCE_TEXTEDITOR_JUCEHEADER__
  27247. /*** End of inlined file: juce_TextEditor.h ***/
  27248. class Label;
  27249. /**
  27250. A class for receiving events from a Label.
  27251. You can register a LabelListener with a Label using the Label::addListener()
  27252. method, and it will be called when the text of the label changes, either because
  27253. of a call to Label::setText() or by the user editing the text (if the label is
  27254. editable).
  27255. @see Label::addListener, Label::removeListener
  27256. */
  27257. class JUCE_API LabelListener
  27258. {
  27259. public:
  27260. /** Destructor. */
  27261. virtual ~LabelListener() {}
  27262. /** Called when a Label's text has changed.
  27263. */
  27264. virtual void labelTextChanged (Label* labelThatHasChanged) = 0;
  27265. };
  27266. /**
  27267. A component that displays a text string, and can optionally become a text
  27268. editor when clicked.
  27269. */
  27270. class JUCE_API Label : public Component,
  27271. public SettableTooltipClient,
  27272. protected TextEditorListener,
  27273. private ComponentListener,
  27274. private Value::Listener
  27275. {
  27276. public:
  27277. /** Creates a Label.
  27278. @param componentName the name to give the component
  27279. @param labelText the text to show in the label
  27280. */
  27281. Label (const String& componentName = String::empty,
  27282. const String& labelText = String::empty);
  27283. /** Destructor. */
  27284. ~Label();
  27285. /** Changes the label text.
  27286. If broadcastChangeMessage is true and the new text is different to the current
  27287. text, then the class will broadcast a change message to any LabelListeners that
  27288. are registered.
  27289. */
  27290. void setText (const String& newText,
  27291. bool broadcastChangeMessage);
  27292. /** Returns the label's current text.
  27293. @param returnActiveEditorContents if this is true and the label is currently
  27294. being edited, then this method will return the
  27295. text as it's being shown in the editor. If false,
  27296. then the value returned here won't be updated until
  27297. the user has finished typing and pressed the return
  27298. key.
  27299. */
  27300. const String getText (bool returnActiveEditorContents = false) const throw();
  27301. /** Returns the text content as a Value object.
  27302. You can call Value::referTo() on this object to make the label read and control
  27303. a Value object that you supply.
  27304. */
  27305. Value& getTextValue() { return textValue; }
  27306. /** Changes the font to use to draw the text.
  27307. @see getFont
  27308. */
  27309. void setFont (const Font& newFont) throw();
  27310. /** Returns the font currently being used.
  27311. @see setFont
  27312. */
  27313. const Font& getFont() const throw();
  27314. /** A set of colour IDs to use to change the colour of various aspects of the label.
  27315. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27316. methods.
  27317. Note that you can also use the constants from TextEditor::ColourIds to change the
  27318. colour of the text editor that is opened when a label is editable.
  27319. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27320. */
  27321. enum ColourIds
  27322. {
  27323. backgroundColourId = 0x1000280, /**< The background colour to fill the label with. */
  27324. textColourId = 0x1000281, /**< The colour for the text. */
  27325. outlineColourId = 0x1000282 /**< An optional colour to use to draw a border around the label.
  27326. Leave this transparent to not have an outline. */
  27327. };
  27328. /** Sets the style of justification to be used for positioning the text.
  27329. (The default is Justification::centredLeft)
  27330. */
  27331. void setJustificationType (const Justification& justification) throw();
  27332. /** Returns the type of justification, as set in setJustificationType(). */
  27333. const Justification getJustificationType() const throw() { return justification; }
  27334. /** Changes the gap that is left between the edge of the component and the text.
  27335. By default there's a small gap left at the sides of the component to allow for
  27336. the drawing of the border, but you can change this if necessary.
  27337. */
  27338. void setBorderSize (int horizontalBorder, int verticalBorder);
  27339. /** Returns the size of the horizontal gap being left around the text.
  27340. */
  27341. int getHorizontalBorderSize() const throw() { return horizontalBorderSize; }
  27342. /** Returns the size of the vertical gap being left around the text.
  27343. */
  27344. int getVerticalBorderSize() const throw() { return verticalBorderSize; }
  27345. /** Makes this label "stick to" another component.
  27346. This will cause the label to follow another component around, staying
  27347. either to its left or above it.
  27348. @param owner the component to follow
  27349. @param onLeft if true, the label will stay on the left of its component; if
  27350. false, it will stay above it.
  27351. */
  27352. void attachToComponent (Component* owner, bool onLeft);
  27353. /** If this label has been attached to another component using attachToComponent, this
  27354. returns the other component.
  27355. Returns 0 if the label is not attached.
  27356. */
  27357. Component* getAttachedComponent() const;
  27358. /** If the label is attached to the left of another component, this returns true.
  27359. Returns false if the label is above the other component. This is only relevent if
  27360. attachToComponent() has been called.
  27361. */
  27362. bool isAttachedOnLeft() const throw() { return leftOfOwnerComp; }
  27363. /** Specifies the minimum amount that the font can be squashed horizantally before it starts
  27364. using ellipsis.
  27365. @see Graphics::drawFittedText
  27366. */
  27367. void setMinimumHorizontalScale (float newScale);
  27368. float getMinimumHorizontalScale() const throw() { return minimumHorizontalScale; }
  27369. /** Registers a listener that will be called when the label's text changes. */
  27370. void addListener (LabelListener* listener) throw();
  27371. /** Deregisters a previously-registered listener. */
  27372. void removeListener (LabelListener* listener) throw();
  27373. /** Makes the label turn into a TextEditor when clicked.
  27374. By default this is turned off.
  27375. If turned on, then single- or double-clicking will turn the label into
  27376. an editor. If the user then changes the text, then the ChangeBroadcaster
  27377. base class will be used to send change messages to any listeners that
  27378. have registered.
  27379. If the user changes the text, the textWasEdited() method will be called
  27380. afterwards, and subclasses can override this if they need to do anything
  27381. special.
  27382. @param editOnSingleClick if true, just clicking once on the label will start editing the text
  27383. @param editOnDoubleClick if true, a double-click is needed to start editing
  27384. @param lossOfFocusDiscardsChanges if true, clicking somewhere else while the text is being
  27385. edited will discard any changes; if false, then this will
  27386. commit the changes.
  27387. @see showEditor, setEditorColours, TextEditor
  27388. */
  27389. void setEditable (bool editOnSingleClick,
  27390. bool editOnDoubleClick = false,
  27391. bool lossOfFocusDiscardsChanges = false) throw();
  27392. /** Returns true if this option was set using setEditable(). */
  27393. bool isEditableOnSingleClick() const throw() { return editSingleClick; }
  27394. /** Returns true if this option was set using setEditable(). */
  27395. bool isEditableOnDoubleClick() const throw() { return editDoubleClick; }
  27396. /** Returns true if this option has been set in a call to setEditable(). */
  27397. bool doesLossOfFocusDiscardChanges() const throw() { return lossOfFocusDiscardsChanges; }
  27398. /** Returns true if the user can edit this label's text. */
  27399. bool isEditable() const throw() { return editSingleClick || editDoubleClick; }
  27400. /** Makes the editor appear as if the label had been clicked by the user.
  27401. @see textWasEdited, setEditable
  27402. */
  27403. void showEditor();
  27404. /** Hides the editor if it was being shown.
  27405. @param discardCurrentEditorContents if true, the label's text will be
  27406. reset to whatever it was before the editor
  27407. was shown; if false, the current contents of the
  27408. editor will be used to set the label's text
  27409. before it is hidden.
  27410. */
  27411. void hideEditor (bool discardCurrentEditorContents);
  27412. /** Returns true if the editor is currently focused and active. */
  27413. bool isBeingEdited() const throw();
  27414. juce_UseDebuggingNewOperator
  27415. protected:
  27416. /** Creates the TextEditor component that will be used when the user has clicked on the label.
  27417. Subclasses can override this if they need to customise this component in some way.
  27418. */
  27419. virtual TextEditor* createEditorComponent();
  27420. /** Called after the user changes the text.
  27421. */
  27422. virtual void textWasEdited();
  27423. /** Called when the text has been altered.
  27424. */
  27425. virtual void textWasChanged();
  27426. /** Called when the text editor has just appeared, due to a user click or other
  27427. focus change.
  27428. */
  27429. virtual void editorShown (TextEditor* editorComponent);
  27430. /** Called when the text editor is going to be deleted, after editing has finished.
  27431. */
  27432. virtual void editorAboutToBeHidden (TextEditor* editorComponent);
  27433. /** @internal */
  27434. void paint (Graphics& g);
  27435. /** @internal */
  27436. void resized();
  27437. /** @internal */
  27438. void mouseUp (const MouseEvent& e);
  27439. /** @internal */
  27440. void mouseDoubleClick (const MouseEvent& e);
  27441. /** @internal */
  27442. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  27443. /** @internal */
  27444. void componentParentHierarchyChanged (Component& component);
  27445. /** @internal */
  27446. void componentVisibilityChanged (Component& component);
  27447. /** @internal */
  27448. void inputAttemptWhenModal();
  27449. /** @internal */
  27450. void focusGained (FocusChangeType);
  27451. /** @internal */
  27452. void enablementChanged();
  27453. /** @internal */
  27454. KeyboardFocusTraverser* createFocusTraverser();
  27455. /** @internal */
  27456. void textEditorTextChanged (TextEditor& editor);
  27457. /** @internal */
  27458. void textEditorReturnKeyPressed (TextEditor& editor);
  27459. /** @internal */
  27460. void textEditorEscapeKeyPressed (TextEditor& editor);
  27461. /** @internal */
  27462. void textEditorFocusLost (TextEditor& editor);
  27463. /** @internal */
  27464. void colourChanged();
  27465. /** @internal */
  27466. void valueChanged (Value&);
  27467. private:
  27468. Value textValue;
  27469. String lastTextValue;
  27470. Font font;
  27471. Justification justification;
  27472. ScopedPointer <TextEditor> editor;
  27473. ListenerList <LabelListener> listeners;
  27474. Component::SafePointer<Component> ownerComponent;
  27475. int horizontalBorderSize, verticalBorderSize;
  27476. float minimumHorizontalScale;
  27477. bool editSingleClick : 1;
  27478. bool editDoubleClick : 1;
  27479. bool lossOfFocusDiscardsChanges : 1;
  27480. bool leftOfOwnerComp : 1;
  27481. bool updateFromTextEditorContents();
  27482. void callChangeListeners();
  27483. Label (const Label&);
  27484. Label& operator= (const Label&);
  27485. };
  27486. #endif // __JUCE_LABEL_JUCEHEADER__
  27487. /*** End of inlined file: juce_Label.h ***/
  27488. class ComboBox;
  27489. /**
  27490. A class for receiving events from a ComboBox.
  27491. You can register a ComboBoxListener with a ComboBox using the ComboBox::addListener()
  27492. method, and it will be called when the selected item in the box changes.
  27493. @see ComboBox::addListener, ComboBox::removeListener
  27494. */
  27495. class JUCE_API ComboBoxListener
  27496. {
  27497. public:
  27498. /** Destructor. */
  27499. virtual ~ComboBoxListener() {}
  27500. /** Called when a ComboBox has its selected item changed.
  27501. */
  27502. virtual void comboBoxChanged (ComboBox* comboBoxThatHasChanged) = 0;
  27503. };
  27504. /**
  27505. A component that lets the user choose from a drop-down list of choices.
  27506. The combo-box has a list of text strings, each with an associated id number,
  27507. that will be shown in the drop-down list when the user clicks on the component.
  27508. The currently selected choice is displayed in the combo-box, and this can
  27509. either be read-only text, or editable.
  27510. To find out when the user selects a different item or edits the text, you
  27511. can register a ComboBoxListener to receive callbacks.
  27512. @see ComboBoxListener
  27513. */
  27514. class JUCE_API ComboBox : public Component,
  27515. public SettableTooltipClient,
  27516. private LabelListener,
  27517. private AsyncUpdater,
  27518. private Value::Listener
  27519. {
  27520. public:
  27521. /** Creates a combo-box.
  27522. On construction, the text field will be empty, so you should call the
  27523. setSelectedId() or setText() method to choose the initial value before
  27524. displaying it.
  27525. @param componentName the name to set for the component (see Component::setName())
  27526. */
  27527. explicit ComboBox (const String& componentName = String::empty);
  27528. /** Destructor. */
  27529. ~ComboBox();
  27530. /** Sets whether the test in the combo-box is editable.
  27531. The default state for a new ComboBox is non-editable, and can only be changed
  27532. by choosing from the drop-down list.
  27533. */
  27534. void setEditableText (bool isEditable);
  27535. /** Returns true if the text is directly editable.
  27536. @see setEditableText
  27537. */
  27538. bool isTextEditable() const throw();
  27539. /** Sets the style of justification to be used for positioning the text.
  27540. The default is Justification::centredLeft. The text is displayed using a
  27541. Label component inside the ComboBox.
  27542. */
  27543. void setJustificationType (const Justification& justification) throw();
  27544. /** Returns the current justification for the text box.
  27545. @see setJustificationType
  27546. */
  27547. const Justification getJustificationType() const throw();
  27548. /** Adds an item to be shown in the drop-down list.
  27549. @param newItemText the text of the item to show in the list
  27550. @param newItemId an associated ID number that can be set or retrieved - see
  27551. getSelectedId() and setSelectedId()
  27552. @see setItemEnabled, addSeparator, addSectionHeading, removeItem, getNumItems, getItemText, getItemId
  27553. */
  27554. void addItem (const String& newItemText,
  27555. int newItemId) throw();
  27556. /** Adds a separator line to the drop-down list.
  27557. This is like adding a separator to a popup menu. See PopupMenu::addSeparator().
  27558. */
  27559. void addSeparator() throw();
  27560. /** Adds a heading to the drop-down list, so that you can group the items into
  27561. different sections.
  27562. The headings are indented slightly differently to set them apart from the
  27563. items on the list, and obviously can't be selected. You might want to add
  27564. separators between your sections too.
  27565. @see addItem, addSeparator
  27566. */
  27567. void addSectionHeading (const String& headingName) throw();
  27568. /** This allows items in the drop-down list to be selectively disabled.
  27569. When you add an item, it's enabled by default, but you can call this
  27570. method to change its status.
  27571. If you disable an item which is already selected, this won't change the
  27572. current selection - it just stops the user choosing that item from the list.
  27573. */
  27574. void setItemEnabled (int itemId,
  27575. bool shouldBeEnabled) throw();
  27576. /** Changes the text for an existing item.
  27577. */
  27578. void changeItemText (int itemId,
  27579. const String& newText) throw();
  27580. /** Removes all the items from the drop-down list.
  27581. If this call causes the content to be cleared, then a change-message
  27582. will be broadcast unless dontSendChangeMessage is true.
  27583. @see addItem, removeItem, getNumItems
  27584. */
  27585. void clear (bool dontSendChangeMessage = false);
  27586. /** Returns the number of items that have been added to the list.
  27587. Note that this doesn't include headers or separators.
  27588. */
  27589. int getNumItems() const throw();
  27590. /** Returns the text for one of the items in the list.
  27591. Note that this doesn't include headers or separators.
  27592. @param index the item's index from 0 to (getNumItems() - 1)
  27593. */
  27594. const String getItemText (int index) const throw();
  27595. /** Returns the ID for one of the items in the list.
  27596. Note that this doesn't include headers or separators.
  27597. @param index the item's index from 0 to (getNumItems() - 1)
  27598. */
  27599. int getItemId (int index) const throw();
  27600. /** Returns the index in the list of a particular item ID.
  27601. If no such ID is found, this will return -1.
  27602. */
  27603. int indexOfItemId (int itemId) const throw();
  27604. /** Returns the ID of the item that's currently shown in the box.
  27605. If no item is selected, or if the text is editable and the user
  27606. has entered something which isn't one of the items in the list, then
  27607. this will return 0.
  27608. @see setSelectedId, getSelectedItemIndex, getText
  27609. */
  27610. int getSelectedId() const throw();
  27611. /** Returns a Value object that can be used to get or set the selected item's ID.
  27612. You can call Value::referTo() on this object to make the combo box control
  27613. another Value object.
  27614. */
  27615. Value& getSelectedIdAsValue() throw() { return currentId; }
  27616. /** Sets one of the items to be the current selection.
  27617. This will set the ComboBox's text to that of the item that matches
  27618. this ID.
  27619. @param newItemId the new item to select
  27620. @param dontSendChangeMessage if set to true, this method won't trigger a
  27621. change notification
  27622. @see getSelectedId, setSelectedItemIndex, setText
  27623. */
  27624. void setSelectedId (int newItemId,
  27625. bool dontSendChangeMessage = false) throw();
  27626. /** Returns the index of the item that's currently shown in the box.
  27627. If no item is selected, or if the text is editable and the user
  27628. has entered something which isn't one of the items in the list, then
  27629. this will return -1.
  27630. @see setSelectedItemIndex, getSelectedId, getText
  27631. */
  27632. int getSelectedItemIndex() const throw();
  27633. /** Sets one of the items to be the current selection.
  27634. This will set the ComboBox's text to that of the item at the given
  27635. index in the list.
  27636. @param newItemIndex the new item to select
  27637. @param dontSendChangeMessage if set to true, this method won't trigger a
  27638. change notification
  27639. @see getSelectedItemIndex, setSelectedId, setText
  27640. */
  27641. void setSelectedItemIndex (int newItemIndex,
  27642. bool dontSendChangeMessage = false) throw();
  27643. /** Returns the text that is currently shown in the combo-box's text field.
  27644. If the ComboBox has editable text, then this text may have been edited
  27645. by the user; otherwise it will be one of the items from the list, or
  27646. possibly an empty string if nothing was selected.
  27647. @see setText, getSelectedId, getSelectedItemIndex
  27648. */
  27649. const String getText() const throw();
  27650. /** Sets the contents of the combo-box's text field.
  27651. The text passed-in will be set as the current text regardless of whether
  27652. it is one of the items in the list. If the current text isn't one of the
  27653. items, then getSelectedId() will return -1, otherwise it wil return
  27654. the approriate ID.
  27655. @param newText the text to select
  27656. @param dontSendChangeMessage if set to true, this method won't trigger a
  27657. change notification
  27658. @see getText
  27659. */
  27660. void setText (const String& newText,
  27661. bool dontSendChangeMessage = false) throw();
  27662. /** Programmatically opens the text editor to allow the user to edit the current item.
  27663. This is the same effect as when the box is clicked-on.
  27664. @see Label::showEditor();
  27665. */
  27666. void showEditor();
  27667. /** Pops up the combo box's list. */
  27668. void showPopup();
  27669. /** Registers a listener that will be called when the box's content changes. */
  27670. void addListener (ComboBoxListener* listener) throw();
  27671. /** Deregisters a previously-registered listener. */
  27672. void removeListener (ComboBoxListener* listener) throw();
  27673. /** Sets a message to display when there is no item currently selected.
  27674. @see getTextWhenNothingSelected
  27675. */
  27676. void setTextWhenNothingSelected (const String& newMessage) throw();
  27677. /** Returns the text that is shown when no item is selected.
  27678. @see setTextWhenNothingSelected
  27679. */
  27680. const String getTextWhenNothingSelected() const throw();
  27681. /** Sets the message to show when there are no items in the list, and the user clicks
  27682. on the drop-down box.
  27683. By default it just says "no choices", but this lets you change it to something more
  27684. meaningful.
  27685. */
  27686. void setTextWhenNoChoicesAvailable (const String& newMessage) throw();
  27687. /** Returns the text shown when no items have been added to the list.
  27688. @see setTextWhenNoChoicesAvailable
  27689. */
  27690. const String getTextWhenNoChoicesAvailable() const throw();
  27691. /** Gives the ComboBox a tooltip. */
  27692. void setTooltip (const String& newTooltip);
  27693. /** A set of colour IDs to use to change the colour of various aspects of the combo box.
  27694. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  27695. methods.
  27696. To change the colours of the menu that pops up
  27697. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  27698. */
  27699. enum ColourIds
  27700. {
  27701. backgroundColourId = 0x1000b00, /**< The background colour to fill the box with. */
  27702. textColourId = 0x1000a00, /**< The colour for the text in the box. */
  27703. outlineColourId = 0x1000c00, /**< The colour for an outline around the box. */
  27704. buttonColourId = 0x1000d00, /**< The base colour for the button (a LookAndFeel class will probably use variations on this). */
  27705. arrowColourId = 0x1000e00, /**< The colour for the arrow shape that pops up the menu */
  27706. };
  27707. /** @internal */
  27708. void labelTextChanged (Label*);
  27709. /** @internal */
  27710. void enablementChanged();
  27711. /** @internal */
  27712. void colourChanged();
  27713. /** @internal */
  27714. void focusGained (Component::FocusChangeType cause);
  27715. /** @internal */
  27716. void focusLost (Component::FocusChangeType cause);
  27717. /** @internal */
  27718. void handleAsyncUpdate();
  27719. /** @internal */
  27720. const String getTooltip() { return label->getTooltip(); }
  27721. /** @internal */
  27722. void mouseDown (const MouseEvent&);
  27723. /** @internal */
  27724. void mouseDrag (const MouseEvent&);
  27725. /** @internal */
  27726. void mouseUp (const MouseEvent&);
  27727. /** @internal */
  27728. void lookAndFeelChanged();
  27729. /** @internal */
  27730. void paint (Graphics&);
  27731. /** @internal */
  27732. void resized();
  27733. /** @internal */
  27734. bool keyStateChanged (bool isKeyDown);
  27735. /** @internal */
  27736. bool keyPressed (const KeyPress&);
  27737. /** @internal */
  27738. void valueChanged (Value&);
  27739. juce_UseDebuggingNewOperator
  27740. private:
  27741. struct ItemInfo
  27742. {
  27743. String name;
  27744. int itemId;
  27745. bool isEnabled : 1, isHeading : 1;
  27746. bool isSeparator() const throw();
  27747. bool isRealItem() const throw();
  27748. };
  27749. class Callback;
  27750. friend class Callback;
  27751. OwnedArray <ItemInfo> items;
  27752. Value currentId;
  27753. int lastCurrentId;
  27754. bool isButtonDown, separatorPending, menuActive, textIsCustom;
  27755. ListenerList <ComboBoxListener> listeners;
  27756. ScopedPointer<Label> label;
  27757. String textWhenNothingSelected, noChoicesMessage;
  27758. ItemInfo* getItemForId (int itemId) const throw();
  27759. ItemInfo* getItemForIndex (int index) const throw();
  27760. ComboBox (const ComboBox&);
  27761. ComboBox& operator= (const ComboBox&);
  27762. };
  27763. #endif // __JUCE_COMBOBOX_JUCEHEADER__
  27764. /*** End of inlined file: juce_ComboBox.h ***/
  27765. /**
  27766. Manages the state of some audio and midi i/o devices.
  27767. This class keeps tracks of a currently-selected audio device, through
  27768. with which it continuously streams data from an audio callback, as well as
  27769. one or more midi inputs.
  27770. The idea is that your application will create one global instance of this object,
  27771. and let it take care of creating and deleting specific types of audio devices
  27772. internally. So when the device is changed, your callbacks will just keep running
  27773. without having to worry about this.
  27774. The manager can save and reload all of its device settings as XML, which
  27775. makes it very easy for you to save and reload the audio setup of your
  27776. application.
  27777. And to make it easy to let the user change its settings, there's a component
  27778. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  27779. device selection/sample-rate/latency controls.
  27780. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  27781. call addAudioCallback() to register your audio callback with it, and use that to process
  27782. your audio data.
  27783. The manager also acts as a handy hub for incoming midi messages, allowing a
  27784. listener to register for messages from either a specific midi device, or from whatever
  27785. the current default midi input device is. The listener then doesn't have to worry about
  27786. re-registering with different midi devices if they are changed or deleted.
  27787. And yet another neat trick is that amount of CPU time being used is measured and
  27788. available with the getCpuUsage() method.
  27789. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  27790. listeners whenever one of its settings is changed.
  27791. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  27792. */
  27793. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  27794. {
  27795. public:
  27796. /** Creates a default AudioDeviceManager.
  27797. Initially no audio device will be selected. You should call the initialise() method
  27798. and register an audio callback with setAudioCallback() before it'll be able to
  27799. actually make any noise.
  27800. */
  27801. AudioDeviceManager();
  27802. /** Destructor. */
  27803. ~AudioDeviceManager();
  27804. /**
  27805. This structure holds a set of properties describing the current audio setup.
  27806. An AudioDeviceManager uses this class to save/load its current settings, and to
  27807. specify your preferred options when opening a device.
  27808. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  27809. */
  27810. struct JUCE_API AudioDeviceSetup
  27811. {
  27812. /** Creates an AudioDeviceSetup object.
  27813. The default constructor sets all the member variables to indicate default values.
  27814. You can then fill-in any values you want to before passing the object to
  27815. AudioDeviceManager::initialise().
  27816. */
  27817. AudioDeviceSetup();
  27818. bool operator== (const AudioDeviceSetup& other) const;
  27819. /** The name of the audio device used for output.
  27820. The name has to be one of the ones listed by the AudioDeviceManager's currently
  27821. selected device type.
  27822. This may be the same as the input device.
  27823. An empty string indicates the default device.
  27824. */
  27825. String outputDeviceName;
  27826. /** The name of the audio device used for input.
  27827. This may be the same as the output device.
  27828. An empty string indicates the default device.
  27829. */
  27830. String inputDeviceName;
  27831. /** The current sample rate.
  27832. This rate is used for both the input and output devices.
  27833. A value of 0 indicates the default rate.
  27834. */
  27835. double sampleRate;
  27836. /** The buffer size, in samples.
  27837. This buffer size is used for both the input and output devices.
  27838. A value of 0 indicates the default buffer size.
  27839. */
  27840. int bufferSize;
  27841. /** The set of active input channels.
  27842. The bits that are set in this array indicate the channels of the
  27843. input device that are active.
  27844. If useDefaultInputChannels is true, this value is ignored.
  27845. */
  27846. BigInteger inputChannels;
  27847. /** If this is true, it indicates that the inputChannels array
  27848. should be ignored, and instead, the device's default channels
  27849. should be used.
  27850. */
  27851. bool useDefaultInputChannels;
  27852. /** The set of active output channels.
  27853. The bits that are set in this array indicate the channels of the
  27854. input device that are active.
  27855. If useDefaultOutputChannels is true, this value is ignored.
  27856. */
  27857. BigInteger outputChannels;
  27858. /** If this is true, it indicates that the outputChannels array
  27859. should be ignored, and instead, the device's default channels
  27860. should be used.
  27861. */
  27862. bool useDefaultOutputChannels;
  27863. };
  27864. /** Opens a set of audio devices ready for use.
  27865. This will attempt to open either a default audio device, or one that was
  27866. previously saved as XML.
  27867. @param numInputChannelsNeeded a minimum number of input channels needed
  27868. by your app.
  27869. @param numOutputChannelsNeeded a minimum number of output channels to open
  27870. @param savedState either a previously-saved state that was produced
  27871. by createStateXml(), or 0 if you want the manager
  27872. to choose the best device to open.
  27873. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  27874. fails to open, then a default device will be used
  27875. instead. If false, then on failure, no device is
  27876. opened.
  27877. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  27878. name, then that will be used as the default device
  27879. (assuming that there wasn't one specified in the XML).
  27880. The string can actually be a simple wildcard, containing "*"
  27881. and "?" characters
  27882. @param preferredSetupOptions if this is non-null, the structure will be used as the
  27883. set of preferred settings when opening the device. If you
  27884. use this parameter, the preferredDefaultDeviceName
  27885. field will be ignored
  27886. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27887. */
  27888. const String initialise (int numInputChannelsNeeded,
  27889. int numOutputChannelsNeeded,
  27890. const XmlElement* savedState,
  27891. bool selectDefaultDeviceOnFailure,
  27892. const String& preferredDefaultDeviceName = String::empty,
  27893. const AudioDeviceSetup* preferredSetupOptions = 0);
  27894. /** Returns some XML representing the current state of the manager.
  27895. This stores the current device, its samplerate, block size, etc, and
  27896. can be restored later with initialise().
  27897. */
  27898. XmlElement* createStateXml() const;
  27899. /** Returns the current device properties that are in use.
  27900. @see setAudioDeviceSetup
  27901. */
  27902. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  27903. /** Changes the current device or its settings.
  27904. If you want to change a device property, like the current sample rate or
  27905. block size, you can call getAudioDeviceSetup() to retrieve the current
  27906. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  27907. and pass it back into this method to apply the new settings.
  27908. @param newSetup the settings that you'd like to use
  27909. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  27910. settings will be taken as having been explicitly chosen by the
  27911. user, and the next time createStateXml() is called, these settings
  27912. will be returned. If it's false, then the device is treated as a
  27913. temporary or default device, and a call to createStateXml() will
  27914. return either the last settings that were made with treatAsChosenDevice
  27915. as true, or the last XML settings that were passed into initialise().
  27916. @returns an error message if anything went wrong, or an empty string if it worked ok.
  27917. @see getAudioDeviceSetup
  27918. */
  27919. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  27920. bool treatAsChosenDevice);
  27921. /** Returns the currently-active audio device. */
  27922. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  27923. /** Returns the type of audio device currently in use.
  27924. @see setCurrentAudioDeviceType
  27925. */
  27926. const String getCurrentAudioDeviceType() const { return currentDeviceType; }
  27927. /** Returns the currently active audio device type object.
  27928. Don't keep a copy of this pointer - it's owned by the device manager and could
  27929. change at any time.
  27930. */
  27931. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  27932. /** Changes the class of audio device being used.
  27933. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  27934. this because there's only one type: CoreAudio.
  27935. For a list of types, see getAvailableDeviceTypes().
  27936. */
  27937. void setCurrentAudioDeviceType (const String& type,
  27938. bool treatAsChosenDevice);
  27939. /** Closes the currently-open device.
  27940. You can call restartLastAudioDevice() later to reopen it in the same state
  27941. that it was just in.
  27942. */
  27943. void closeAudioDevice();
  27944. /** Tries to reload the last audio device that was running.
  27945. Note that this only reloads the last device that was running before
  27946. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  27947. and can only be called after a device has been opened with SetAudioDevice().
  27948. If a device is already open, this call will do nothing.
  27949. */
  27950. void restartLastAudioDevice();
  27951. /** Registers an audio callback to be used.
  27952. The manager will redirect callbacks from whatever audio device is currently
  27953. in use to all registered callback objects. If more than one callback is
  27954. active, they will all be given the same input data, and their outputs will
  27955. be summed.
  27956. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  27957. object before returning.
  27958. To remove a callback, use removeAudioCallback().
  27959. */
  27960. void addAudioCallback (AudioIODeviceCallback* newCallback);
  27961. /** Deregisters a previously added callback.
  27962. If necessary, this method will invoke audioDeviceStopped() on the callback
  27963. object before returning.
  27964. @see addAudioCallback
  27965. */
  27966. void removeAudioCallback (AudioIODeviceCallback* callback);
  27967. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  27968. Returns a value between 0 and 1.0
  27969. */
  27970. double getCpuUsage() const;
  27971. /** Enables or disables a midi input device.
  27972. The list of devices can be obtained with the MidiInput::getDevices() method.
  27973. Any incoming messages from enabled input devices will be forwarded on to all the
  27974. listeners that have been registered with the addMidiInputCallback() method. They
  27975. can either register for messages from a particular device, or from just the
  27976. "default" midi input.
  27977. Routing the midi input via an AudioDeviceManager means that when a listener
  27978. registers for the default midi input, this default device can be changed by the
  27979. manager without the listeners having to know about it or re-register.
  27980. It also means that a listener can stay registered for a midi input that is disabled
  27981. or not present, so that when the input is re-enabled, the listener will start
  27982. receiving messages again.
  27983. @see addMidiInputCallback, isMidiInputEnabled
  27984. */
  27985. void setMidiInputEnabled (const String& midiInputDeviceName,
  27986. bool enabled);
  27987. /** Returns true if a given midi input device is being used.
  27988. @see setMidiInputEnabled
  27989. */
  27990. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  27991. /** Registers a listener for callbacks when midi events arrive from a midi input.
  27992. The device name can be empty to indicate that it wants events from whatever the
  27993. current "default" device is. Or it can be the name of one of the midi input devices
  27994. (see MidiInput::getDevices() for the names).
  27995. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  27996. events forwarded on to listeners.
  27997. */
  27998. void addMidiInputCallback (const String& midiInputDeviceName,
  27999. MidiInputCallback* callback);
  28000. /** Removes a listener that was previously registered with addMidiInputCallback().
  28001. */
  28002. void removeMidiInputCallback (const String& midiInputDeviceName,
  28003. MidiInputCallback* callback);
  28004. /** Sets a midi output device to use as the default.
  28005. The list of devices can be obtained with the MidiOutput::getDevices() method.
  28006. The specified device will be opened automatically and can be retrieved with the
  28007. getDefaultMidiOutput() method.
  28008. Pass in an empty string to deselect all devices. For the default device, you
  28009. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  28010. @see getDefaultMidiOutput, getDefaultMidiOutputName
  28011. */
  28012. void setDefaultMidiOutput (const String& deviceName);
  28013. /** Returns the name of the default midi output.
  28014. @see setDefaultMidiOutput, getDefaultMidiOutput
  28015. */
  28016. const String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
  28017. /** Returns the current default midi output device.
  28018. If no device has been selected, or the device can't be opened, this will
  28019. return 0.
  28020. @see getDefaultMidiOutputName
  28021. */
  28022. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  28023. /** Returns a list of the types of device supported.
  28024. */
  28025. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  28026. /** Creates a list of available types.
  28027. This will add a set of new AudioIODeviceType objects to the specified list, to
  28028. represent each available types of device.
  28029. You can override this if your app needs to do something specific, like avoid
  28030. using DirectSound devices, etc.
  28031. */
  28032. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  28033. /** Plays a beep through the current audio device.
  28034. This is here to allow the audio setup UI panels to easily include a "test"
  28035. button so that the user can check where the audio is coming from.
  28036. */
  28037. void playTestSound();
  28038. /** Turns on level-measuring.
  28039. When enabled, the device manager will measure the peak input level
  28040. across all channels, and you can get this level by calling getCurrentInputLevel().
  28041. This is mainly intended for audio setup UI panels to use to create a mic
  28042. level display, so that the user can check that they've selected the right
  28043. device.
  28044. A simple filter is used to make the level decay smoothly, but this is
  28045. only intended for giving rough feedback, and not for any kind of accurate
  28046. measurement.
  28047. */
  28048. void enableInputLevelMeasurement (bool enableMeasurement);
  28049. /** Returns the current input level.
  28050. To use this, you must first enable it by calling enableInputLevelMeasurement().
  28051. See enableInputLevelMeasurement() for more info.
  28052. */
  28053. double getCurrentInputLevel() const;
  28054. juce_UseDebuggingNewOperator
  28055. private:
  28056. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  28057. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  28058. AudioDeviceSetup currentSetup;
  28059. ScopedPointer <AudioIODevice> currentAudioDevice;
  28060. SortedSet <AudioIODeviceCallback*> callbacks;
  28061. int numInputChansNeeded, numOutputChansNeeded;
  28062. String currentDeviceType;
  28063. BigInteger inputChannels, outputChannels;
  28064. ScopedPointer <XmlElement> lastExplicitSettings;
  28065. mutable bool listNeedsScanning;
  28066. bool useInputNames;
  28067. int inputLevelMeasurementEnabledCount;
  28068. double inputLevel;
  28069. ScopedPointer <AudioSampleBuffer> testSound;
  28070. int testSoundPosition;
  28071. AudioSampleBuffer tempBuffer;
  28072. StringArray midiInsFromXml;
  28073. OwnedArray <MidiInput> enabledMidiInputs;
  28074. Array <MidiInputCallback*> midiCallbacks;
  28075. Array <MidiInput*> midiCallbackDevices;
  28076. String defaultMidiOutputName;
  28077. ScopedPointer <MidiOutput> defaultMidiOutput;
  28078. CriticalSection audioCallbackLock, midiCallbackLock;
  28079. double cpuUsageMs, timeToCpuScale;
  28080. class CallbackHandler : public AudioIODeviceCallback,
  28081. public MidiInputCallback
  28082. {
  28083. public:
  28084. AudioDeviceManager* owner;
  28085. void audioDeviceIOCallback (const float** inputChannelData,
  28086. int totalNumInputChannels,
  28087. float** outputChannelData,
  28088. int totalNumOutputChannels,
  28089. int numSamples);
  28090. void audioDeviceAboutToStart (AudioIODevice*);
  28091. void audioDeviceStopped();
  28092. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28093. };
  28094. CallbackHandler callbackHandler;
  28095. friend class CallbackHandler;
  28096. void audioDeviceIOCallbackInt (const float** inputChannelData,
  28097. int totalNumInputChannels,
  28098. float** outputChannelData,
  28099. int totalNumOutputChannels,
  28100. int numSamples);
  28101. void audioDeviceAboutToStartInt (AudioIODevice* device);
  28102. void audioDeviceStoppedInt();
  28103. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  28104. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  28105. const BigInteger& ins, const BigInteger& outs);
  28106. void stopDevice();
  28107. void updateXml();
  28108. void createDeviceTypesIfNeeded();
  28109. void scanDevicesIfNeeded();
  28110. void deleteCurrentDevice();
  28111. double chooseBestSampleRate (double preferred) const;
  28112. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  28113. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  28114. AudioDeviceManager (const AudioDeviceManager&);
  28115. AudioDeviceManager& operator= (const AudioDeviceManager&);
  28116. };
  28117. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  28118. /*** End of inlined file: juce_AudioDeviceManager.h ***/
  28119. #endif
  28120. #ifndef __JUCE_AUDIOIODEVICE_JUCEHEADER__
  28121. #endif
  28122. #ifndef __JUCE_AUDIOIODEVICETYPE_JUCEHEADER__
  28123. #endif
  28124. #ifndef __JUCE_MIDIINPUT_JUCEHEADER__
  28125. #endif
  28126. #ifndef __JUCE_MIDIOUTPUT_JUCEHEADER__
  28127. #endif
  28128. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28129. /*** Start of inlined file: juce_AudioDataConverters.h ***/
  28130. #ifndef __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28131. #define __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28132. /**
  28133. A set of routines to convert buffers of 32-bit floating point data to and from
  28134. various integer formats.
  28135. */
  28136. class JUCE_API AudioDataConverters
  28137. {
  28138. public:
  28139. static void convertFloatToInt16LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  28140. static void convertFloatToInt16BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 2);
  28141. static void convertFloatToInt24LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  28142. static void convertFloatToInt24BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 3);
  28143. static void convertFloatToInt32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28144. static void convertFloatToInt32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28145. static void convertFloatToFloat32LE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28146. static void convertFloatToFloat32BE (const float* source, void* dest, int numSamples, int destBytesPerSample = 4);
  28147. static void convertInt16LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  28148. static void convertInt16BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 2);
  28149. static void convertInt24LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  28150. static void convertInt24BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 3);
  28151. static void convertInt32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28152. static void convertInt32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28153. static void convertFloat32LEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28154. static void convertFloat32BEToFloat (const void* source, float* dest, int numSamples, int srcBytesPerSample = 4);
  28155. enum DataFormat
  28156. {
  28157. int16LE,
  28158. int16BE,
  28159. int24LE,
  28160. int24BE,
  28161. int32LE,
  28162. int32BE,
  28163. float32LE,
  28164. float32BE,
  28165. };
  28166. static void convertFloatToFormat (DataFormat destFormat,
  28167. const float* source, void* dest, int numSamples);
  28168. static void convertFormatToFloat (DataFormat sourceFormat,
  28169. const void* source, float* dest, int numSamples);
  28170. static void interleaveSamples (const float** source, float* dest,
  28171. int numSamples, int numChannels);
  28172. static void deinterleaveSamples (const float* source, float** dest,
  28173. int numSamples, int numChannels);
  28174. private:
  28175. AudioDataConverters();
  28176. AudioDataConverters (const AudioDataConverters&);
  28177. AudioDataConverters& operator= (const AudioDataConverters&);
  28178. };
  28179. #endif // __JUCE_AUDIODATACONVERTERS_JUCEHEADER__
  28180. /*** End of inlined file: juce_AudioDataConverters.h ***/
  28181. #endif
  28182. #ifndef __JUCE_AUDIOSAMPLEBUFFER_JUCEHEADER__
  28183. #endif
  28184. #ifndef __JUCE_IIRFILTER_JUCEHEADER__
  28185. #endif
  28186. #ifndef __JUCE_MIDIBUFFER_JUCEHEADER__
  28187. #endif
  28188. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  28189. /*** Start of inlined file: juce_MidiFile.h ***/
  28190. #ifndef __JUCE_MIDIFILE_JUCEHEADER__
  28191. #define __JUCE_MIDIFILE_JUCEHEADER__
  28192. /*** Start of inlined file: juce_MidiMessageSequence.h ***/
  28193. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28194. #define __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28195. /**
  28196. A sequence of timestamped midi messages.
  28197. This allows the sequence to be manipulated, and also to be read from and
  28198. written to a standard midi file.
  28199. @see MidiMessage, MidiFile
  28200. */
  28201. class JUCE_API MidiMessageSequence
  28202. {
  28203. public:
  28204. /** Creates an empty midi sequence object. */
  28205. MidiMessageSequence();
  28206. /** Creates a copy of another sequence. */
  28207. MidiMessageSequence (const MidiMessageSequence& other);
  28208. /** Replaces this sequence with another one. */
  28209. MidiMessageSequence& operator= (const MidiMessageSequence& other);
  28210. /** Destructor. */
  28211. ~MidiMessageSequence();
  28212. /** Structure used to hold midi events in the sequence.
  28213. These structures act as 'handles' on the events as they are moved about in
  28214. the list, and make it quick to find the matching note-offs for note-on events.
  28215. @see MidiMessageSequence::getEventPointer
  28216. */
  28217. class MidiEventHolder
  28218. {
  28219. public:
  28220. /** Destructor. */
  28221. ~MidiEventHolder();
  28222. /** The message itself, whose timestamp is used to specify the event's time.
  28223. */
  28224. MidiMessage message;
  28225. /** The matching note-off event (if this is a note-on event).
  28226. If this isn't a note-on, this pointer will be null.
  28227. Use the MidiMessageSequence::updateMatchedPairs() method to keep these
  28228. note-offs up-to-date after events have been moved around in the sequence
  28229. or deleted.
  28230. */
  28231. MidiEventHolder* noteOffObject;
  28232. juce_UseDebuggingNewOperator
  28233. private:
  28234. friend class MidiMessageSequence;
  28235. MidiEventHolder (const MidiMessage& message);
  28236. };
  28237. /** Clears the sequence. */
  28238. void clear();
  28239. /** Returns the number of events in the sequence. */
  28240. int getNumEvents() const;
  28241. /** Returns a pointer to one of the events. */
  28242. MidiEventHolder* getEventPointer (int index) const;
  28243. /** Returns the time of the note-up that matches the note-on at this index.
  28244. If the event at this index isn't a note-on, it'll just return 0.
  28245. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  28246. */
  28247. double getTimeOfMatchingKeyUp (int index) const;
  28248. /** Returns the index of the note-up that matches the note-on at this index.
  28249. If the event at this index isn't a note-on, it'll just return -1.
  28250. @see MidiMessageSequence::MidiEventHolder::noteOffObject
  28251. */
  28252. int getIndexOfMatchingKeyUp (int index) const;
  28253. /** Returns the index of an event. */
  28254. int getIndexOf (MidiEventHolder* event) const;
  28255. /** Returns the index of the first event on or after the given timestamp.
  28256. If the time is beyond the end of the sequence, this will return the
  28257. number of events.
  28258. */
  28259. int getNextIndexAtTime (double timeStamp) const;
  28260. /** Returns the timestamp of the first event in the sequence.
  28261. @see getEndTime
  28262. */
  28263. double getStartTime() const;
  28264. /** Returns the timestamp of the last event in the sequence.
  28265. @see getStartTime
  28266. */
  28267. double getEndTime() const;
  28268. /** Returns the timestamp of the event at a given index.
  28269. If the index is out-of-range, this will return 0.0
  28270. */
  28271. double getEventTime (int index) const;
  28272. /** Inserts a midi message into the sequence.
  28273. The index at which the new message gets inserted will depend on its timestamp,
  28274. because the sequence is kept sorted.
  28275. Remember to call updateMatchedPairs() after adding note-on events.
  28276. @param newMessage the new message to add (an internal copy will be made)
  28277. @param timeAdjustment an optional value to add to the timestamp of the message
  28278. that will be inserted
  28279. @see updateMatchedPairs
  28280. */
  28281. void addEvent (const MidiMessage& newMessage,
  28282. double timeAdjustment = 0);
  28283. /** Deletes one of the events in the sequence.
  28284. Remember to call updateMatchedPairs() after removing events.
  28285. @param index the index of the event to delete
  28286. @param deleteMatchingNoteUp whether to also remove the matching note-off
  28287. if the event you're removing is a note-on
  28288. */
  28289. void deleteEvent (int index, bool deleteMatchingNoteUp);
  28290. /** Merges another sequence into this one.
  28291. Remember to call updateMatchedPairs() after using this method.
  28292. @param other the sequence to add from
  28293. @param timeAdjustmentDelta an amount to add to the timestamps of the midi events
  28294. as they are read from the other sequence
  28295. @param firstAllowableDestTime events will not be added if their time is earlier
  28296. than this time. (This is after their time has been adjusted
  28297. by the timeAdjustmentDelta)
  28298. @param endOfAllowableDestTimes events will not be added if their time is equal to
  28299. or greater than this time. (This is after their time has
  28300. been adjusted by the timeAdjustmentDelta)
  28301. */
  28302. void addSequence (const MidiMessageSequence& other,
  28303. double timeAdjustmentDelta,
  28304. double firstAllowableDestTime,
  28305. double endOfAllowableDestTimes);
  28306. /** Makes sure all the note-on and note-off pairs are up-to-date.
  28307. Call this after moving messages about or deleting/adding messages, and it
  28308. will scan the list and make sure all the note-offs in the MidiEventHolder
  28309. structures are pointing at the correct ones.
  28310. */
  28311. void updateMatchedPairs();
  28312. /** Copies all the messages for a particular midi channel to another sequence.
  28313. @param channelNumberToExtract the midi channel to look for, in the range 1 to 16
  28314. @param destSequence the sequence that the chosen events should be copied to
  28315. @param alsoIncludeMetaEvents if true, any meta-events (which don't apply to a specific
  28316. channel) will also be copied across.
  28317. @see extractSysExMessages
  28318. */
  28319. void extractMidiChannelMessages (int channelNumberToExtract,
  28320. MidiMessageSequence& destSequence,
  28321. bool alsoIncludeMetaEvents) const;
  28322. /** Copies all midi sys-ex messages to another sequence.
  28323. @param destSequence this is the sequence to which any sys-exes in this sequence
  28324. will be added
  28325. @see extractMidiChannelMessages
  28326. */
  28327. void extractSysExMessages (MidiMessageSequence& destSequence) const;
  28328. /** Removes any messages in this sequence that have a specific midi channel.
  28329. @param channelNumberToRemove the midi channel to look for, in the range 1 to 16
  28330. */
  28331. void deleteMidiChannelMessages (int channelNumberToRemove);
  28332. /** Removes any sys-ex messages from this sequence.
  28333. */
  28334. void deleteSysExMessages();
  28335. /** Adds an offset to the timestamps of all events in the sequence.
  28336. @param deltaTime the amount to add to each timestamp.
  28337. */
  28338. void addTimeToMessages (double deltaTime);
  28339. /** Scans through the sequence to determine the state of any midi controllers at
  28340. a given time.
  28341. This will create a sequence of midi controller changes that can be
  28342. used to set all midi controllers to the state they would be in at the
  28343. specified time within this sequence.
  28344. As well as controllers, it will also recreate the midi program number
  28345. and pitch bend position.
  28346. @param channelNumber the midi channel to look for, in the range 1 to 16. Controllers
  28347. for other channels will be ignored.
  28348. @param time the time at which you want to find out the state - there are
  28349. no explicit units for this time measurement, it's the same units
  28350. as used for the timestamps of the messages
  28351. @param resultMessages an array to which midi controller-change messages will be added. This
  28352. will be the minimum number of controller changes to recreate the
  28353. state at the required time.
  28354. */
  28355. void createControllerUpdatesForTime (int channelNumber, double time,
  28356. OwnedArray<MidiMessage>& resultMessages);
  28357. /** Swaps this sequence with another one. */
  28358. void swapWith (MidiMessageSequence& other) throw();
  28359. juce_UseDebuggingNewOperator
  28360. /** @internal */
  28361. static int compareElements (const MidiMessageSequence::MidiEventHolder* first,
  28362. const MidiMessageSequence::MidiEventHolder* second) throw();
  28363. private:
  28364. friend class MidiFile;
  28365. OwnedArray <MidiEventHolder> list;
  28366. void sort();
  28367. };
  28368. #endif // __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28369. /*** End of inlined file: juce_MidiMessageSequence.h ***/
  28370. /**
  28371. Reads/writes standard midi format files.
  28372. To read a midi file, create a MidiFile object and call its readFrom() method. You
  28373. can then get the individual midi tracks from it using the getTrack() method.
  28374. To write a file, create a MidiFile object, add some MidiMessageSequence objects
  28375. to it using the addTrack() method, and then call its writeTo() method to stream
  28376. it out.
  28377. @see MidiMessageSequence
  28378. */
  28379. class JUCE_API MidiFile
  28380. {
  28381. public:
  28382. /** Creates an empty MidiFile object.
  28383. */
  28384. MidiFile();
  28385. /** Destructor. */
  28386. ~MidiFile();
  28387. /** Returns the number of tracks in the file.
  28388. @see getTrack, addTrack
  28389. */
  28390. int getNumTracks() const throw();
  28391. /** Returns a pointer to one of the tracks in the file.
  28392. @returns a pointer to the track, or 0 if the index is out-of-range
  28393. @see getNumTracks, addTrack
  28394. */
  28395. const MidiMessageSequence* getTrack (const int index) const throw();
  28396. /** Adds a midi track to the file.
  28397. This will make its own internal copy of the sequence that is passed-in.
  28398. @see getNumTracks, getTrack
  28399. */
  28400. void addTrack (const MidiMessageSequence& trackSequence);
  28401. /** Removes all midi tracks from the file.
  28402. @see getNumTracks
  28403. */
  28404. void clear();
  28405. /** Returns the raw time format code that will be written to a stream.
  28406. After reading a midi file, this method will return the time-format that
  28407. was read from the file's header. It can be changed using the setTicksPerQuarterNote()
  28408. or setSmpteTimeFormat() methods.
  28409. If the value returned is positive, it indicates the number of midi ticks
  28410. per quarter-note - see setTicksPerQuarterNote().
  28411. It it's negative, the upper byte indicates the frames-per-second (but negative), and
  28412. the lower byte is the number of ticks per frame - see setSmpteTimeFormat().
  28413. */
  28414. short getTimeFormat() const throw();
  28415. /** Sets the time format to use when this file is written to a stream.
  28416. If this is called, the file will be written as bars/beats using the
  28417. specified resolution, rather than SMPTE absolute times, as would be
  28418. used if setSmpteTimeFormat() had been called instead.
  28419. @param ticksPerQuarterNote e.g. 96, 960
  28420. @see setSmpteTimeFormat
  28421. */
  28422. void setTicksPerQuarterNote (const int ticksPerQuarterNote) throw();
  28423. /** Sets the time format to use when this file is written to a stream.
  28424. If this is called, the file will be written using absolute times, rather
  28425. than bars/beats as would be the case if setTicksPerBeat() had been called
  28426. instead.
  28427. @param framesPerSecond must be 24, 25, 29 or 30
  28428. @param subframeResolution the sub-second resolution, e.g. 4 (midi time code),
  28429. 8, 10, 80 (SMPTE bit resolution), or 100. For millisecond
  28430. timing, setSmpteTimeFormat (25, 40)
  28431. @see setTicksPerBeat
  28432. */
  28433. void setSmpteTimeFormat (const int framesPerSecond,
  28434. const int subframeResolution) throw();
  28435. /** Makes a list of all the tempo-change meta-events from all tracks in the midi file.
  28436. Useful for finding the positions of all the tempo changes in a file.
  28437. @param tempoChangeEvents a list to which all the events will be added
  28438. */
  28439. void findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const;
  28440. /** Makes a list of all the time-signature meta-events from all tracks in the midi file.
  28441. Useful for finding the positions of all the tempo changes in a file.
  28442. @param timeSigEvents a list to which all the events will be added
  28443. */
  28444. void findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const;
  28445. /** Returns the latest timestamp in any of the tracks.
  28446. (Useful for finding the length of the file).
  28447. */
  28448. double getLastTimestamp() const;
  28449. /** Reads a midi file format stream.
  28450. After calling this, you can get the tracks that were read from the file by using the
  28451. getNumTracks() and getTrack() methods.
  28452. The timestamps of the midi events in the tracks will represent their positions in
  28453. terms of midi ticks. To convert them to seconds, use the convertTimestampTicksToSeconds()
  28454. method.
  28455. @returns true if the stream was read successfully
  28456. */
  28457. bool readFrom (InputStream& sourceStream);
  28458. /** Writes the midi tracks as a standard midi file.
  28459. @returns true if the operation succeeded.
  28460. */
  28461. bool writeTo (OutputStream& destStream);
  28462. /** Converts the timestamp of all the midi events from midi ticks to seconds.
  28463. This will use the midi time format and tempo/time signature info in the
  28464. tracks to convert all the timestamps to absolute values in seconds.
  28465. */
  28466. void convertTimestampTicksToSeconds();
  28467. juce_UseDebuggingNewOperator
  28468. /** @internal */
  28469. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  28470. const MidiMessageSequence::MidiEventHolder* const second);
  28471. private:
  28472. OwnedArray <MidiMessageSequence> tracks;
  28473. short timeFormat;
  28474. MidiFile (const MidiFile&);
  28475. MidiFile& operator= (const MidiFile&);
  28476. void readNextTrack (const uint8* data, int size);
  28477. void writeTrack (OutputStream& mainOut, const int trackNum);
  28478. };
  28479. #endif // __JUCE_MIDIFILE_JUCEHEADER__
  28480. /*** End of inlined file: juce_MidiFile.h ***/
  28481. #endif
  28482. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28483. /*** Start of inlined file: juce_MidiKeyboardState.h ***/
  28484. #ifndef __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28485. #define __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28486. class MidiKeyboardState;
  28487. /**
  28488. Receives events from a MidiKeyboardState object.
  28489. @see MidiKeyboardState
  28490. */
  28491. class JUCE_API MidiKeyboardStateListener
  28492. {
  28493. public:
  28494. MidiKeyboardStateListener() throw() {}
  28495. virtual ~MidiKeyboardStateListener() {}
  28496. /** Called when one of the MidiKeyboardState's keys is pressed.
  28497. This will be called synchronously when the state is either processing a
  28498. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28499. when a note is being played with its MidiKeyboardState::noteOn() method.
  28500. Note that this callback could happen from an audio callback thread, so be
  28501. careful not to block, and avoid any UI activity in the callback.
  28502. */
  28503. virtual void handleNoteOn (MidiKeyboardState* source,
  28504. int midiChannel, int midiNoteNumber, float velocity) = 0;
  28505. /** Called when one of the MidiKeyboardState's keys is released.
  28506. This will be called synchronously when the state is either processing a
  28507. buffer in its MidiKeyboardState::processNextMidiBuffer() method, or
  28508. when a note is being played with its MidiKeyboardState::noteOff() method.
  28509. Note that this callback could happen from an audio callback thread, so be
  28510. careful not to block, and avoid any UI activity in the callback.
  28511. */
  28512. virtual void handleNoteOff (MidiKeyboardState* source,
  28513. int midiChannel, int midiNoteNumber) = 0;
  28514. };
  28515. /**
  28516. Represents a piano keyboard, keeping track of which keys are currently pressed.
  28517. This object can parse a stream of midi events, using them to update its idea
  28518. of which keys are pressed for each individiual midi channel.
  28519. When keys go up or down, it can broadcast these events to listener objects.
  28520. It also allows key up/down events to be triggered with its noteOn() and noteOff()
  28521. methods, and midi messages for these events will be merged into the
  28522. midi stream that gets processed by processNextMidiBuffer().
  28523. */
  28524. class JUCE_API MidiKeyboardState
  28525. {
  28526. public:
  28527. MidiKeyboardState();
  28528. ~MidiKeyboardState();
  28529. /** Resets the state of the object.
  28530. All internal data for all the channels is reset, but no events are sent as a
  28531. result.
  28532. If you want to release any keys that are currently down, and to send out note-up
  28533. midi messages for this, use the allNotesOff() method instead.
  28534. */
  28535. void reset();
  28536. /** Returns true if the given midi key is currently held down for the given midi channel.
  28537. The channel number must be between 1 and 16. If you want to see if any notes are
  28538. on for a range of channels, use the isNoteOnForChannels() method.
  28539. */
  28540. bool isNoteOn (const int midiChannel, const int midiNoteNumber) const throw();
  28541. /** Returns true if the given midi key is currently held down on any of a set of midi channels.
  28542. The channel mask has a bit set for each midi channel you want to test for - bit
  28543. 0 = midi channel 1, bit 1 = midi channel 2, etc.
  28544. If a note is on for at least one of the specified channels, this returns true.
  28545. */
  28546. bool isNoteOnForChannels (const int midiChannelMask, const int midiNoteNumber) const throw();
  28547. /** Turns a specified note on.
  28548. This will cause a suitable midi note-on event to be injected into the midi buffer during the
  28549. next call to processNextMidiBuffer().
  28550. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28551. gone down.
  28552. */
  28553. void noteOn (const int midiChannel, const int midiNoteNumber, const float velocity);
  28554. /** Turns a specified note off.
  28555. This will cause a suitable midi note-off event to be injected into the midi buffer during the
  28556. next call to processNextMidiBuffer().
  28557. It will also trigger a synchronous callback to the listeners to tell them that the key has
  28558. gone up.
  28559. But if the note isn't acutally down for the given channel, this method will in fact do nothing.
  28560. */
  28561. void noteOff (const int midiChannel, const int midiNoteNumber);
  28562. /** This will turn off any currently-down notes for the given midi channel.
  28563. If you pass 0 for the midi channel, it will in fact turn off all notes on all channels.
  28564. Calling this method will make calls to noteOff(), so can trigger synchronous callbacks
  28565. and events being added to the midi stream.
  28566. */
  28567. void allNotesOff (const int midiChannel);
  28568. /** Looks at a key-up/down event and uses it to update the state of this object.
  28569. To process a buffer full of midi messages, use the processNextMidiBuffer() method
  28570. instead.
  28571. */
  28572. void processNextMidiEvent (const MidiMessage& message);
  28573. /** Scans a midi stream for up/down events and adds its own events to it.
  28574. This will look for any up/down events and use them to update the internal state,
  28575. synchronously making suitable callbacks to the listeners.
  28576. If injectIndirectEvents is true, then midi events to produce the recent noteOn()
  28577. and noteOff() calls will be added into the buffer.
  28578. Only the section of the buffer whose timestamps are between startSample and
  28579. (startSample + numSamples) will be affected, and any events added will be placed
  28580. between these times.
  28581. If you're going to use this method, you'll need to keep calling it regularly for
  28582. it to work satisfactorily.
  28583. To process a single midi event at a time, use the processNextMidiEvent() method
  28584. instead.
  28585. */
  28586. void processNextMidiBuffer (MidiBuffer& buffer,
  28587. const int startSample,
  28588. const int numSamples,
  28589. const bool injectIndirectEvents);
  28590. /** Registers a listener for callbacks when keys go up or down.
  28591. @see removeListener
  28592. */
  28593. void addListener (MidiKeyboardStateListener* const listener) throw();
  28594. /** Deregisters a listener.
  28595. @see addListener
  28596. */
  28597. void removeListener (MidiKeyboardStateListener* const listener) throw();
  28598. juce_UseDebuggingNewOperator
  28599. private:
  28600. CriticalSection lock;
  28601. uint16 noteStates [128];
  28602. MidiBuffer eventsToAdd;
  28603. Array <MidiKeyboardStateListener*> listeners;
  28604. void noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity);
  28605. void noteOffInternal (const int midiChannel, const int midiNoteNumber);
  28606. MidiKeyboardState (const MidiKeyboardState&);
  28607. MidiKeyboardState& operator= (const MidiKeyboardState&);
  28608. };
  28609. #endif // __JUCE_MIDIKEYBOARDSTATE_JUCEHEADER__
  28610. /*** End of inlined file: juce_MidiKeyboardState.h ***/
  28611. #endif
  28612. #ifndef __JUCE_MIDIMESSAGE_JUCEHEADER__
  28613. #endif
  28614. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28615. /*** Start of inlined file: juce_MidiMessageCollector.h ***/
  28616. #ifndef __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28617. #define __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28618. /**
  28619. Collects incoming realtime MIDI messages and turns them into blocks suitable for
  28620. processing by a block-based audio callback.
  28621. The class can also be used as either a MidiKeyboardStateListener or a MidiInputCallback
  28622. so it can easily use a midi input or keyboard component as its source.
  28623. @see MidiMessage, MidiInput
  28624. */
  28625. class JUCE_API MidiMessageCollector : public MidiKeyboardStateListener,
  28626. public MidiInputCallback
  28627. {
  28628. public:
  28629. /** Creates a MidiMessageCollector. */
  28630. MidiMessageCollector();
  28631. /** Destructor. */
  28632. ~MidiMessageCollector();
  28633. /** Clears any messages from the queue.
  28634. You need to call this method before starting to use the collector, so that
  28635. it knows the correct sample rate to use.
  28636. */
  28637. void reset (double sampleRate);
  28638. /** Takes an incoming real-time message and adds it to the queue.
  28639. The message's timestamp is taken, and it will be ready for retrieval as part
  28640. of the block returned by the next call to removeNextBlockOfMessages().
  28641. This method is fully thread-safe when overlapping calls are made with
  28642. removeNextBlockOfMessages().
  28643. */
  28644. void addMessageToQueue (const MidiMessage& message);
  28645. /** Removes all the pending messages from the queue as a buffer.
  28646. This will also correct the messages' timestamps to make sure they're in
  28647. the range 0 to numSamples - 1.
  28648. This call should be made regularly by something like an audio processing
  28649. callback, because the time that it happens is used in calculating the
  28650. midi event positions.
  28651. This method is fully thread-safe when overlapping calls are made with
  28652. addMessageToQueue().
  28653. */
  28654. void removeNextBlockOfMessages (MidiBuffer& destBuffer, int numSamples);
  28655. /** @internal */
  28656. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  28657. /** @internal */
  28658. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  28659. /** @internal */
  28660. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  28661. juce_UseDebuggingNewOperator
  28662. private:
  28663. double lastCallbackTime;
  28664. CriticalSection midiCallbackLock;
  28665. MidiBuffer incomingMessages;
  28666. double sampleRate;
  28667. MidiMessageCollector (const MidiMessageCollector&);
  28668. MidiMessageCollector& operator= (const MidiMessageCollector&);
  28669. };
  28670. #endif // __JUCE_MIDIMESSAGECOLLECTOR_JUCEHEADER__
  28671. /*** End of inlined file: juce_MidiMessageCollector.h ***/
  28672. #endif
  28673. #ifndef __JUCE_MIDIMESSAGESEQUENCE_JUCEHEADER__
  28674. #endif
  28675. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28676. /*** Start of inlined file: juce_AudioUnitPluginFormat.h ***/
  28677. #ifndef __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28678. #define __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  28679. /*** Start of inlined file: juce_AudioPluginFormat.h ***/
  28680. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28681. #define __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  28682. /*** Start of inlined file: juce_AudioPluginInstance.h ***/
  28683. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28684. #define __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  28685. /*** Start of inlined file: juce_AudioProcessor.h ***/
  28686. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28687. #define __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  28688. /*** Start of inlined file: juce_AudioProcessorEditor.h ***/
  28689. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28690. #define __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28691. class AudioProcessor;
  28692. /**
  28693. Base class for the component that acts as the GUI for an AudioProcessor.
  28694. Derive your editor component from this class, and create an instance of it
  28695. by overriding the AudioProcessor::createEditor() method.
  28696. @see AudioProcessor, GenericAudioProcessorEditor
  28697. */
  28698. class JUCE_API AudioProcessorEditor : public Component
  28699. {
  28700. protected:
  28701. /** Creates an editor for the specified processor.
  28702. */
  28703. AudioProcessorEditor (AudioProcessor* const owner);
  28704. public:
  28705. /** Destructor. */
  28706. ~AudioProcessorEditor();
  28707. /** Returns a pointer to the processor that this editor represents. */
  28708. AudioProcessor* getAudioProcessor() const throw() { return owner; }
  28709. private:
  28710. AudioProcessor* const owner;
  28711. AudioProcessorEditor (const AudioProcessorEditor&);
  28712. AudioProcessorEditor& operator= (const AudioProcessorEditor&);
  28713. };
  28714. #endif // __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  28715. /*** End of inlined file: juce_AudioProcessorEditor.h ***/
  28716. /*** Start of inlined file: juce_AudioProcessorListener.h ***/
  28717. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28718. #define __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28719. class AudioProcessor;
  28720. /**
  28721. Base class for listeners that want to know about changes to an AudioProcessor.
  28722. Use AudioProcessor::addListener() to register your listener with an AudioProcessor.
  28723. @see AudioProcessor
  28724. */
  28725. class JUCE_API AudioProcessorListener
  28726. {
  28727. public:
  28728. /** Destructor. */
  28729. virtual ~AudioProcessorListener() {}
  28730. /** Receives a callback when a parameter is changed.
  28731. IMPORTANT NOTE: this will be called synchronously when a parameter changes, and
  28732. many audio processors will change their parameter during their audio callback.
  28733. This means that not only has your handler code got to be completely thread-safe,
  28734. but it's also got to be VERY fast, and avoid blocking. If you need to handle
  28735. this event on your message thread, use this callback to trigger an AsyncUpdater
  28736. or ChangeBroadcaster which you can respond to on the message thread.
  28737. */
  28738. virtual void audioProcessorParameterChanged (AudioProcessor* processor,
  28739. int parameterIndex,
  28740. float newValue) = 0;
  28741. /** Called to indicate that something else in the plugin has changed, like its
  28742. program, number of parameters, etc.
  28743. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28744. call it during their audio callback. This means that not only has your handler code
  28745. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28746. blocking. If you need to handle this event on your message thread, use this callback
  28747. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28748. message thread.
  28749. */
  28750. virtual void audioProcessorChanged (AudioProcessor* processor) = 0;
  28751. /** Indicates that a parameter change gesture has started.
  28752. E.g. if the user is dragging a slider, this would be called when they first
  28753. press the mouse button, and audioProcessorParameterChangeGestureEnd would be
  28754. called when they release it.
  28755. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28756. call it during their audio callback. This means that not only has your handler code
  28757. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28758. blocking. If you need to handle this event on your message thread, use this callback
  28759. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28760. message thread.
  28761. @see audioProcessorParameterChangeGestureEnd
  28762. */
  28763. virtual void audioProcessorParameterChangeGestureBegin (AudioProcessor* processor,
  28764. int parameterIndex);
  28765. /** Indicates that a parameter change gesture has finished.
  28766. E.g. if the user is dragging a slider, this would be called when they release
  28767. the mouse button.
  28768. IMPORTANT NOTE: this will be called synchronously, and many audio processors will
  28769. call it during their audio callback. This means that not only has your handler code
  28770. got to be completely thread-safe, but it's also got to be VERY fast, and avoid
  28771. blocking. If you need to handle this event on your message thread, use this callback
  28772. to trigger an AsyncUpdater or ChangeBroadcaster which you can respond to later on the
  28773. message thread.
  28774. @see audioPluginParameterChangeGestureStart
  28775. */
  28776. virtual void audioProcessorParameterChangeGestureEnd (AudioProcessor* processor,
  28777. int parameterIndex);
  28778. };
  28779. #endif // __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  28780. /*** End of inlined file: juce_AudioProcessorListener.h ***/
  28781. /*** Start of inlined file: juce_AudioPlayHead.h ***/
  28782. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28783. #define __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28784. /**
  28785. A subclass of AudioPlayHead can supply information about the position and
  28786. status of a moving play head during audio playback.
  28787. One of these can be supplied to an AudioProcessor object so that it can find
  28788. out about the position of the audio that it is rendering.
  28789. @see AudioProcessor::setPlayHead, AudioProcessor::getPlayHead
  28790. */
  28791. class JUCE_API AudioPlayHead
  28792. {
  28793. protected:
  28794. AudioPlayHead() {}
  28795. public:
  28796. virtual ~AudioPlayHead() {}
  28797. /** Frame rate types. */
  28798. enum FrameRateType
  28799. {
  28800. fps24 = 0,
  28801. fps25 = 1,
  28802. fps2997 = 2,
  28803. fps30 = 3,
  28804. fps2997drop = 4,
  28805. fps30drop = 5,
  28806. fpsUnknown = 99
  28807. };
  28808. /** This structure is filled-in by the AudioPlayHead::getCurrentPosition() method.
  28809. */
  28810. struct CurrentPositionInfo
  28811. {
  28812. /** The tempo in BPM */
  28813. double bpm;
  28814. /** Time signature numerator, e.g. the 3 of a 3/4 time sig */
  28815. int timeSigNumerator;
  28816. /** Time signature denominator, e.g. the 4 of a 3/4 time sig */
  28817. int timeSigDenominator;
  28818. /** The current play position, in seconds from the start of the edit. */
  28819. double timeInSeconds;
  28820. /** For timecode, the position of the start of the edit, in seconds from 00:00:00:00. */
  28821. double editOriginTime;
  28822. /** The current play position in pulses-per-quarter-note.
  28823. This is the number of quarter notes since the edit start.
  28824. */
  28825. double ppqPosition;
  28826. /** The position of the start of the last bar, in pulses-per-quarter-note.
  28827. This is the number of quarter notes from the start of the edit to the
  28828. start of the current bar.
  28829. Note - this value may be unavailable on some hosts, e.g. Pro-Tools. If
  28830. it's not available, the value will be 0.
  28831. */
  28832. double ppqPositionOfLastBarStart;
  28833. /** The video frame rate, if applicable. */
  28834. FrameRateType frameRate;
  28835. /** True if the transport is currently playing. */
  28836. bool isPlaying;
  28837. /** True if the transport is currently recording.
  28838. (When isRecording is true, then isPlaying will also be true).
  28839. */
  28840. bool isRecording;
  28841. bool operator== (const CurrentPositionInfo& other) const throw();
  28842. bool operator!= (const CurrentPositionInfo& other) const throw();
  28843. void resetToDefault();
  28844. };
  28845. /** Fills-in the given structure with details about the transport's
  28846. position at the start of the current processing block.
  28847. */
  28848. virtual bool getCurrentPosition (CurrentPositionInfo& result) = 0;
  28849. };
  28850. #endif // __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  28851. /*** End of inlined file: juce_AudioPlayHead.h ***/
  28852. /**
  28853. Base class for audio processing filters or plugins.
  28854. This is intended to act as a base class of audio filter that is general enough to
  28855. be wrapped as a VST, AU, RTAS, etc, or used internally.
  28856. It is also used by the plugin hosting code as the wrapper around an instance
  28857. of a loaded plugin.
  28858. Derive your filter class from this base class, and if you're building a plugin,
  28859. you should implement a global function called createPluginFilter() which creates
  28860. and returns a new instance of your subclass.
  28861. */
  28862. class JUCE_API AudioProcessor
  28863. {
  28864. protected:
  28865. /** Constructor.
  28866. You can also do your initialisation tasks in the initialiseFilterInfo()
  28867. call, which will be made after this object has been created.
  28868. */
  28869. AudioProcessor();
  28870. public:
  28871. /** Destructor. */
  28872. virtual ~AudioProcessor();
  28873. /** Returns the name of this processor.
  28874. */
  28875. virtual const String getName() const = 0;
  28876. /** Called before playback starts, to let the filter prepare itself.
  28877. The sample rate is the target sample rate, and will remain constant until
  28878. playback stops.
  28879. The estimatedSamplesPerBlock value is a HINT about the typical number of
  28880. samples that will be processed for each callback, but isn't any kind
  28881. of guarantee. The actual block sizes that the host uses may be different
  28882. each time the callback happens, and may be more or less than this value.
  28883. */
  28884. virtual void prepareToPlay (double sampleRate,
  28885. int estimatedSamplesPerBlock) = 0;
  28886. /** Called after playback has stopped, to let the filter free up any resources it
  28887. no longer needs.
  28888. */
  28889. virtual void releaseResources() = 0;
  28890. /** Renders the next block.
  28891. When this method is called, the buffer contains a number of channels which is
  28892. at least as great as the maximum number of input and output channels that
  28893. this filter is using. It will be filled with the filter's input data and
  28894. should be replaced with the filter's output.
  28895. So for example if your filter has 2 input channels and 4 output channels, then
  28896. the buffer will contain 4 channels, the first two being filled with the
  28897. input data. Your filter should read these, do its processing, and replace
  28898. the contents of all 4 channels with its output.
  28899. Or if your filter has 5 inputs and 2 outputs, the buffer will have 5 channels,
  28900. all filled with data, and your filter should overwrite the first 2 of these
  28901. with its output. But be VERY careful not to write anything to the last 3
  28902. channels, as these might be mapped to memory that the host assumes is read-only!
  28903. Note that if you have more outputs than inputs, then only those channels that
  28904. correspond to an input channel are guaranteed to contain sensible data - e.g.
  28905. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  28906. but the last two channels may contain garbage, so you should be careful not to
  28907. let this pass through without being overwritten or cleared.
  28908. Also note that the buffer may have more channels than are strictly necessary,
  28909. but your should only read/write from the ones that your filter is supposed to
  28910. be using.
  28911. The number of samples in these buffers is NOT guaranteed to be the same for every
  28912. callback, and may be more or less than the estimated value given to prepareToPlay().
  28913. Your code must be able to cope with variable-sized blocks, or you're going to get
  28914. clicks and crashes!
  28915. If the filter is receiving a midi input, then the midiMessages array will be filled
  28916. with the midi messages for this block. Each message's timestamp will indicate the
  28917. message's time, as a number of samples from the start of the block.
  28918. Any messages left in the midi buffer when this method has finished are assumed to
  28919. be the filter's midi output. This means that your filter should be careful to
  28920. clear any incoming messages from the array if it doesn't want them to be passed-on.
  28921. Be very careful about what you do in this callback - it's going to be called by
  28922. the audio thread, so any kind of interaction with the UI is absolutely
  28923. out of the question. If you change a parameter in here and need to tell your UI to
  28924. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  28925. the UI components register as listeners, and then call sendChangeMessage() inside the
  28926. processBlock() method to send out an asynchronous message. You could also use
  28927. the AsyncUpdater class in a similar way.
  28928. */
  28929. virtual void processBlock (AudioSampleBuffer& buffer,
  28930. MidiBuffer& midiMessages) = 0;
  28931. /** Returns the current AudioPlayHead object that should be used to find
  28932. out the state and position of the playhead.
  28933. You can call this from your processBlock() method, and use the AudioPlayHead
  28934. object to get the details about the time of the start of the block currently
  28935. being processed.
  28936. If the host hasn't supplied a playhead object, this will return 0.
  28937. */
  28938. AudioPlayHead* getPlayHead() const throw() { return playHead; }
  28939. /** Returns the current sample rate.
  28940. This can be called from your processBlock() method - it's not guaranteed
  28941. to be valid at any other time, and may return 0 if it's unknown.
  28942. */
  28943. double getSampleRate() const throw() { return sampleRate; }
  28944. /** Returns the current typical block size that is being used.
  28945. This can be called from your processBlock() method - it's not guaranteed
  28946. to be valid at any other time.
  28947. Remember it's not the ONLY block size that may be used when calling
  28948. processBlock, it's just the normal one. The actual block sizes used may be
  28949. larger or smaller than this, and will vary between successive calls.
  28950. */
  28951. int getBlockSize() const throw() { return blockSize; }
  28952. /** Returns the number of input channels that the host will be sending the filter.
  28953. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28954. number of channels that your filter would prefer to have, and this method lets
  28955. you know how many the host is actually using.
  28956. Note that this method is only valid during or after the prepareToPlay()
  28957. method call. Until that point, the number of channels will be unknown.
  28958. */
  28959. int getNumInputChannels() const throw() { return numInputChannels; }
  28960. /** Returns the number of output channels that the host will be sending the filter.
  28961. If writing a plugin, your JucePluginCharacteristics.h file should specify the
  28962. number of channels that your filter would prefer to have, and this method lets
  28963. you know how many the host is actually using.
  28964. Note that this method is only valid during or after the prepareToPlay()
  28965. method call. Until that point, the number of channels will be unknown.
  28966. */
  28967. int getNumOutputChannels() const throw() { return numOutputChannels; }
  28968. /** Returns the name of one of the input channels, as returned by the host.
  28969. The host might not supply very useful names for channels, and this might be
  28970. something like "1", "2", "left", "right", etc.
  28971. */
  28972. virtual const String getInputChannelName (const int channelIndex) const = 0;
  28973. /** Returns the name of one of the output channels, as returned by the host.
  28974. The host might not supply very useful names for channels, and this might be
  28975. something like "1", "2", "left", "right", etc.
  28976. */
  28977. virtual const String getOutputChannelName (const int channelIndex) const = 0;
  28978. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28979. virtual bool isInputChannelStereoPair (int index) const = 0;
  28980. /** Returns true if the specified channel is part of a stereo pair with its neighbour. */
  28981. virtual bool isOutputChannelStereoPair (int index) const = 0;
  28982. /** This returns the number of samples delay that the filter imposes on the audio
  28983. passing through it.
  28984. The host will call this to find the latency - the filter itself should set this value
  28985. by calling setLatencySamples() as soon as it can during its initialisation.
  28986. */
  28987. int getLatencySamples() const throw() { return latencySamples; }
  28988. /** The filter should call this to set the number of samples delay that it introduces.
  28989. The filter should call this as soon as it can during initialisation, and can call it
  28990. later if the value changes.
  28991. */
  28992. void setLatencySamples (const int newLatency);
  28993. /** Returns true if the processor wants midi messages. */
  28994. virtual bool acceptsMidi() const = 0;
  28995. /** Returns true if the processor produces midi messages. */
  28996. virtual bool producesMidi() const = 0;
  28997. /** This returns a critical section that will automatically be locked while the host
  28998. is calling the processBlock() method.
  28999. Use it from your UI or other threads to lock access to variables that are used
  29000. by the process callback, but obviously be careful not to keep it locked for
  29001. too long, because that could cause stuttering playback. If you need to do something
  29002. that'll take a long time and need the processing to stop while it happens, use the
  29003. suspendProcessing() method instead.
  29004. @see suspendProcessing
  29005. */
  29006. const CriticalSection& getCallbackLock() const throw() { return callbackLock; }
  29007. /** Enables and disables the processing callback.
  29008. If you need to do something time-consuming on a thread and would like to make sure
  29009. the audio processing callback doesn't happen until you've finished, use this
  29010. to disable the callback and re-enable it again afterwards.
  29011. E.g.
  29012. @code
  29013. void loadNewPatch()
  29014. {
  29015. suspendProcessing (true);
  29016. ..do something that takes ages..
  29017. suspendProcessing (false);
  29018. }
  29019. @endcode
  29020. If the host tries to make an audio callback while processing is suspended, the
  29021. filter will return an empty buffer, but won't block the audio thread like it would
  29022. do if you use the getCallbackLock() critical section to synchronise access.
  29023. If you're going to use this, your processBlock() method must call isSuspended() and
  29024. check whether it's suspended or not. If it is, then it should skip doing any real
  29025. processing, either emitting silence or passing the input through unchanged.
  29026. @see getCallbackLock
  29027. */
  29028. void suspendProcessing (const bool shouldBeSuspended);
  29029. /** Returns true if processing is currently suspended.
  29030. @see suspendProcessing
  29031. */
  29032. bool isSuspended() const throw() { return suspended; }
  29033. /** A plugin can override this to be told when it should reset any playing voices.
  29034. The default implementation does nothing, but a host may call this to tell the
  29035. plugin that it should stop any tails or sounds that have been left running.
  29036. */
  29037. virtual void reset();
  29038. /** Returns true if the processor is being run in an offline mode for rendering.
  29039. If the processor is being run live on realtime signals, this returns false.
  29040. If the mode is unknown, this will assume it's realtime and return false.
  29041. This value may be unreliable until the prepareToPlay() method has been called,
  29042. and could change each time prepareToPlay() is called.
  29043. @see setNonRealtime()
  29044. */
  29045. bool isNonRealtime() const throw() { return nonRealtime; }
  29046. /** Called by the host to tell this processor whether it's being used in a non-realime
  29047. capacity for offline rendering or bouncing.
  29048. Whatever value is passed-in will be
  29049. */
  29050. void setNonRealtime (const bool isNonRealtime) throw();
  29051. /** Creates the filter's UI.
  29052. This can return 0 if you want a UI-less filter, in which case the host may create
  29053. a generic UI that lets the user twiddle the parameters directly.
  29054. If you do want to pass back a component, the component should be created and set to
  29055. the correct size before returning it.
  29056. Remember not to do anything silly like allowing your filter to keep a pointer to
  29057. the component that gets created - it could be deleted later without any warning, which
  29058. would make your pointer into a dangler. Use the getActiveEditor() method instead.
  29059. The correct way to handle the connection between an editor component and its
  29060. filter is to use something like a ChangeBroadcaster so that the editor can
  29061. register itself as a listener, and be told when a change occurs. This lets them
  29062. safely unregister themselves when they are deleted.
  29063. Here are a few things to bear in mind when writing an editor:
  29064. - Initially there won't be an editor, until the user opens one, or they might
  29065. not open one at all. Your filter mustn't rely on it being there.
  29066. - An editor object may be deleted and a replacement one created again at any time.
  29067. - It's safe to assume that an editor will be deleted before its filter.
  29068. */
  29069. virtual AudioProcessorEditor* createEditor() = 0;
  29070. /** Returns the active editor, if there is one.
  29071. Bear in mind this can return 0, even if an editor has previously been
  29072. opened.
  29073. */
  29074. AudioProcessorEditor* getActiveEditor() const throw() { return activeEditor; }
  29075. /** Returns the active editor, or if there isn't one, it will create one.
  29076. This may call createEditor() internally to create the component.
  29077. */
  29078. AudioProcessorEditor* createEditorIfNeeded();
  29079. /** This must return the correct value immediately after the object has been
  29080. created, and mustn't change the number of parameters later.
  29081. */
  29082. virtual int getNumParameters() = 0;
  29083. /** Returns the name of a particular parameter. */
  29084. virtual const String getParameterName (int parameterIndex) = 0;
  29085. /** Called by the host to find out the value of one of the filter's parameters.
  29086. The host will expect the value returned to be between 0 and 1.0.
  29087. This could be called quite frequently, so try to make your code efficient.
  29088. It's also likely to be called by non-UI threads, so the code in here should
  29089. be thread-aware.
  29090. */
  29091. virtual float getParameter (int parameterIndex) = 0;
  29092. /** Returns the value of a parameter as a text string. */
  29093. virtual const String getParameterText (int parameterIndex) = 0;
  29094. /** The host will call this method to change the value of one of the filter's parameters.
  29095. The host may call this at any time, including during the audio processing
  29096. callback, so the filter has to process this very fast and avoid blocking.
  29097. If you want to set the value of a parameter internally, e.g. from your
  29098. editor component, then don't call this directly - instead, use the
  29099. setParameterNotifyingHost() method, which will also send a message to
  29100. the host telling it about the change. If the message isn't sent, the host
  29101. won't be able to automate your parameters properly.
  29102. The value passed will be between 0 and 1.0.
  29103. */
  29104. virtual void setParameter (int parameterIndex,
  29105. float newValue) = 0;
  29106. /** Your filter can call this when it needs to change one of its parameters.
  29107. This could happen when the editor or some other internal operation changes
  29108. a parameter. This method will call the setParameter() method to change the
  29109. value, and will then send a message to the host telling it about the change.
  29110. Note that to make sure the host correctly handles automation, you should call
  29111. the beginParameterChangeGesture() and endParameterChangeGesture() methods to
  29112. tell the host when the user has started and stopped changing the parameter.
  29113. */
  29114. void setParameterNotifyingHost (int parameterIndex,
  29115. float newValue);
  29116. /** Returns true if the host can automate this parameter.
  29117. By default, this returns true for all parameters.
  29118. */
  29119. virtual bool isParameterAutomatable (int parameterIndex) const;
  29120. /** Should return true if this parameter is a "meta" parameter.
  29121. A meta-parameter is a parameter that changes other params. It is used
  29122. by some hosts (e.g. AudioUnit hosts).
  29123. By default this returns false.
  29124. */
  29125. virtual bool isMetaParameter (int parameterIndex) const;
  29126. /** Sends a signal to the host to tell it that the user is about to start changing this
  29127. parameter.
  29128. This allows the host to know when a parameter is actively being held by the user, and
  29129. it may use this information to help it record automation.
  29130. If you call this, it must be matched by a later call to endParameterChangeGesture().
  29131. */
  29132. void beginParameterChangeGesture (int parameterIndex);
  29133. /** Tells the host that the user has finished changing this parameter.
  29134. This allows the host to know when a parameter is actively being held by the user, and
  29135. it may use this information to help it record automation.
  29136. A call to this method must follow a call to beginParameterChangeGesture().
  29137. */
  29138. void endParameterChangeGesture (int parameterIndex);
  29139. /** The filter can call this when something (apart from a parameter value) has changed.
  29140. It sends a hint to the host that something like the program, number of parameters,
  29141. etc, has changed, and that it should update itself.
  29142. */
  29143. void updateHostDisplay();
  29144. /** Returns the number of preset programs the filter supports.
  29145. The value returned must be valid as soon as this object is created, and
  29146. must not change over its lifetime.
  29147. This value shouldn't be less than 1.
  29148. */
  29149. virtual int getNumPrograms() = 0;
  29150. /** Returns the number of the currently active program.
  29151. */
  29152. virtual int getCurrentProgram() = 0;
  29153. /** Called by the host to change the current program.
  29154. */
  29155. virtual void setCurrentProgram (int index) = 0;
  29156. /** Must return the name of a given program. */
  29157. virtual const String getProgramName (int index) = 0;
  29158. /** Called by the host to rename a program.
  29159. */
  29160. virtual void changeProgramName (int index, const String& newName) = 0;
  29161. /** The host will call this method when it wants to save the filter's internal state.
  29162. This must copy any info about the filter's state into the block of memory provided,
  29163. so that the host can store this and later restore it using setStateInformation().
  29164. Note that there's also a getCurrentProgramStateInformation() method, which only
  29165. stores the current program, not the state of the entire filter.
  29166. See also the helper function copyXmlToBinary() for storing settings as XML.
  29167. @see getCurrentProgramStateInformation
  29168. */
  29169. virtual void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData) = 0;
  29170. /** The host will call this method if it wants to save the state of just the filter's
  29171. current program.
  29172. Unlike getStateInformation, this should only return the current program's state.
  29173. Not all hosts support this, and if you don't implement it, the base class
  29174. method just calls getStateInformation() instead. If you do implement it, be
  29175. sure to also implement getCurrentProgramStateInformation.
  29176. @see getStateInformation, setCurrentProgramStateInformation
  29177. */
  29178. virtual void getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  29179. /** This must restore the filter's state from a block of data previously created
  29180. using getStateInformation().
  29181. Note that there's also a setCurrentProgramStateInformation() method, which tries
  29182. to restore just the current program, not the state of the entire filter.
  29183. See also the helper function getXmlFromBinary() for loading settings as XML.
  29184. @see setCurrentProgramStateInformation
  29185. */
  29186. virtual void setStateInformation (const void* data, int sizeInBytes) = 0;
  29187. /** The host will call this method if it wants to restore the state of just the filter's
  29188. current program.
  29189. Not all hosts support this, and if you don't implement it, the base class
  29190. method just calls setStateInformation() instead. If you do implement it, be
  29191. sure to also implement getCurrentProgramStateInformation.
  29192. @see setStateInformation, getCurrentProgramStateInformation
  29193. */
  29194. virtual void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  29195. /** Adds a listener that will be called when an aspect of this processor changes. */
  29196. void addListener (AudioProcessorListener* const newListener) throw();
  29197. /** Removes a previously added listener. */
  29198. void removeListener (AudioProcessorListener* const listenerToRemove) throw();
  29199. /** Not for public use - this is called before deleting an editor component. */
  29200. void editorBeingDeleted (AudioProcessorEditor* const editor) throw();
  29201. /** Not for public use - this is called to initialise the processor. */
  29202. void setPlayHead (AudioPlayHead* const newPlayHead) throw();
  29203. /** Not for public use - this is called to initialise the processor before playing. */
  29204. void setPlayConfigDetails (const int numIns, const int numOuts,
  29205. const double sampleRate,
  29206. const int blockSize) throw();
  29207. juce_UseDebuggingNewOperator
  29208. protected:
  29209. /** Helper function that just converts an xml element into a binary blob.
  29210. Use this in your filter's getStateInformation() method if you want to
  29211. store its state as xml.
  29212. Then use getXmlFromBinary() to reverse this operation and retrieve the XML
  29213. from a binary blob.
  29214. */
  29215. static void copyXmlToBinary (const XmlElement& xml,
  29216. JUCE_NAMESPACE::MemoryBlock& destData);
  29217. /** Retrieves an XML element that was stored as binary with the copyXmlToBinary() method.
  29218. This might return 0 if the data's unsuitable or corrupted. Otherwise it will return
  29219. an XmlElement object that the caller must delete when no longer needed.
  29220. */
  29221. static XmlElement* getXmlFromBinary (const void* data,
  29222. const int sizeInBytes);
  29223. /** @internal */
  29224. AudioPlayHead* playHead;
  29225. /** @internal */
  29226. void sendParamChangeMessageToListeners (const int parameterIndex, const float newValue);
  29227. private:
  29228. Array <AudioProcessorListener*> listeners;
  29229. AudioProcessorEditor* activeEditor;
  29230. double sampleRate;
  29231. int blockSize, numInputChannels, numOutputChannels, latencySamples;
  29232. bool suspended, nonRealtime;
  29233. CriticalSection callbackLock, listenerLock;
  29234. #if JUCE_DEBUG
  29235. BigInteger changingParams;
  29236. #endif
  29237. AudioProcessor (const AudioProcessor&);
  29238. AudioProcessor& operator= (const AudioProcessor&);
  29239. };
  29240. #endif // __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  29241. /*** End of inlined file: juce_AudioProcessor.h ***/
  29242. /*** Start of inlined file: juce_PluginDescription.h ***/
  29243. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29244. #define __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29245. /**
  29246. A small class to represent some facts about a particular type of plugin.
  29247. This class is for storing and managing the details about a plugin without
  29248. actually having to load an instance of it.
  29249. A KnownPluginList contains a list of PluginDescription objects.
  29250. @see KnownPluginList
  29251. */
  29252. class JUCE_API PluginDescription
  29253. {
  29254. public:
  29255. PluginDescription() throw();
  29256. PluginDescription (const PluginDescription& other) throw();
  29257. PluginDescription& operator= (const PluginDescription& other) throw();
  29258. ~PluginDescription() throw();
  29259. /** The name of the plugin. */
  29260. String name;
  29261. /** The plugin format, e.g. "VST", "AudioUnit", etc.
  29262. */
  29263. String pluginFormatName;
  29264. /** A category, such as "Dynamics", "Reverbs", etc.
  29265. */
  29266. String category;
  29267. /** The manufacturer. */
  29268. String manufacturerName;
  29269. /** The version. This string doesn't have any particular format. */
  29270. String version;
  29271. /** Either the file containing the plugin module, or some other unique way
  29272. of identifying it.
  29273. E.g. for an AU, this would be an ID string that the component manager
  29274. could use to retrieve the plugin. For a VST, it's the file path.
  29275. */
  29276. String fileOrIdentifier;
  29277. /** The last time the plugin file was changed.
  29278. This is handy when scanning for new or changed plugins.
  29279. */
  29280. Time lastFileModTime;
  29281. /** A unique ID for the plugin.
  29282. Note that this might not be unique between formats, e.g. a VST and some
  29283. other format might actually have the same id.
  29284. @see createIdentifierString
  29285. */
  29286. int uid;
  29287. /** True if the plugin identifies itself as a synthesiser. */
  29288. bool isInstrument;
  29289. /** The number of inputs. */
  29290. int numInputChannels;
  29291. /** The number of outputs. */
  29292. int numOutputChannels;
  29293. /** Returns true if the two descriptions refer the the same plugin.
  29294. This isn't quite as simple as them just having the same file (because of
  29295. shell plugins).
  29296. */
  29297. bool isDuplicateOf (const PluginDescription& other) const;
  29298. /** Returns a string that can be saved and used to uniquely identify the
  29299. plugin again.
  29300. This contains less info than the XML encoding, and is independent of the
  29301. plugin's file location, so can be used to store a plugin ID for use
  29302. across different machines.
  29303. */
  29304. const String createIdentifierString() const throw();
  29305. /** Creates an XML object containing these details.
  29306. @see loadFromXml
  29307. */
  29308. XmlElement* createXml() const;
  29309. /** Reloads the info in this structure from an XML record that was previously
  29310. saved with createXML().
  29311. Returns true if the XML was a valid plugin description.
  29312. */
  29313. bool loadFromXml (const XmlElement& xml);
  29314. juce_UseDebuggingNewOperator
  29315. };
  29316. #endif // __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29317. /*** End of inlined file: juce_PluginDescription.h ***/
  29318. /**
  29319. Base class for an active instance of a plugin.
  29320. This derives from the AudioProcessor class, and adds some extra functionality
  29321. that helps when wrapping dynamically loaded plugins.
  29322. @see AudioProcessor, AudioPluginFormat
  29323. */
  29324. class JUCE_API AudioPluginInstance : public AudioProcessor
  29325. {
  29326. public:
  29327. /** Destructor.
  29328. Make sure that you delete any UI components that belong to this plugin before
  29329. deleting the plugin.
  29330. */
  29331. virtual ~AudioPluginInstance();
  29332. /** Fills-in the appropriate parts of this plugin description object.
  29333. */
  29334. virtual void fillInPluginDescription (PluginDescription& description) const = 0;
  29335. juce_UseDebuggingNewOperator
  29336. protected:
  29337. AudioPluginInstance();
  29338. AudioPluginInstance (const AudioPluginInstance&);
  29339. AudioPluginInstance& operator= (const AudioPluginInstance&);
  29340. };
  29341. #endif // __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29342. /*** End of inlined file: juce_AudioPluginInstance.h ***/
  29343. class PluginDescription;
  29344. /**
  29345. The base class for a type of plugin format, such as VST, AudioUnit, LADSPA, etc.
  29346. Use the static getNumFormats() and getFormat() calls to find the types
  29347. of format that are available.
  29348. */
  29349. class JUCE_API AudioPluginFormat
  29350. {
  29351. public:
  29352. /** Destructor. */
  29353. virtual ~AudioPluginFormat();
  29354. /** Returns the format name.
  29355. E.g. "VST", "AudioUnit", etc.
  29356. */
  29357. virtual const String getName() const = 0;
  29358. /** This tries to create descriptions for all the plugin types available in
  29359. a binary module file.
  29360. The file will be some kind of DLL or bundle.
  29361. Normally there will only be one type returned, but some plugins
  29362. (e.g. VST shells) can use a single DLL to create a set of different plugin
  29363. subtypes, so in that case, each subtype is returned as a separate object.
  29364. */
  29365. virtual void findAllTypesForFile (OwnedArray <PluginDescription>& results,
  29366. const String& fileOrIdentifier) = 0;
  29367. /** Tries to recreate a type from a previously generated PluginDescription.
  29368. @see PluginDescription::createInstance
  29369. */
  29370. virtual AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc) = 0;
  29371. /** Should do a quick check to see if this file or directory might be a plugin of
  29372. this format.
  29373. This is for searching for potential files, so it shouldn't actually try to
  29374. load the plugin or do anything time-consuming.
  29375. */
  29376. virtual bool fileMightContainThisPluginType (const String& fileOrIdentifier) = 0;
  29377. /** Returns a readable version of the name of the plugin that this identifier refers to.
  29378. */
  29379. virtual const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) = 0;
  29380. /** Checks whether this plugin could possibly be loaded.
  29381. It doesn't actually need to load it, just to check whether the file or component
  29382. still exists.
  29383. */
  29384. virtual bool doesPluginStillExist (const PluginDescription& desc) = 0;
  29385. /** Searches a suggested set of directories for any plugins in this format.
  29386. The path might be ignored, e.g. by AUs, which are found by the OS rather
  29387. than manually.
  29388. */
  29389. virtual const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch,
  29390. bool recursive) = 0;
  29391. /** Returns the typical places to look for this kind of plugin.
  29392. Note that if this returns no paths, it means that the format can't be scanned-for
  29393. (i.e. it's an internal format that doesn't live in files)
  29394. */
  29395. virtual const FileSearchPath getDefaultLocationsToSearch() = 0;
  29396. juce_UseDebuggingNewOperator
  29397. protected:
  29398. AudioPluginFormat() throw();
  29399. AudioPluginFormat (const AudioPluginFormat&);
  29400. AudioPluginFormat& operator= (const AudioPluginFormat&);
  29401. };
  29402. #endif // __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29403. /*** End of inlined file: juce_AudioPluginFormat.h ***/
  29404. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  29405. /**
  29406. Implements a plugin format manager for AudioUnits.
  29407. */
  29408. class JUCE_API AudioUnitPluginFormat : public AudioPluginFormat
  29409. {
  29410. public:
  29411. AudioUnitPluginFormat();
  29412. ~AudioUnitPluginFormat();
  29413. const String getName() const { return "AudioUnit"; }
  29414. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29415. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29416. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29417. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29418. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29419. bool doesPluginStillExist (const PluginDescription& desc);
  29420. const FileSearchPath getDefaultLocationsToSearch();
  29421. juce_UseDebuggingNewOperator
  29422. private:
  29423. AudioUnitPluginFormat (const AudioUnitPluginFormat&);
  29424. AudioUnitPluginFormat& operator= (const AudioUnitPluginFormat&);
  29425. };
  29426. #endif
  29427. #endif // __JUCE_AUDIOUNITPLUGINFORMAT_JUCEHEADER__
  29428. /*** End of inlined file: juce_AudioUnitPluginFormat.h ***/
  29429. #endif
  29430. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29431. /*** Start of inlined file: juce_DirectXPluginFormat.h ***/
  29432. #ifndef __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29433. #define __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29434. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  29435. // Sorry, this file is just a placeholder at the moment!...
  29436. /**
  29437. Implements a plugin format manager for DirectX plugins.
  29438. */
  29439. class JUCE_API DirectXPluginFormat : public AudioPluginFormat
  29440. {
  29441. public:
  29442. DirectXPluginFormat();
  29443. ~DirectXPluginFormat();
  29444. const String getName() const { return "DirectX"; }
  29445. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29446. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29447. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29448. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29449. const FileSearchPath getDefaultLocationsToSearch();
  29450. juce_UseDebuggingNewOperator
  29451. private:
  29452. DirectXPluginFormat (const DirectXPluginFormat&);
  29453. DirectXPluginFormat& operator= (const DirectXPluginFormat&);
  29454. };
  29455. #endif
  29456. #endif // __JUCE_DIRECTXPLUGINFORMAT_JUCEHEADER__
  29457. /*** End of inlined file: juce_DirectXPluginFormat.h ***/
  29458. #endif
  29459. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29460. /*** Start of inlined file: juce_LADSPAPluginFormat.h ***/
  29461. #ifndef __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29462. #define __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29463. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  29464. // Sorry, this file is just a placeholder at the moment!...
  29465. /**
  29466. Implements a plugin format manager for DirectX plugins.
  29467. */
  29468. class JUCE_API LADSPAPluginFormat : public AudioPluginFormat
  29469. {
  29470. public:
  29471. LADSPAPluginFormat();
  29472. ~LADSPAPluginFormat();
  29473. const String getName() const { return "LADSPA"; }
  29474. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29475. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29476. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29477. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier) { return fileOrIdentifier; }
  29478. const FileSearchPath getDefaultLocationsToSearch();
  29479. juce_UseDebuggingNewOperator
  29480. private:
  29481. LADSPAPluginFormat (const LADSPAPluginFormat&);
  29482. LADSPAPluginFormat& operator= (const LADSPAPluginFormat&);
  29483. };
  29484. #endif
  29485. #endif // __JUCE_LADSPAPLUGINFORMAT_JUCEHEADER__
  29486. /*** End of inlined file: juce_LADSPAPluginFormat.h ***/
  29487. #endif
  29488. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29489. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  29490. #ifdef __aeffect__
  29491. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29492. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29493. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  29494. events to the list.
  29495. This is used by both the VST hosting code and the plugin wrapper.
  29496. */
  29497. class VSTMidiEventList
  29498. {
  29499. public:
  29500. VSTMidiEventList()
  29501. : numEventsUsed (0), numEventsAllocated (0)
  29502. {
  29503. }
  29504. ~VSTMidiEventList()
  29505. {
  29506. freeEvents();
  29507. }
  29508. void clear()
  29509. {
  29510. numEventsUsed = 0;
  29511. if (events != 0)
  29512. events->numEvents = 0;
  29513. }
  29514. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  29515. {
  29516. ensureSize (numEventsUsed + 1);
  29517. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  29518. events->numEvents = ++numEventsUsed;
  29519. if (numBytes <= 4)
  29520. {
  29521. if (e->type == kVstSysExType)
  29522. {
  29523. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29524. e->type = kVstMidiType;
  29525. e->byteSize = sizeof (VstMidiEvent);
  29526. e->noteLength = 0;
  29527. e->noteOffset = 0;
  29528. e->detune = 0;
  29529. e->noteOffVelocity = 0;
  29530. }
  29531. e->deltaFrames = frameOffset;
  29532. memcpy (e->midiData, midiData, numBytes);
  29533. }
  29534. else
  29535. {
  29536. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  29537. if (se->type == kVstSysExType)
  29538. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  29539. else
  29540. se->sysexDump = (char*) juce_malloc (numBytes);
  29541. memcpy (se->sysexDump, midiData, numBytes);
  29542. se->type = kVstSysExType;
  29543. se->byteSize = sizeof (VstMidiSysexEvent);
  29544. se->deltaFrames = frameOffset;
  29545. se->flags = 0;
  29546. se->dumpBytes = numBytes;
  29547. se->resvd1 = 0;
  29548. se->resvd2 = 0;
  29549. }
  29550. }
  29551. // Handy method to pull the events out of an event buffer supplied by the host
  29552. // or plugin.
  29553. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  29554. {
  29555. for (int i = 0; i < events->numEvents; ++i)
  29556. {
  29557. const VstEvent* const e = events->events[i];
  29558. if (e != 0)
  29559. {
  29560. if (e->type == kVstMidiType)
  29561. {
  29562. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  29563. 4, e->deltaFrames);
  29564. }
  29565. else if (e->type == kVstSysExType)
  29566. {
  29567. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  29568. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  29569. e->deltaFrames);
  29570. }
  29571. }
  29572. }
  29573. }
  29574. void ensureSize (int numEventsNeeded)
  29575. {
  29576. if (numEventsNeeded > numEventsAllocated)
  29577. {
  29578. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  29579. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  29580. if (events == 0)
  29581. events.calloc (size, 1);
  29582. else
  29583. events.realloc (size, 1);
  29584. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  29585. {
  29586. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  29587. (int) sizeof (VstMidiSysexEvent)));
  29588. e->type = kVstMidiType;
  29589. e->byteSize = sizeof (VstMidiEvent);
  29590. events->events[i] = (VstEvent*) e;
  29591. }
  29592. numEventsAllocated = numEventsNeeded;
  29593. }
  29594. }
  29595. void freeEvents()
  29596. {
  29597. if (events != 0)
  29598. {
  29599. for (int i = numEventsAllocated; --i >= 0;)
  29600. {
  29601. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  29602. if (e->type == kVstSysExType)
  29603. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  29604. juce_free (e);
  29605. }
  29606. events.free();
  29607. numEventsUsed = 0;
  29608. numEventsAllocated = 0;
  29609. }
  29610. }
  29611. HeapBlock <VstEvents> events;
  29612. private:
  29613. int numEventsUsed, numEventsAllocated;
  29614. };
  29615. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29616. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  29617. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  29618. #endif
  29619. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29620. /*** Start of inlined file: juce_VSTPluginFormat.h ***/
  29621. #ifndef __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29622. #define __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29623. #if JUCE_PLUGINHOST_VST
  29624. /**
  29625. Implements a plugin format manager for VSTs.
  29626. */
  29627. class JUCE_API VSTPluginFormat : public AudioPluginFormat
  29628. {
  29629. public:
  29630. VSTPluginFormat();
  29631. ~VSTPluginFormat();
  29632. const String getName() const { return "VST"; }
  29633. void findAllTypesForFile (OwnedArray <PluginDescription>& results, const String& fileOrIdentifier);
  29634. AudioPluginInstance* createInstanceFromDescription (const PluginDescription& desc);
  29635. bool fileMightContainThisPluginType (const String& fileOrIdentifier);
  29636. const String getNameOfPluginFromIdentifier (const String& fileOrIdentifier);
  29637. const StringArray searchPathsForPlugins (const FileSearchPath& directoriesToSearch, bool recursive);
  29638. bool doesPluginStillExist (const PluginDescription& desc);
  29639. const FileSearchPath getDefaultLocationsToSearch();
  29640. juce_UseDebuggingNewOperator
  29641. private:
  29642. VSTPluginFormat (const VSTPluginFormat&);
  29643. VSTPluginFormat& operator= (const VSTPluginFormat&);
  29644. void recursiveFileSearch (StringArray& results, const File& dir, const bool recursive);
  29645. };
  29646. #endif
  29647. #endif // __JUCE_VSTPLUGINFORMAT_JUCEHEADER__
  29648. /*** End of inlined file: juce_VSTPluginFormat.h ***/
  29649. #endif
  29650. #ifndef __JUCE_AUDIOPLUGINFORMAT_JUCEHEADER__
  29651. #endif
  29652. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29653. /*** Start of inlined file: juce_AudioPluginFormatManager.h ***/
  29654. #ifndef __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29655. #define __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29656. /**
  29657. This maintains a list of known AudioPluginFormats.
  29658. @see AudioPluginFormat
  29659. */
  29660. class JUCE_API AudioPluginFormatManager : public DeletedAtShutdown
  29661. {
  29662. public:
  29663. AudioPluginFormatManager() throw();
  29664. /** Destructor. */
  29665. ~AudioPluginFormatManager() throw();
  29666. juce_DeclareSingleton_SingleThreaded (AudioPluginFormatManager, false);
  29667. /** Adds any formats that it knows about, e.g. VST.
  29668. */
  29669. void addDefaultFormats();
  29670. /** Returns the number of types of format that are available.
  29671. Use getFormat() to get one of them.
  29672. */
  29673. int getNumFormats() throw();
  29674. /** Returns one of the available formats.
  29675. @see getNumFormats
  29676. */
  29677. AudioPluginFormat* getFormat (const int index) throw();
  29678. /** Adds a format to the list.
  29679. The object passed in will be owned and deleted by the manager.
  29680. */
  29681. void addFormat (AudioPluginFormat* const format) throw();
  29682. /** Tries to load the type for this description, by trying all the formats
  29683. that this manager knows about.
  29684. The caller is responsible for deleting the object that is returned.
  29685. If it can't load the plugin, it returns 0 and leaves a message in the
  29686. errorMessage string.
  29687. */
  29688. AudioPluginInstance* createPluginInstance (const PluginDescription& description,
  29689. String& errorMessage) const;
  29690. /** Checks that the file or component for this plugin actually still exists.
  29691. (This won't try to load the plugin)
  29692. */
  29693. bool doesPluginStillExist (const PluginDescription& description) const;
  29694. juce_UseDebuggingNewOperator
  29695. private:
  29696. OwnedArray <AudioPluginFormat> formats;
  29697. AudioPluginFormatManager (const AudioPluginFormatManager&);
  29698. AudioPluginFormatManager& operator= (const AudioPluginFormatManager&);
  29699. };
  29700. #endif // __JUCE_AUDIOPLUGINFORMATMANAGER_JUCEHEADER__
  29701. /*** End of inlined file: juce_AudioPluginFormatManager.h ***/
  29702. #endif
  29703. #ifndef __JUCE_AUDIOPLUGININSTANCE_JUCEHEADER__
  29704. #endif
  29705. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29706. /*** Start of inlined file: juce_KnownPluginList.h ***/
  29707. #ifndef __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29708. #define __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29709. /**
  29710. Manages a list of plugin types.
  29711. This can be easily edited, saved and loaded, and used to create instances of
  29712. the plugin types in it.
  29713. @see PluginListComponent
  29714. */
  29715. class JUCE_API KnownPluginList : public ChangeBroadcaster
  29716. {
  29717. public:
  29718. /** Creates an empty list.
  29719. */
  29720. KnownPluginList();
  29721. /** Destructor. */
  29722. ~KnownPluginList();
  29723. /** Clears the list. */
  29724. void clear();
  29725. /** Returns the number of types currently in the list.
  29726. @see getType
  29727. */
  29728. int getNumTypes() const throw() { return types.size(); }
  29729. /** Returns one of the types.
  29730. @see getNumTypes
  29731. */
  29732. PluginDescription* getType (int index) const throw() { return types [index]; }
  29733. /** Looks for a type in the list which comes from this file.
  29734. */
  29735. PluginDescription* getTypeForFile (const String& fileOrIdentifier) const throw();
  29736. /** Looks for a type in the list which matches a plugin type ID.
  29737. The identifierString parameter must have been created by
  29738. PluginDescription::createIdentifierString().
  29739. */
  29740. PluginDescription* getTypeForIdentifierString (const String& identifierString) const throw();
  29741. /** Adds a type manually from its description. */
  29742. bool addType (const PluginDescription& type);
  29743. /** Removes a type. */
  29744. void removeType (int index) throw();
  29745. /** Looks for all types that can be loaded from a given file, and adds them
  29746. to the list.
  29747. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29748. re-tested if it's not already in the list, or if the file's modification
  29749. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29750. false, the file will always be reloaded and tested.
  29751. Returns true if any new types were added, and all the types found in this
  29752. file (even if it was already known and hasn't been re-scanned) get returned
  29753. in the array.
  29754. */
  29755. bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
  29756. bool dontRescanIfAlreadyInList,
  29757. OwnedArray <PluginDescription>& typesFound,
  29758. AudioPluginFormat& formatToUse);
  29759. /** Returns true if the specified file is already known about and if it
  29760. hasn't been modified since our entry was created.
  29761. */
  29762. bool isListingUpToDate (const String& possiblePluginFileOrIdentifier) const throw();
  29763. /** Scans and adds a bunch of files that might have been dragged-and-dropped.
  29764. If any types are found in the files, their descriptions are returned in the array.
  29765. */
  29766. void scanAndAddDragAndDroppedFiles (const StringArray& filenames,
  29767. OwnedArray <PluginDescription>& typesFound);
  29768. /** Sort methods used to change the order of the plugins in the list.
  29769. */
  29770. enum SortMethod
  29771. {
  29772. defaultOrder = 0,
  29773. sortAlphabetically,
  29774. sortByCategory,
  29775. sortByManufacturer,
  29776. sortByFileSystemLocation
  29777. };
  29778. /** Adds all the plugin types to a popup menu so that the user can select one.
  29779. Depending on the sort method, it may add sub-menus for categories,
  29780. manufacturers, etc.
  29781. Use getIndexChosenByMenu() to find out the type that was chosen.
  29782. */
  29783. void addToMenu (PopupMenu& menu,
  29784. const SortMethod sortMethod) const;
  29785. /** Converts a menu item index that has been chosen into its index in this list.
  29786. Returns -1 if it's not an ID that was used.
  29787. @see addToMenu
  29788. */
  29789. int getIndexChosenByMenu (int menuResultCode) const;
  29790. /** Sorts the list. */
  29791. void sort (const SortMethod method);
  29792. /** Creates some XML that can be used to store the state of this list.
  29793. */
  29794. XmlElement* createXml() const;
  29795. /** Recreates the state of this list from its stored XML format.
  29796. */
  29797. void recreateFromXml (const XmlElement& xml);
  29798. juce_UseDebuggingNewOperator
  29799. private:
  29800. OwnedArray <PluginDescription> types;
  29801. KnownPluginList (const KnownPluginList&);
  29802. KnownPluginList& operator= (const KnownPluginList&);
  29803. };
  29804. #endif // __JUCE_KNOWNPLUGINLIST_JUCEHEADER__
  29805. /*** End of inlined file: juce_KnownPluginList.h ***/
  29806. #endif
  29807. #ifndef __JUCE_PLUGINDESCRIPTION_JUCEHEADER__
  29808. #endif
  29809. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29810. /*** Start of inlined file: juce_PluginDirectoryScanner.h ***/
  29811. #ifndef __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29812. #define __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29813. /**
  29814. Scans a directory for plugins, and adds them to a KnownPluginList.
  29815. To use one of these, create it and call scanNextFile() repeatedly, until
  29816. it returns false.
  29817. */
  29818. class JUCE_API PluginDirectoryScanner
  29819. {
  29820. public:
  29821. /**
  29822. Creates a scanner.
  29823. @param listToAddResultsTo this will get the new types added to it.
  29824. @param formatToLookFor this is the type of format that you want to look for
  29825. @param directoriesToSearch the path to search
  29826. @param searchRecursively true to search recursively
  29827. @param deadMansPedalFile if this isn't File::nonexistent, then it will
  29828. be used as a file to store the names of any plugins
  29829. that crash during initialisation. If there are
  29830. any plugins listed in it, then these will always
  29831. be scanned after all other possible files have
  29832. been tried - in this way, even if there's a few
  29833. dodgy plugins in your path, then a couple of rescans
  29834. will still manage to find all the proper plugins.
  29835. It's probably best to choose a file in the user's
  29836. application data directory (alongside your app's
  29837. settings file) for this. The file format it uses
  29838. is just a list of filenames of the modules that
  29839. failed.
  29840. */
  29841. PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
  29842. AudioPluginFormat& formatToLookFor,
  29843. FileSearchPath directoriesToSearch,
  29844. bool searchRecursively,
  29845. const File& deadMansPedalFile);
  29846. /** Destructor. */
  29847. ~PluginDirectoryScanner();
  29848. /** Tries the next likely-looking file.
  29849. If dontRescanIfAlreadyInList is true, then the file will only be loaded and
  29850. re-tested if it's not already in the list, or if the file's modification
  29851. time has changed since the list was created. If dontRescanIfAlreadyInList is
  29852. false, the file will always be reloaded and tested.
  29853. Returns false when there are no more files to try.
  29854. */
  29855. bool scanNextFile (bool dontRescanIfAlreadyInList);
  29856. /** Returns the description of the plugin that will be scanned during the next
  29857. call to scanNextFile().
  29858. This is handy if you want to show the user which file is currently getting
  29859. scanned.
  29860. */
  29861. const String getNextPluginFileThatWillBeScanned() const throw();
  29862. /** Returns the estimated progress, between 0 and 1.
  29863. */
  29864. float getProgress() const { return progress; }
  29865. /** This returns a list of all the filenames of things that looked like being
  29866. a plugin file, but which failed to open for some reason.
  29867. */
  29868. const StringArray& getFailedFiles() const throw() { return failedFiles; }
  29869. juce_UseDebuggingNewOperator
  29870. private:
  29871. KnownPluginList& list;
  29872. AudioPluginFormat& format;
  29873. StringArray filesOrIdentifiersToScan;
  29874. File deadMansPedalFile;
  29875. StringArray failedFiles;
  29876. int nextIndex;
  29877. float progress;
  29878. const StringArray getDeadMansPedalFile() throw();
  29879. void setDeadMansPedalFile (const StringArray& newContents) throw();
  29880. PluginDirectoryScanner (const PluginDirectoryScanner&);
  29881. PluginDirectoryScanner& operator= (const PluginDirectoryScanner&);
  29882. };
  29883. #endif // __JUCE_PLUGINDIRECTORYSCANNER_JUCEHEADER__
  29884. /*** End of inlined file: juce_PluginDirectoryScanner.h ***/
  29885. #endif
  29886. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29887. /*** Start of inlined file: juce_PluginListComponent.h ***/
  29888. #ifndef __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29889. #define __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  29890. /*** Start of inlined file: juce_ListBox.h ***/
  29891. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  29892. #define __JUCE_LISTBOX_JUCEHEADER__
  29893. class ListViewport;
  29894. /**
  29895. A subclass of this is used to drive a ListBox.
  29896. @see ListBox
  29897. */
  29898. class JUCE_API ListBoxModel
  29899. {
  29900. public:
  29901. /** Destructor. */
  29902. virtual ~ListBoxModel() {}
  29903. /** This has to return the number of items in the list.
  29904. @see ListBox::getNumRows()
  29905. */
  29906. virtual int getNumRows() = 0;
  29907. /** This method must be implemented to draw a row of the list.
  29908. */
  29909. virtual void paintListBoxItem (int rowNumber,
  29910. Graphics& g,
  29911. int width, int height,
  29912. bool rowIsSelected) = 0;
  29913. /** This is used to create or update a custom component to go in a row of the list.
  29914. Any row may contain a custom component, or can just be drawn with the paintListBoxItem() method
  29915. and handle mouse clicks with listBoxItemClicked().
  29916. This method will be called whenever a custom component might need to be updated - e.g.
  29917. when the table is changed, or TableListBox::updateContent() is called.
  29918. If you don't need a custom component for the specified row, then return 0.
  29919. If you do want a custom component, and the existingComponentToUpdate is null, then
  29920. this method must create a suitable new component and return it.
  29921. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  29922. by this method. In this case, the method must either update it to make sure it's correctly representing
  29923. the given row (which may be different from the one that the component was created for), or it can
  29924. delete this component and return a new one.
  29925. The component that your method returns will be deleted by the ListBox when it is no longer needed.
  29926. */
  29927. virtual Component* refreshComponentForRow (int rowNumber, bool isRowSelected,
  29928. Component* existingComponentToUpdate);
  29929. /** This can be overridden to react to the user clicking on a row.
  29930. @see listBoxItemDoubleClicked
  29931. */
  29932. virtual void listBoxItemClicked (int row, const MouseEvent& e);
  29933. /** This can be overridden to react to the user double-clicking on a row.
  29934. @see listBoxItemClicked
  29935. */
  29936. virtual void listBoxItemDoubleClicked (int row, const MouseEvent& e);
  29937. /** This can be overridden to react to the user double-clicking on a part of the list where
  29938. there are no rows.
  29939. @see listBoxItemClicked
  29940. */
  29941. virtual void backgroundClicked();
  29942. /** Override this to be informed when rows are selected or deselected.
  29943. This will be called whenever a row is selected or deselected. If a range of
  29944. rows is selected all at once, this will just be called once for that event.
  29945. @param lastRowSelected the last row that the user selected. If no
  29946. rows are currently selected, this may be -1.
  29947. */
  29948. virtual void selectedRowsChanged (int lastRowSelected);
  29949. /** Override this to be informed when the delete key is pressed.
  29950. If no rows are selected when they press the key, this won't be called.
  29951. @param lastRowSelected the last row that had been selected when they pressed the
  29952. key - if there are multiple selections, this might not be
  29953. very useful
  29954. */
  29955. virtual void deleteKeyPressed (int lastRowSelected);
  29956. /** Override this to be informed when the return key is pressed.
  29957. If no rows are selected when they press the key, this won't be called.
  29958. @param lastRowSelected the last row that had been selected when they pressed the
  29959. key - if there are multiple selections, this might not be
  29960. very useful
  29961. */
  29962. virtual void returnKeyPressed (int lastRowSelected);
  29963. /** Override this to be informed when the list is scrolled.
  29964. This might be caused by the user moving the scrollbar, or by programmatic changes
  29965. to the list position.
  29966. */
  29967. virtual void listWasScrolled();
  29968. /** To allow rows from your list to be dragged-and-dropped, implement this method.
  29969. If this returns a non-empty name then when the user drags a row, the listbox will
  29970. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  29971. a drag-and-drop operation, using this string as the source description, with the listbox
  29972. itself as the source component.
  29973. @see DragAndDropContainer::startDragging
  29974. */
  29975. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  29976. /** You can override this to provide tool tips for specific rows.
  29977. @see TooltipClient
  29978. */
  29979. virtual const String getTooltipForRow (int row);
  29980. };
  29981. /**
  29982. A list of items that can be scrolled vertically.
  29983. To create a list, you'll need to create a subclass of ListBoxModel. This can
  29984. either paint each row of the list and respond to events via callbacks, or for
  29985. more specialised tasks, it can supply a custom component to fill each row.
  29986. @see ComboBox, TableListBox
  29987. */
  29988. class JUCE_API ListBox : public Component,
  29989. public SettableTooltipClient
  29990. {
  29991. public:
  29992. /** Creates a ListBox.
  29993. The model pointer passed-in can be null, in which case you can set it later
  29994. with setModel().
  29995. */
  29996. ListBox (const String& componentName,
  29997. ListBoxModel* model);
  29998. /** Destructor. */
  29999. ~ListBox();
  30000. /** Changes the current data model to display. */
  30001. void setModel (ListBoxModel* newModel);
  30002. /** Returns the current list model. */
  30003. ListBoxModel* getModel() const throw() { return model; }
  30004. /** Causes the list to refresh its content.
  30005. Call this when the number of rows in the list changes, or if you want it
  30006. to call refreshComponentForRow() on all the row components.
  30007. Be careful not to call it from a different thread, though, as it's not
  30008. thread-safe.
  30009. */
  30010. void updateContent();
  30011. /** Turns on multiple-selection of rows.
  30012. By default this is disabled.
  30013. When your row component gets clicked you'll need to call the
  30014. selectRowsBasedOnModifierKeys() method to tell the list that it's been
  30015. clicked and to get it to do the appropriate selection based on whether
  30016. the ctrl/shift keys are held down.
  30017. */
  30018. void setMultipleSelectionEnabled (bool shouldBeEnabled);
  30019. /** Makes the list react to mouse moves by selecting the row that the mouse if over.
  30020. This function is here primarily for the ComboBox class to use, but might be
  30021. useful for some other purpose too.
  30022. */
  30023. void setMouseMoveSelectsRows (bool shouldSelect);
  30024. /** Selects a row.
  30025. If the row is already selected, this won't do anything.
  30026. @param rowNumber the row to select
  30027. @param dontScrollToShowThisRow if true, the list's position won't change; if false and
  30028. the selected row is off-screen, it'll scroll to make
  30029. sure that row is on-screen
  30030. @param deselectOthersFirst if true and there are multiple selections, these will
  30031. first be deselected before this item is selected
  30032. @see isRowSelected, selectRowsBasedOnModifierKeys, flipRowSelection, deselectRow,
  30033. deselectAllRows, selectRangeOfRows
  30034. */
  30035. void selectRow (int rowNumber,
  30036. bool dontScrollToShowThisRow = false,
  30037. bool deselectOthersFirst = true);
  30038. /** Selects a set of rows.
  30039. This will add these rows to the current selection, so you might need to
  30040. clear the current selection first with deselectAllRows()
  30041. @param firstRow the first row to select (inclusive)
  30042. @param lastRow the last row to select (inclusive)
  30043. */
  30044. void selectRangeOfRows (int firstRow,
  30045. int lastRow);
  30046. /** Deselects a row.
  30047. If it's not currently selected, this will do nothing.
  30048. @see selectRow, deselectAllRows
  30049. */
  30050. void deselectRow (int rowNumber);
  30051. /** Deselects any currently selected rows.
  30052. @see deselectRow
  30053. */
  30054. void deselectAllRows();
  30055. /** Selects or deselects a row.
  30056. If the row's currently selected, this deselects it, and vice-versa.
  30057. */
  30058. void flipRowSelection (int rowNumber);
  30059. /** Returns a sparse set indicating the rows that are currently selected.
  30060. @see setSelectedRows
  30061. */
  30062. const SparseSet<int> getSelectedRows() const;
  30063. /** Sets the rows that should be selected, based on an explicit set of ranges.
  30064. If sendNotificationEventToModel is true, the ListBoxModel::selectedRowsChanged()
  30065. method will be called. If it's false, no notification will be sent to the model.
  30066. @see getSelectedRows
  30067. */
  30068. void setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  30069. bool sendNotificationEventToModel = true);
  30070. /** Checks whether a row is selected.
  30071. */
  30072. bool isRowSelected (int rowNumber) const;
  30073. /** Returns the number of rows that are currently selected.
  30074. @see getSelectedRow, isRowSelected, getLastRowSelected
  30075. */
  30076. int getNumSelectedRows() const;
  30077. /** Returns the row number of a selected row.
  30078. This will return the row number of the Nth selected row. The row numbers returned will
  30079. be sorted in order from low to high.
  30080. @param index the index of the selected row to return, (from 0 to getNumSelectedRows() - 1)
  30081. @returns the row number, or -1 if the index was out of range or if there aren't any rows
  30082. selected
  30083. @see getNumSelectedRows, isRowSelected, getLastRowSelected
  30084. */
  30085. int getSelectedRow (int index = 0) const;
  30086. /** Returns the last row that the user selected.
  30087. This isn't the same as the highest row number that is currently selected - if the user
  30088. had multiply-selected rows 10, 5 and then 6 in that order, this would return 6.
  30089. If nothing is selected, it will return -1.
  30090. */
  30091. int getLastRowSelected() const;
  30092. /** Multiply-selects rows based on the modifier keys.
  30093. If no modifier keys are down, this will select the given row and
  30094. deselect any others.
  30095. If the ctrl (or command on the Mac) key is down, it'll flip the
  30096. state of the selected row.
  30097. If the shift key is down, it'll select up to the given row from the
  30098. last row selected.
  30099. @see selectRow
  30100. */
  30101. void selectRowsBasedOnModifierKeys (int rowThatWasClickedOn,
  30102. const ModifierKeys& modifiers);
  30103. /** Scrolls the list to a particular position.
  30104. The proportion is between 0 and 1.0, so 0 scrolls to the top of the list,
  30105. 1.0 scrolls to the bottom.
  30106. If the total number of rows all fit onto the screen at once, then this
  30107. method won't do anything.
  30108. @see getVerticalPosition
  30109. */
  30110. void setVerticalPosition (double newProportion);
  30111. /** Returns the current vertical position as a proportion of the total.
  30112. This can be used in conjunction with setVerticalPosition() to save and restore
  30113. the list's position. It returns a value in the range 0 to 1.
  30114. @see setVerticalPosition
  30115. */
  30116. double getVerticalPosition() const;
  30117. /** Scrolls if necessary to make sure that a particular row is visible.
  30118. */
  30119. void scrollToEnsureRowIsOnscreen (int row);
  30120. /** Returns a pointer to the scrollbar.
  30121. (Unlikely to be useful for most people).
  30122. */
  30123. ScrollBar* getVerticalScrollBar() const throw();
  30124. /** Returns a pointer to the scrollbar.
  30125. (Unlikely to be useful for most people).
  30126. */
  30127. ScrollBar* getHorizontalScrollBar() const throw();
  30128. /** Finds the row index that contains a given x,y position.
  30129. The position is relative to the ListBox's top-left.
  30130. If no row exists at this position, the method will return -1.
  30131. @see getComponentForRowNumber
  30132. */
  30133. int getRowContainingPosition (int x, int y) const throw();
  30134. /** Finds a row index that would be the most suitable place to insert a new
  30135. item for a given position.
  30136. This is useful when the user is e.g. dragging and dropping onto the listbox,
  30137. because it lets you easily choose the best position to insert the item that
  30138. they drop, based on where they drop it.
  30139. If the position is out of range, this will return -1. If the position is
  30140. beyond the end of the list, it will return getNumRows() to indicate the end
  30141. of the list.
  30142. @see getComponentForRowNumber
  30143. */
  30144. int getInsertionIndexForPosition (int x, int y) const throw();
  30145. /** Returns the position of one of the rows, relative to the top-left of
  30146. the listbox.
  30147. This may be off-screen, and the range of the row number that is passed-in is
  30148. not checked to see if it's a valid row.
  30149. */
  30150. const Rectangle<int> getRowPosition (int rowNumber,
  30151. bool relativeToComponentTopLeft) const throw();
  30152. /** Finds the row component for a given row in the list.
  30153. The component returned will have been created using createRowComponent().
  30154. If the component for this row is off-screen or if the row is out-of-range,
  30155. this will return 0.
  30156. @see getRowContainingPosition
  30157. */
  30158. Component* getComponentForRowNumber (int rowNumber) const throw();
  30159. /** Returns the row number that the given component represents.
  30160. If the component isn't one of the list's rows, this will return -1.
  30161. */
  30162. int getRowNumberOfComponent (Component* rowComponent) const throw();
  30163. /** Returns the width of a row (which may be less than the width of this component
  30164. if there's a scrollbar).
  30165. */
  30166. int getVisibleRowWidth() const throw();
  30167. /** Sets the height of each row in the list.
  30168. The default height is 22 pixels.
  30169. @see getRowHeight
  30170. */
  30171. void setRowHeight (int newHeight);
  30172. /** Returns the height of a row in the list.
  30173. @see setRowHeight
  30174. */
  30175. int getRowHeight() const throw() { return rowHeight; }
  30176. /** Returns the number of rows actually visible.
  30177. This is the number of whole rows which will fit on-screen, so the value might
  30178. be more than the actual number of rows in the list.
  30179. */
  30180. int getNumRowsOnScreen() const throw();
  30181. /** A set of colour IDs to use to change the colour of various aspects of the label.
  30182. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30183. methods.
  30184. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30185. */
  30186. enum ColourIds
  30187. {
  30188. backgroundColourId = 0x1002800, /**< The background colour to fill the list with.
  30189. Make this transparent if you don't want the background to be filled. */
  30190. outlineColourId = 0x1002810, /**< An optional colour to use to draw a border around the list.
  30191. Make this transparent to not have an outline. */
  30192. textColourId = 0x1002820 /**< The preferred colour to use for drawing text in the listbox. */
  30193. };
  30194. /** Sets the thickness of a border that will be drawn around the box.
  30195. To set the colour of the outline, use @code setColour (ListBox::outlineColourId, colourXYZ); @endcode
  30196. @see outlineColourId
  30197. */
  30198. void setOutlineThickness (int outlineThickness);
  30199. /** Returns the thickness of outline that will be drawn around the listbox.
  30200. @see setOutlineColour
  30201. */
  30202. int getOutlineThickness() const throw() { return outlineThickness; }
  30203. /** Sets a component that the list should use as a header.
  30204. This will position the given component at the top of the list, maintaining the
  30205. height of the component passed-in, but rescaling it horizontally to match the
  30206. width of the items in the listbox.
  30207. The component will be deleted when setHeaderComponent() is called with a
  30208. different component, or when the listbox is deleted.
  30209. */
  30210. void setHeaderComponent (Component* newHeaderComponent);
  30211. /** Changes the width of the rows in the list.
  30212. This can be used to make the list's row components wider than the list itself - the
  30213. width of the rows will be either the width of the list or this value, whichever is
  30214. greater, and if the rows become wider than the list, a horizontal scrollbar will
  30215. appear.
  30216. The default value for this is 0, which means that the rows will always
  30217. be the same width as the list.
  30218. */
  30219. void setMinimumContentWidth (int newMinimumWidth);
  30220. /** Returns the space currently available for the row items, taking into account
  30221. borders, scrollbars, etc.
  30222. */
  30223. int getVisibleContentWidth() const throw();
  30224. /** Repaints one of the rows.
  30225. This is a lightweight alternative to calling updateContent, and just causes a
  30226. repaint of the row's area.
  30227. */
  30228. void repaintRow (int rowNumber) throw();
  30229. /** This fairly obscure method creates an image that just shows the currently
  30230. selected row components.
  30231. It's a handy method for doing drag-and-drop, as it can be passed to the
  30232. DragAndDropContainer for use as the drag image.
  30233. Note that it will make the row components temporarily invisible, so if you're
  30234. using custom components this could affect them if they're sensitive to that
  30235. sort of thing.
  30236. @see Component::createComponentSnapshot
  30237. */
  30238. const Image createSnapshotOfSelectedRows (int& x, int& y);
  30239. /** Returns the viewport that this ListBox uses.
  30240. You may need to use this to change parameters such as whether scrollbars
  30241. are shown, etc.
  30242. */
  30243. Viewport* getViewport() const throw();
  30244. /** @internal */
  30245. bool keyPressed (const KeyPress& key);
  30246. /** @internal */
  30247. bool keyStateChanged (bool isKeyDown);
  30248. /** @internal */
  30249. void paint (Graphics& g);
  30250. /** @internal */
  30251. void paintOverChildren (Graphics& g);
  30252. /** @internal */
  30253. void resized();
  30254. /** @internal */
  30255. void visibilityChanged();
  30256. /** @internal */
  30257. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  30258. /** @internal */
  30259. void mouseMove (const MouseEvent&);
  30260. /** @internal */
  30261. void mouseExit (const MouseEvent&);
  30262. /** @internal */
  30263. void mouseUp (const MouseEvent&);
  30264. /** @internal */
  30265. void colourChanged();
  30266. /** @internal */
  30267. void startDragAndDrop (const MouseEvent& e, const String& dragDescription);
  30268. juce_UseDebuggingNewOperator
  30269. private:
  30270. friend class ListViewport;
  30271. friend class TableListBox;
  30272. ListBoxModel* model;
  30273. ScopedPointer<ListViewport> viewport;
  30274. ScopedPointer<Component> headerComponent;
  30275. int totalItems, rowHeight, minimumRowWidth;
  30276. int outlineThickness;
  30277. int lastRowSelected;
  30278. bool mouseMoveSelects, multipleSelection, hasDoneInitialUpdate;
  30279. SparseSet <int> selected;
  30280. void selectRowInternal (int rowNumber,
  30281. bool dontScrollToShowThisRow,
  30282. bool deselectOthersFirst,
  30283. bool isMouseClick);
  30284. ListBox (const ListBox&);
  30285. ListBox& operator= (const ListBox&);
  30286. };
  30287. #endif // __JUCE_LISTBOX_JUCEHEADER__
  30288. /*** End of inlined file: juce_ListBox.h ***/
  30289. /*** Start of inlined file: juce_TextButton.h ***/
  30290. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  30291. #define __JUCE_TEXTBUTTON_JUCEHEADER__
  30292. /**
  30293. A button that uses the standard lozenge-shaped background with a line of
  30294. text on it.
  30295. @see Button, DrawableButton
  30296. */
  30297. class JUCE_API TextButton : public Button
  30298. {
  30299. public:
  30300. /** Creates a TextButton.
  30301. @param buttonName the text to put in the button (the component's name is also
  30302. initially set to this string, but these can be changed later
  30303. using the setName() and setButtonText() methods)
  30304. @param toolTip an optional string to use as a toolip
  30305. @see Button
  30306. */
  30307. TextButton (const String& buttonName = String::empty,
  30308. const String& toolTip = String::empty);
  30309. /** Destructor. */
  30310. ~TextButton();
  30311. /** A set of colour IDs to use to change the colour of various aspects of the button.
  30312. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  30313. methods.
  30314. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  30315. */
  30316. enum ColourIds
  30317. {
  30318. buttonColourId = 0x1000100, /**< The colour used to fill the button shape (when the button is toggled
  30319. 'off'). The look-and-feel class might re-interpret this to add
  30320. effects, etc. */
  30321. buttonOnColourId = 0x1000101, /**< The colour used to fill the button shape (when the button is toggled
  30322. 'on'). The look-and-feel class might re-interpret this to add
  30323. effects, etc. */
  30324. textColourOffId = 0x1000102, /**< The colour to use for the button's text when the button's toggle state is "off". */
  30325. textColourOnId = 0x1000103 /**< The colour to use for the button's text.when the button's toggle state is "on". */
  30326. };
  30327. /** Resizes the button to fit neatly around its current text.
  30328. If newHeight is >= 0, the button's height will be changed to this
  30329. value. If it's less than zero, its height will be unaffected.
  30330. */
  30331. void changeWidthToFitText (int newHeight = -1);
  30332. /** This can be overridden to use different fonts than the default one.
  30333. Note that you'll need to set the font's size appropriately, too.
  30334. */
  30335. virtual const Font getFont();
  30336. juce_UseDebuggingNewOperator
  30337. protected:
  30338. /** @internal */
  30339. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  30340. /** @internal */
  30341. void colourChanged();
  30342. private:
  30343. TextButton (const TextButton&);
  30344. TextButton& operator= (const TextButton&);
  30345. };
  30346. #endif // __JUCE_TEXTBUTTON_JUCEHEADER__
  30347. /*** End of inlined file: juce_TextButton.h ***/
  30348. /**
  30349. A component displaying a list of plugins, with options to scan for them,
  30350. add, remove and sort them.
  30351. */
  30352. class JUCE_API PluginListComponent : public Component,
  30353. public ListBoxModel,
  30354. public ChangeListener,
  30355. public ButtonListener,
  30356. public Timer
  30357. {
  30358. public:
  30359. /**
  30360. Creates the list component.
  30361. For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
  30362. The properties file, if supplied, is used to store the user's last search paths.
  30363. */
  30364. PluginListComponent (KnownPluginList& listToRepresent,
  30365. const File& deadMansPedalFile,
  30366. PropertiesFile* propertiesToUse);
  30367. /** Destructor. */
  30368. ~PluginListComponent();
  30369. /** @internal */
  30370. void resized();
  30371. /** @internal */
  30372. bool isInterestedInFileDrag (const StringArray& files);
  30373. /** @internal */
  30374. void filesDropped (const StringArray& files, int, int);
  30375. /** @internal */
  30376. int getNumRows();
  30377. /** @internal */
  30378. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected);
  30379. /** @internal */
  30380. void deleteKeyPressed (int lastRowSelected);
  30381. /** @internal */
  30382. void buttonClicked (Button* b);
  30383. /** @internal */
  30384. void changeListenerCallback (void*);
  30385. /** @internal */
  30386. void timerCallback();
  30387. juce_UseDebuggingNewOperator
  30388. private:
  30389. KnownPluginList& list;
  30390. File deadMansPedalFile;
  30391. ListBox* listBox;
  30392. TextButton* optionsButton;
  30393. PropertiesFile* propertiesToUse;
  30394. int typeToScan;
  30395. void scanFor (AudioPluginFormat* format);
  30396. PluginListComponent (const PluginListComponent&);
  30397. PluginListComponent& operator= (const PluginListComponent&);
  30398. };
  30399. #endif // __JUCE_PLUGINLISTCOMPONENT_JUCEHEADER__
  30400. /*** End of inlined file: juce_PluginListComponent.h ***/
  30401. #endif
  30402. #ifndef __JUCE_AUDIOPLAYHEAD_JUCEHEADER__
  30403. #endif
  30404. #ifndef __JUCE_AUDIOPROCESSOR_JUCEHEADER__
  30405. #endif
  30406. #ifndef __JUCE_AUDIOPROCESSOREDITOR_JUCEHEADER__
  30407. #endif
  30408. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30409. /*** Start of inlined file: juce_AudioProcessorGraph.h ***/
  30410. #ifndef __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30411. #define __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30412. /**
  30413. A type of AudioProcessor which plays back a graph of other AudioProcessors.
  30414. Use one of these objects if you want to wire-up a set of AudioProcessors
  30415. and play back the result.
  30416. Processors can be added to the graph as "nodes" using addNode(), and once
  30417. added, you can connect any of their input or output channels to other
  30418. nodes using addConnection().
  30419. To play back a graph through an audio device, you might want to use an
  30420. AudioProcessorPlayer object.
  30421. */
  30422. class JUCE_API AudioProcessorGraph : public AudioProcessor,
  30423. public AsyncUpdater
  30424. {
  30425. public:
  30426. /** Creates an empty graph.
  30427. */
  30428. AudioProcessorGraph();
  30429. /** Destructor.
  30430. Any processor objects that have been added to the graph will also be deleted.
  30431. */
  30432. ~AudioProcessorGraph();
  30433. /** Represents one of the nodes, or processors, in an AudioProcessorGraph.
  30434. To create a node, call AudioProcessorGraph::addNode().
  30435. */
  30436. class JUCE_API Node : public ReferenceCountedObject
  30437. {
  30438. public:
  30439. /** Destructor.
  30440. */
  30441. ~Node();
  30442. /** The ID number assigned to this node.
  30443. This is assigned by the graph that owns it, and can't be changed.
  30444. */
  30445. const uint32 id;
  30446. /** The actual processor object that this node represents.
  30447. */
  30448. AudioProcessor* const processor;
  30449. /** A set of user-definable properties that are associated with this node.
  30450. This can be used to attach values to the node for whatever purpose seems
  30451. useful. For example, you might store an x and y position if your application
  30452. is displaying the nodes on-screen.
  30453. */
  30454. NamedValueSet properties;
  30455. /** A convenient typedef for referring to a pointer to a node object.
  30456. */
  30457. typedef ReferenceCountedObjectPtr <Node> Ptr;
  30458. juce_UseDebuggingNewOperator
  30459. private:
  30460. friend class AudioProcessorGraph;
  30461. bool isPrepared;
  30462. Node (uint32 id, AudioProcessor* processor);
  30463. void prepare (double sampleRate, int blockSize, AudioProcessorGraph* graph);
  30464. void unprepare();
  30465. Node (const Node&);
  30466. Node& operator= (const Node&);
  30467. };
  30468. /** Represents a connection between two channels of two nodes in an AudioProcessorGraph.
  30469. To create a connection, use AudioProcessorGraph::addConnection().
  30470. */
  30471. struct JUCE_API Connection
  30472. {
  30473. public:
  30474. /** The ID number of the node which is the input source for this connection.
  30475. @see AudioProcessorGraph::getNodeForId
  30476. */
  30477. uint32 sourceNodeId;
  30478. /** The index of the output channel of the source node from which this
  30479. connection takes its data.
  30480. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30481. it is referring to the source node's midi output. Otherwise, it is the zero-based
  30482. index of an audio output channel in the source node.
  30483. */
  30484. int sourceChannelIndex;
  30485. /** The ID number of the node which is the destination for this connection.
  30486. @see AudioProcessorGraph::getNodeForId
  30487. */
  30488. uint32 destNodeId;
  30489. /** The index of the input channel of the destination node to which this
  30490. connection delivers its data.
  30491. If this value is the special number AudioProcessorGraph::midiChannelIndex, then
  30492. it is referring to the destination node's midi input. Otherwise, it is the zero-based
  30493. index of an audio input channel in the destination node.
  30494. */
  30495. int destChannelIndex;
  30496. juce_UseDebuggingNewOperator
  30497. private:
  30498. };
  30499. /** Deletes all nodes and connections from this graph.
  30500. Any processor objects in the graph will be deleted.
  30501. */
  30502. void clear();
  30503. /** Returns the number of nodes in the graph. */
  30504. int getNumNodes() const { return nodes.size(); }
  30505. /** Returns a pointer to one of the nodes in the graph.
  30506. This will return 0 if the index is out of range.
  30507. @see getNodeForId
  30508. */
  30509. Node* getNode (const int index) const { return nodes [index]; }
  30510. /** Searches the graph for a node with the given ID number and returns it.
  30511. If no such node was found, this returns 0.
  30512. @see getNode
  30513. */
  30514. Node* getNodeForId (const uint32 nodeId) const;
  30515. /** Adds a node to the graph.
  30516. This creates a new node in the graph, for the specified processor. Once you have
  30517. added a processor to the graph, the graph owns it and will delete it later when
  30518. it is no longer needed.
  30519. The optional nodeId parameter lets you specify an ID to use for the node, but
  30520. if the value is already in use, this new node will overwrite the old one.
  30521. If this succeeds, it returns a pointer to the newly-created node.
  30522. */
  30523. Node* addNode (AudioProcessor* newProcessor, uint32 nodeId = 0);
  30524. /** Deletes a node within the graph which has the specified ID.
  30525. This will also delete any connections that are attached to this node.
  30526. */
  30527. bool removeNode (uint32 nodeId);
  30528. /** Returns the number of connections in the graph. */
  30529. int getNumConnections() const { return connections.size(); }
  30530. /** Returns a pointer to one of the connections in the graph. */
  30531. const Connection* getConnection (int index) const { return connections [index]; }
  30532. /** Searches for a connection between some specified channels.
  30533. If no such connection is found, this returns 0.
  30534. */
  30535. const Connection* getConnectionBetween (uint32 sourceNodeId,
  30536. int sourceChannelIndex,
  30537. uint32 destNodeId,
  30538. int destChannelIndex) const;
  30539. /** Returns true if there is a connection between any of the channels of
  30540. two specified nodes.
  30541. */
  30542. bool isConnected (uint32 possibleSourceNodeId,
  30543. uint32 possibleDestNodeId) const;
  30544. /** Returns true if it would be legal to connect the specified points.
  30545. */
  30546. bool canConnect (uint32 sourceNodeId, int sourceChannelIndex,
  30547. uint32 destNodeId, int destChannelIndex) const;
  30548. /** Attempts to connect two specified channels of two nodes.
  30549. If this isn't allowed (e.g. because you're trying to connect a midi channel
  30550. to an audio one or other such nonsense), then it'll return false.
  30551. */
  30552. bool addConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30553. uint32 destNodeId, int destChannelIndex);
  30554. /** Deletes the connection with the specified index.
  30555. Returns true if a connection was actually deleted.
  30556. */
  30557. void removeConnection (int index);
  30558. /** Deletes any connection between two specified points.
  30559. Returns true if a connection was actually deleted.
  30560. */
  30561. bool removeConnection (uint32 sourceNodeId, int sourceChannelIndex,
  30562. uint32 destNodeId, int destChannelIndex);
  30563. /** Removes all connections from the specified node.
  30564. */
  30565. bool disconnectNode (uint32 nodeId);
  30566. /** Performs a sanity checks of all the connections.
  30567. This might be useful if some of the processors are doing things like changing
  30568. their channel counts, which could render some connections obsolete.
  30569. */
  30570. bool removeIllegalConnections();
  30571. /** A special number that represents the midi channel of a node.
  30572. This is used as a channel index value if you want to refer to the midi input
  30573. or output instead of an audio channel.
  30574. */
  30575. static const int midiChannelIndex;
  30576. /** A special type of AudioProcessor that can live inside an AudioProcessorGraph
  30577. in order to use the audio that comes into and out of the graph itself.
  30578. If you create an AudioGraphIOProcessor in "input" mode, it will act as a
  30579. node in the graph which delivers the audio that is coming into the parent
  30580. graph. This allows you to stream the data to other nodes and process the
  30581. incoming audio.
  30582. Likewise, one of these in "output" mode can be sent data which it will add to
  30583. the sum of data being sent to the graph's output.
  30584. @see AudioProcessorGraph
  30585. */
  30586. class JUCE_API AudioGraphIOProcessor : public AudioPluginInstance
  30587. {
  30588. public:
  30589. /** Specifies the mode in which this processor will operate.
  30590. */
  30591. enum IODeviceType
  30592. {
  30593. audioInputNode, /**< In this mode, the processor has output channels
  30594. representing all the audio input channels that are
  30595. coming into its parent audio graph. */
  30596. audioOutputNode, /**< In this mode, the processor has input channels
  30597. representing all the audio output channels that are
  30598. going out of its parent audio graph. */
  30599. midiInputNode, /**< In this mode, the processor has a midi output which
  30600. delivers the same midi data that is arriving at its
  30601. parent graph. */
  30602. midiOutputNode /**< In this mode, the processor has a midi input and
  30603. any data sent to it will be passed out of the parent
  30604. graph. */
  30605. };
  30606. /** Returns the mode of this processor. */
  30607. IODeviceType getType() const { return type; }
  30608. /** Returns the parent graph to which this processor belongs, or 0 if it
  30609. hasn't yet been added to one. */
  30610. AudioProcessorGraph* getParentGraph() const { return graph; }
  30611. /** True if this is an audio or midi input. */
  30612. bool isInput() const;
  30613. /** True if this is an audio or midi output. */
  30614. bool isOutput() const;
  30615. AudioGraphIOProcessor (const IODeviceType type);
  30616. ~AudioGraphIOProcessor();
  30617. const String getName() const;
  30618. void fillInPluginDescription (PluginDescription& d) const;
  30619. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30620. void releaseResources();
  30621. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30622. const String getInputChannelName (const int channelIndex) const;
  30623. const String getOutputChannelName (const int channelIndex) const;
  30624. bool isInputChannelStereoPair (int index) const;
  30625. bool isOutputChannelStereoPair (int index) const;
  30626. bool acceptsMidi() const;
  30627. bool producesMidi() const;
  30628. AudioProcessorEditor* createEditor();
  30629. int getNumParameters();
  30630. const String getParameterName (int);
  30631. float getParameter (int);
  30632. const String getParameterText (int);
  30633. void setParameter (int, float);
  30634. int getNumPrograms();
  30635. int getCurrentProgram();
  30636. void setCurrentProgram (int);
  30637. const String getProgramName (int);
  30638. void changeProgramName (int, const String&);
  30639. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30640. void setStateInformation (const void* data, int sizeInBytes);
  30641. /** @internal */
  30642. void setParentGraph (AudioProcessorGraph* graph);
  30643. juce_UseDebuggingNewOperator
  30644. private:
  30645. const IODeviceType type;
  30646. AudioProcessorGraph* graph;
  30647. AudioGraphIOProcessor (const AudioGraphIOProcessor&);
  30648. AudioGraphIOProcessor& operator= (const AudioGraphIOProcessor&);
  30649. };
  30650. // AudioProcessor methods:
  30651. const String getName() const;
  30652. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  30653. void releaseResources();
  30654. void processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages);
  30655. const String getInputChannelName (const int channelIndex) const;
  30656. const String getOutputChannelName (const int channelIndex) const;
  30657. bool isInputChannelStereoPair (int index) const;
  30658. bool isOutputChannelStereoPair (int index) const;
  30659. bool acceptsMidi() const;
  30660. bool producesMidi() const;
  30661. AudioProcessorEditor* createEditor() { return 0; }
  30662. int getNumParameters() { return 0; }
  30663. const String getParameterName (int) { return String::empty; }
  30664. float getParameter (int) { return 0; }
  30665. const String getParameterText (int) { return String::empty; }
  30666. void setParameter (int, float) { }
  30667. int getNumPrograms() { return 0; }
  30668. int getCurrentProgram() { return 0; }
  30669. void setCurrentProgram (int) { }
  30670. const String getProgramName (int) { return String::empty; }
  30671. void changeProgramName (int, const String&) { }
  30672. void getStateInformation (JUCE_NAMESPACE::MemoryBlock& destData);
  30673. void setStateInformation (const void* data, int sizeInBytes);
  30674. /** @internal */
  30675. void handleAsyncUpdate();
  30676. juce_UseDebuggingNewOperator
  30677. private:
  30678. ReferenceCountedArray <Node> nodes;
  30679. OwnedArray <Connection> connections;
  30680. int lastNodeId;
  30681. AudioSampleBuffer renderingBuffers;
  30682. OwnedArray <MidiBuffer> midiBuffers;
  30683. CriticalSection renderLock;
  30684. Array<void*> renderingOps;
  30685. friend class AudioGraphIOProcessor;
  30686. AudioSampleBuffer* currentAudioInputBuffer;
  30687. AudioSampleBuffer currentAudioOutputBuffer;
  30688. MidiBuffer* currentMidiInputBuffer;
  30689. MidiBuffer currentMidiOutputBuffer;
  30690. void clearRenderingSequence();
  30691. void buildRenderingSequence();
  30692. bool isAnInputTo (uint32 possibleInputId, uint32 possibleDestinationId, int recursionCheck) const;
  30693. AudioProcessorGraph (const AudioProcessorGraph&);
  30694. AudioProcessorGraph& operator= (const AudioProcessorGraph&);
  30695. };
  30696. #endif // __JUCE_AUDIOPROCESSORGRAPH_JUCEHEADER__
  30697. /*** End of inlined file: juce_AudioProcessorGraph.h ***/
  30698. #endif
  30699. #ifndef __JUCE_AUDIOPROCESSORLISTENER_JUCEHEADER__
  30700. #endif
  30701. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30702. /*** Start of inlined file: juce_AudioProcessorPlayer.h ***/
  30703. #ifndef __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30704. #define __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30705. /**
  30706. An AudioIODeviceCallback object which streams audio through an AudioProcessor.
  30707. To use one of these, just make it the callback used by your AudioIODevice, and
  30708. give it a processor to use by calling setProcessor().
  30709. It's also a MidiInputCallback, so you can connect it to both an audio and midi
  30710. input to send both streams through the processor.
  30711. @see AudioProcessor, AudioProcessorGraph
  30712. */
  30713. class JUCE_API AudioProcessorPlayer : public AudioIODeviceCallback,
  30714. public MidiInputCallback
  30715. {
  30716. public:
  30717. /**
  30718. */
  30719. AudioProcessorPlayer();
  30720. /** Destructor. */
  30721. virtual ~AudioProcessorPlayer();
  30722. /** Sets the processor that should be played.
  30723. The processor that is passed in will not be deleted or owned by this object.
  30724. To stop anything playing, pass in 0 to this method.
  30725. */
  30726. void setProcessor (AudioProcessor* const processorToPlay);
  30727. /** Returns the current audio processor that is being played.
  30728. */
  30729. AudioProcessor* getCurrentProcessor() const { return processor; }
  30730. /** Returns a midi message collector that you can pass midi messages to if you
  30731. want them to be injected into the midi stream that is being sent to the
  30732. processor.
  30733. */
  30734. MidiMessageCollector& getMidiMessageCollector() { return messageCollector; }
  30735. /** @internal */
  30736. void audioDeviceIOCallback (const float** inputChannelData,
  30737. int totalNumInputChannels,
  30738. float** outputChannelData,
  30739. int totalNumOutputChannels,
  30740. int numSamples);
  30741. /** @internal */
  30742. void audioDeviceAboutToStart (AudioIODevice* device);
  30743. /** @internal */
  30744. void audioDeviceStopped();
  30745. /** @internal */
  30746. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  30747. juce_UseDebuggingNewOperator
  30748. private:
  30749. AudioProcessor* processor;
  30750. CriticalSection lock;
  30751. double sampleRate;
  30752. int blockSize;
  30753. bool isPrepared;
  30754. int numInputChans, numOutputChans;
  30755. float* channels [128];
  30756. AudioSampleBuffer tempBuffer;
  30757. MidiBuffer incomingMidi;
  30758. MidiMessageCollector messageCollector;
  30759. AudioProcessorPlayer (const AudioProcessorPlayer&);
  30760. AudioProcessorPlayer& operator= (const AudioProcessorPlayer&);
  30761. };
  30762. #endif // __JUCE_AUDIOPROCESSORPLAYER_JUCEHEADER__
  30763. /*** End of inlined file: juce_AudioProcessorPlayer.h ***/
  30764. #endif
  30765. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30766. /*** Start of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30767. #ifndef __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30768. #define __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30769. /*** Start of inlined file: juce_PropertyPanel.h ***/
  30770. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  30771. #define __JUCE_PROPERTYPANEL_JUCEHEADER__
  30772. /*** Start of inlined file: juce_PropertyComponent.h ***/
  30773. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30774. #define __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30775. class EditableProperty;
  30776. /**
  30777. A base class for a component that goes in a PropertyPanel and displays one of
  30778. an item's properties.
  30779. Subclasses of this are used to display a property in various forms, e.g. a
  30780. ChoicePropertyComponent shows its value as a combo box; a SliderPropertyComponent
  30781. shows its value as a slider; a TextPropertyComponent as a text box, etc.
  30782. A subclass must implement the refresh() method which will be called to tell the
  30783. component to update itself, and is also responsible for calling this it when the
  30784. item that it refers to is changed.
  30785. @see PropertyPanel, TextPropertyComponent, SliderPropertyComponent,
  30786. ChoicePropertyComponent, ButtonPropertyComponent, BooleanPropertyComponent
  30787. */
  30788. class JUCE_API PropertyComponent : public Component,
  30789. public SettableTooltipClient
  30790. {
  30791. public:
  30792. /** Creates a PropertyComponent.
  30793. @param propertyName the name is stored as this component's name, and is
  30794. used as the name displayed next to this component in
  30795. a property panel
  30796. @param preferredHeight the height that the component should be given - some
  30797. items may need to be larger than a normal row height.
  30798. This value can also be set if a subclass changes the
  30799. preferredHeight member variable.
  30800. */
  30801. PropertyComponent (const String& propertyName,
  30802. int preferredHeight = 25);
  30803. /** Destructor. */
  30804. ~PropertyComponent();
  30805. /** Returns this item's preferred height.
  30806. This value is specified either in the constructor or by a subclass changing the
  30807. preferredHeight member variable.
  30808. */
  30809. int getPreferredHeight() const throw() { return preferredHeight; }
  30810. void setPreferredHeight (int newHeight) throw() { preferredHeight = newHeight; }
  30811. /** Updates the property component if the item it refers to has changed.
  30812. A subclass must implement this method, and other objects may call it to
  30813. force it to refresh itself.
  30814. The subclass should be economical in the amount of work is done, so for
  30815. example it should check whether it really needs to do a repaint rather than
  30816. just doing one every time this method is called, as it may be called when
  30817. the value being displayed hasn't actually changed.
  30818. */
  30819. virtual void refresh() = 0;
  30820. /** The default paint method fills the background and draws a label for the
  30821. item's name.
  30822. @see LookAndFeel::drawPropertyComponentBackground(), LookAndFeel::drawPropertyComponentLabel()
  30823. */
  30824. void paint (Graphics& g);
  30825. /** The default resize method positions any child component to the right of this
  30826. one, based on the look and feel's default label size.
  30827. */
  30828. void resized();
  30829. /** By default, this just repaints the component. */
  30830. void enablementChanged();
  30831. juce_UseDebuggingNewOperator
  30832. protected:
  30833. /** Used by the PropertyPanel to determine how high this component needs to be.
  30834. A subclass can update this value in its constructor but shouldn't alter it later
  30835. as changes won't necessarily be picked up.
  30836. */
  30837. int preferredHeight;
  30838. };
  30839. #endif // __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  30840. /*** End of inlined file: juce_PropertyComponent.h ***/
  30841. /**
  30842. A panel that holds a list of PropertyComponent objects.
  30843. This panel displays a list of PropertyComponents, and allows them to be organised
  30844. into collapsible sections.
  30845. To use, simply create one of these and add your properties to it with addProperties()
  30846. or addSection().
  30847. @see PropertyComponent
  30848. */
  30849. class JUCE_API PropertyPanel : public Component
  30850. {
  30851. public:
  30852. /** Creates an empty property panel. */
  30853. PropertyPanel();
  30854. /** Destructor. */
  30855. ~PropertyPanel();
  30856. /** Deletes all property components from the panel.
  30857. */
  30858. void clear();
  30859. /** Adds a set of properties to the panel.
  30860. The components in the list will be owned by this object and will be automatically
  30861. deleted later on when no longer needed.
  30862. These properties are added without them being inside a named section. If you
  30863. want them to be kept together in a collapsible section, use addSection() instead.
  30864. */
  30865. void addProperties (const Array <PropertyComponent*>& newPropertyComponents);
  30866. /** Adds a set of properties to the panel.
  30867. These properties are added at the bottom of the list, under a section heading with
  30868. a plus/minus button that allows it to be opened and closed.
  30869. The components in the list will be owned by this object and will be automatically
  30870. deleted later on when no longer needed.
  30871. To add properies without them being in a section, use addProperties().
  30872. */
  30873. void addSection (const String& sectionTitle,
  30874. const Array <PropertyComponent*>& newPropertyComponents,
  30875. bool shouldSectionInitiallyBeOpen = true);
  30876. /** Calls the refresh() method of all PropertyComponents in the panel */
  30877. void refreshAll() const;
  30878. /** Returns a list of all the names of sections in the panel.
  30879. These are the sections that have been added with addSection().
  30880. */
  30881. const StringArray getSectionNames() const;
  30882. /** Returns true if the section at this index is currently open.
  30883. The index is from 0 up to the number of items returned by getSectionNames().
  30884. */
  30885. bool isSectionOpen (int sectionIndex) const;
  30886. /** Opens or closes one of the sections.
  30887. The index is from 0 up to the number of items returned by getSectionNames().
  30888. */
  30889. void setSectionOpen (int sectionIndex, bool shouldBeOpen);
  30890. /** Enables or disables one of the sections.
  30891. The index is from 0 up to the number of items returned by getSectionNames().
  30892. */
  30893. void setSectionEnabled (int sectionIndex, bool shouldBeEnabled);
  30894. /** Saves the current state of open/closed sections so it can be restored later.
  30895. The caller is responsible for deleting the object that is returned.
  30896. To restore this state, use restoreOpennessState().
  30897. @see restoreOpennessState
  30898. */
  30899. XmlElement* getOpennessState() const;
  30900. /** Restores a previously saved arrangement of open/closed sections.
  30901. This will try to restore a snapshot of the panel's state that was created by
  30902. the getOpennessState() method. If any of the sections named in the original
  30903. XML aren't present, they will be ignored.
  30904. @see getOpennessState
  30905. */
  30906. void restoreOpennessState (const XmlElement& newState);
  30907. /** Sets a message to be displayed when there are no properties in the panel.
  30908. The default message is "nothing selected".
  30909. */
  30910. void setMessageWhenEmpty (const String& newMessage);
  30911. /** Returns the message that is displayed when there are no properties.
  30912. @see setMessageWhenEmpty
  30913. */
  30914. const String& getMessageWhenEmpty() const;
  30915. /** @internal */
  30916. void paint (Graphics& g);
  30917. /** @internal */
  30918. void resized();
  30919. juce_UseDebuggingNewOperator
  30920. private:
  30921. Viewport viewport;
  30922. class PropertyHolderComponent;
  30923. PropertyHolderComponent* propertyHolderComponent;
  30924. String messageWhenEmpty;
  30925. void updatePropHolderLayout() const;
  30926. void updatePropHolderLayout (int width) const;
  30927. };
  30928. #endif // __JUCE_PROPERTYPANEL_JUCEHEADER__
  30929. /*** End of inlined file: juce_PropertyPanel.h ***/
  30930. /**
  30931. A type of UI component that displays the parameters of an AudioProcessor as
  30932. a simple list of sliders.
  30933. This can be used for showing an editor for a processor that doesn't supply
  30934. its own custom editor.
  30935. @see AudioProcessor
  30936. */
  30937. class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
  30938. {
  30939. public:
  30940. GenericAudioProcessorEditor (AudioProcessor* const owner);
  30941. ~GenericAudioProcessorEditor();
  30942. void paint (Graphics& g);
  30943. void resized();
  30944. juce_UseDebuggingNewOperator
  30945. private:
  30946. PropertyPanel* panel;
  30947. GenericAudioProcessorEditor (const GenericAudioProcessorEditor&);
  30948. GenericAudioProcessorEditor& operator= (const GenericAudioProcessorEditor&);
  30949. };
  30950. #endif // __JUCE_GENERICAUDIOPROCESSOREDITOR_JUCEHEADER__
  30951. /*** End of inlined file: juce_GenericAudioProcessorEditor.h ***/
  30952. #endif
  30953. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30954. /*** Start of inlined file: juce_Sampler.h ***/
  30955. #ifndef __JUCE_SAMPLER_JUCEHEADER__
  30956. #define __JUCE_SAMPLER_JUCEHEADER__
  30957. /*** Start of inlined file: juce_Synthesiser.h ***/
  30958. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  30959. #define __JUCE_SYNTHESISER_JUCEHEADER__
  30960. /**
  30961. Describes one of the sounds that a Synthesiser can play.
  30962. A synthesiser can contain one or more sounds, and a sound can choose which
  30963. midi notes and channels can trigger it.
  30964. The SynthesiserSound is a passive class that just describes what the sound is -
  30965. the actual audio rendering for a sound is done by a SynthesiserVoice. This allows
  30966. more than one SynthesiserVoice to play the same sound at the same time.
  30967. @see Synthesiser, SynthesiserVoice
  30968. */
  30969. class JUCE_API SynthesiserSound : public ReferenceCountedObject
  30970. {
  30971. protected:
  30972. SynthesiserSound();
  30973. public:
  30974. /** Destructor. */
  30975. virtual ~SynthesiserSound();
  30976. /** Returns true if this sound should be played when a given midi note is pressed.
  30977. The Synthesiser will use this information when deciding which sounds to trigger
  30978. for a given note.
  30979. */
  30980. virtual bool appliesToNote (const int midiNoteNumber) = 0;
  30981. /** Returns true if the sound should be triggered by midi events on a given channel.
  30982. The Synthesiser will use this information when deciding which sounds to trigger
  30983. for a given note.
  30984. */
  30985. virtual bool appliesToChannel (const int midiChannel) = 0;
  30986. /**
  30987. */
  30988. typedef ReferenceCountedObjectPtr <SynthesiserSound> Ptr;
  30989. juce_UseDebuggingNewOperator
  30990. };
  30991. /**
  30992. Represents a voice that a Synthesiser can use to play a SynthesiserSound.
  30993. A voice plays a single sound at a time, and a synthesiser holds an array of
  30994. voices so that it can play polyphonically.
  30995. @see Synthesiser, SynthesiserSound
  30996. */
  30997. class JUCE_API SynthesiserVoice
  30998. {
  30999. public:
  31000. /** Creates a voice. */
  31001. SynthesiserVoice();
  31002. /** Destructor. */
  31003. virtual ~SynthesiserVoice();
  31004. /** Returns the midi note that this voice is currently playing.
  31005. Returns a value less than 0 if no note is playing.
  31006. */
  31007. int getCurrentlyPlayingNote() const { return currentlyPlayingNote; }
  31008. /** Returns the sound that this voice is currently playing.
  31009. Returns 0 if it's not playing.
  31010. */
  31011. const SynthesiserSound::Ptr getCurrentlyPlayingSound() const { return currentlyPlayingSound; }
  31012. /** Must return true if this voice object is capable of playing the given sound.
  31013. If there are different classes of sound, and different classes of voice, a voice can
  31014. choose which ones it wants to take on.
  31015. A typical implementation of this method may just return true if there's only one type
  31016. of voice and sound, or it might check the type of the sound object passed-in and
  31017. see if it's one that it understands.
  31018. */
  31019. virtual bool canPlaySound (SynthesiserSound* sound) = 0;
  31020. /** Called to start a new note.
  31021. This will be called during the rendering callback, so must be fast and thread-safe.
  31022. */
  31023. virtual void startNote (const int midiNoteNumber,
  31024. const float velocity,
  31025. SynthesiserSound* sound,
  31026. const int currentPitchWheelPosition) = 0;
  31027. /** Called to stop a note.
  31028. This will be called during the rendering callback, so must be fast and thread-safe.
  31029. If allowTailOff is false or the voice doesn't want to tail-off, then it must stop all
  31030. sound immediately, and must call clearCurrentNote() to reset the state of this voice
  31031. and allow the synth to reassign it another sound.
  31032. If allowTailOff is true and the voice decides to do a tail-off, then it's allowed to
  31033. begin fading out its sound, and it can stop playing until it's finished. As soon as it
  31034. finishes playing (during the rendering callback), it must make sure that it calls
  31035. clearCurrentNote().
  31036. */
  31037. virtual void stopNote (const bool allowTailOff) = 0;
  31038. /** Called to let the voice know that the pitch wheel has been moved.
  31039. This will be called during the rendering callback, so must be fast and thread-safe.
  31040. */
  31041. virtual void pitchWheelMoved (const int newValue) = 0;
  31042. /** Called to let the voice know that a midi controller has been moved.
  31043. This will be called during the rendering callback, so must be fast and thread-safe.
  31044. */
  31045. virtual void controllerMoved (const int controllerNumber,
  31046. const int newValue) = 0;
  31047. /** Renders the next block of data for this voice.
  31048. The output audio data must be added to the current contents of the buffer provided.
  31049. Only the region of the buffer between startSample and (startSample + numSamples)
  31050. should be altered by this method.
  31051. If the voice is currently silent, it should just return without doing anything.
  31052. If the sound that the voice is playing finishes during the course of this rendered
  31053. block, it must call clearCurrentNote(), to tell the synthesiser that it has finished.
  31054. The size of the blocks that are rendered can change each time it is called, and may
  31055. involve rendering as little as 1 sample at a time. In between rendering callbacks,
  31056. the voice's methods will be called to tell it about note and controller events.
  31057. */
  31058. virtual void renderNextBlock (AudioSampleBuffer& outputBuffer,
  31059. int startSample,
  31060. int numSamples) = 0;
  31061. /** Returns true if the voice is currently playing a sound which is mapped to the given
  31062. midi channel.
  31063. If it's not currently playing, this will return false.
  31064. */
  31065. bool isPlayingChannel (int midiChannel) const;
  31066. /** Changes the voice's reference sample rate.
  31067. The rate is set so that subclasses know the output rate and can set their pitch
  31068. accordingly.
  31069. This method is called by the synth, and subclasses can access the current rate with
  31070. the currentSampleRate member.
  31071. */
  31072. void setCurrentPlaybackSampleRate (double newRate);
  31073. juce_UseDebuggingNewOperator
  31074. protected:
  31075. /** Returns the current target sample rate at which rendering is being done.
  31076. This is available for subclasses so they can pitch things correctly.
  31077. */
  31078. double getSampleRate() const { return currentSampleRate; }
  31079. /** Resets the state of this voice after a sound has finished playing.
  31080. The subclass must call this when it finishes playing a note and becomes available
  31081. to play new ones.
  31082. It must either call it in the stopNote() method, or if the voice is tailing off,
  31083. then it should call it later during the renderNextBlock method, as soon as it
  31084. finishes its tail-off.
  31085. It can also be called at any time during the render callback if the sound happens
  31086. to have finished, e.g. if it's playing a sample and the sample finishes.
  31087. */
  31088. void clearCurrentNote();
  31089. private:
  31090. friend class Synthesiser;
  31091. double currentSampleRate;
  31092. int currentlyPlayingNote;
  31093. uint32 noteOnTime;
  31094. SynthesiserSound::Ptr currentlyPlayingSound;
  31095. };
  31096. /**
  31097. Base class for a musical device that can play sounds.
  31098. To create a synthesiser, you'll need to create a subclass of SynthesiserSound
  31099. to describe each sound available to your synth, and a subclass of SynthesiserVoice
  31100. which can play back one of these sounds.
  31101. Then you can use the addVoice() and addSound() methods to give the synthesiser a
  31102. set of sounds, and a set of voices it can use to play them. If you only give it
  31103. one voice it will be monophonic - the more voices it has, the more polyphony it'll
  31104. have available.
  31105. Then repeatedly call the renderNextBlock() method to produce the audio. Any midi
  31106. events that go in will be scanned for note on/off messages, and these are used to
  31107. start and stop the voices playing the appropriate sounds.
  31108. While it's playing, you can also cause notes to be triggered by calling the noteOn(),
  31109. noteOff() and other controller methods.
  31110. Before rendering, be sure to call the setCurrentPlaybackSampleRate() to tell it
  31111. what the target playback rate is. This value is passed on to the voices so that
  31112. they can pitch their output correctly.
  31113. */
  31114. class JUCE_API Synthesiser
  31115. {
  31116. public:
  31117. /** Creates a new synthesiser.
  31118. You'll need to add some sounds and voices before it'll make any sound..
  31119. */
  31120. Synthesiser();
  31121. /** Destructor. */
  31122. virtual ~Synthesiser();
  31123. /** Deletes all voices. */
  31124. void clearVoices();
  31125. /** Returns the number of voices that have been added. */
  31126. int getNumVoices() const { return voices.size(); }
  31127. /** Returns one of the voices that have been added. */
  31128. SynthesiserVoice* getVoice (int index) const;
  31129. /** Adds a new voice to the synth.
  31130. All the voices should be the same class of object and are treated equally.
  31131. The object passed in will be managed by the synthesiser, which will delete
  31132. it later on when no longer needed. The caller should not retain a pointer to the
  31133. voice.
  31134. */
  31135. void addVoice (SynthesiserVoice* newVoice);
  31136. /** Deletes one of the voices. */
  31137. void removeVoice (int index);
  31138. /** Deletes all sounds. */
  31139. void clearSounds();
  31140. /** Returns the number of sounds that have been added to the synth. */
  31141. int getNumSounds() const { return sounds.size(); }
  31142. /** Returns one of the sounds. */
  31143. SynthesiserSound* getSound (int index) const { return sounds [index]; }
  31144. /** Adds a new sound to the synthesiser.
  31145. The object passed in is reference counted, so will be deleted when it is removed
  31146. from the synthesiser, and when no voices are still using it.
  31147. */
  31148. void addSound (const SynthesiserSound::Ptr& newSound);
  31149. /** Removes and deletes one of the sounds. */
  31150. void removeSound (int index);
  31151. /** If set to true, then the synth will try to take over an existing voice if
  31152. it runs out and needs to play another note.
  31153. The value of this boolean is passed into findFreeVoice(), so the result will
  31154. depend on the implementation of this method.
  31155. */
  31156. void setNoteStealingEnabled (bool shouldStealNotes);
  31157. /** Returns true if note-stealing is enabled.
  31158. @see setNoteStealingEnabled
  31159. */
  31160. bool isNoteStealingEnabled() const { return shouldStealNotes; }
  31161. /** Triggers a note-on event.
  31162. The default method here will find all the sounds that want to be triggered by
  31163. this note/channel. For each sound, it'll try to find a free voice, and use the
  31164. voice to start playing the sound.
  31165. Subclasses might want to override this if they need a more complex algorithm.
  31166. This method will be called automatically according to the midi data passed into
  31167. renderNextBlock(), but may be called explicitly too.
  31168. */
  31169. virtual void noteOn (const int midiChannel,
  31170. const int midiNoteNumber,
  31171. const float velocity);
  31172. /** Triggers a note-off event.
  31173. This will turn off any voices that are playing a sound for the given note/channel.
  31174. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  31175. (if they can do). If this is false, the notes will all be cut off immediately.
  31176. This method will be called automatically according to the midi data passed into
  31177. renderNextBlock(), but may be called explicitly too.
  31178. */
  31179. virtual void noteOff (const int midiChannel,
  31180. const int midiNoteNumber,
  31181. const bool allowTailOff);
  31182. /** Turns off all notes.
  31183. This will turn off any voices that are playing a sound on the given midi channel.
  31184. If midiChannel is 0 or less, then all voices will be turned off, regardless of
  31185. which channel they're playing.
  31186. If allowTailOff is true, the voices will be allowed to fade out the notes gracefully
  31187. (if they can do). If this is false, the notes will all be cut off immediately.
  31188. This method will be called automatically according to the midi data passed into
  31189. renderNextBlock(), but may be called explicitly too.
  31190. */
  31191. virtual void allNotesOff (const int midiChannel,
  31192. const bool allowTailOff);
  31193. /** Sends a pitch-wheel message.
  31194. This will send a pitch-wheel message to any voices that are playing sounds on
  31195. the given midi channel.
  31196. This method will be called automatically according to the midi data passed into
  31197. renderNextBlock(), but may be called explicitly too.
  31198. @param midiChannel the midi channel for the event
  31199. @param wheelValue the wheel position, from 0 to 0x3fff, as returned by MidiMessage::getPitchWheelValue()
  31200. */
  31201. virtual void handlePitchWheel (const int midiChannel,
  31202. const int wheelValue);
  31203. /** Sends a midi controller message.
  31204. This will send a midi controller message to any voices that are playing sounds on
  31205. the given midi channel.
  31206. This method will be called automatically according to the midi data passed into
  31207. renderNextBlock(), but may be called explicitly too.
  31208. @param midiChannel the midi channel for the event
  31209. @param controllerNumber the midi controller type, as returned by MidiMessage::getControllerNumber()
  31210. @param controllerValue the midi controller value, between 0 and 127, as returned by MidiMessage::getControllerValue()
  31211. */
  31212. virtual void handleController (const int midiChannel,
  31213. const int controllerNumber,
  31214. const int controllerValue);
  31215. /** Tells the synthesiser what the sample rate is for the audio it's being used to
  31216. render.
  31217. This value is propagated to the voices so that they can use it to render the correct
  31218. pitches.
  31219. */
  31220. void setCurrentPlaybackSampleRate (const double sampleRate);
  31221. /** Creates the next block of audio output.
  31222. This will process the next numSamples of data from all the voices, and add that output
  31223. to the audio block supplied, starting from the offset specified. Note that the
  31224. data will be added to the current contents of the buffer, so you should clear it
  31225. before calling this method if necessary.
  31226. The midi events in the inputMidi buffer are parsed for note and controller events,
  31227. and these are used to trigger the voices. Note that the startSample offset applies
  31228. both to the audio output buffer and the midi input buffer, so any midi events
  31229. with timestamps outside the specified region will be ignored.
  31230. */
  31231. void renderNextBlock (AudioSampleBuffer& outputAudio,
  31232. const MidiBuffer& inputMidi,
  31233. int startSample,
  31234. int numSamples);
  31235. juce_UseDebuggingNewOperator
  31236. protected:
  31237. /** This is used to control access to the rendering callback and the note trigger methods. */
  31238. CriticalSection lock;
  31239. OwnedArray <SynthesiserVoice> voices;
  31240. ReferenceCountedArray <SynthesiserSound> sounds;
  31241. /** The last pitch-wheel values for each midi channel. */
  31242. int lastPitchWheelValues [16];
  31243. /** Searches through the voices to find one that's not currently playing, and which
  31244. can play the given sound.
  31245. Returns 0 if all voices are busy and stealing isn't enabled.
  31246. This can be overridden to implement custom voice-stealing algorithms.
  31247. */
  31248. virtual SynthesiserVoice* findFreeVoice (SynthesiserSound* soundToPlay,
  31249. const bool stealIfNoneAvailable) const;
  31250. /** Starts a specified voice playing a particular sound.
  31251. You'll probably never need to call this, it's used internally by noteOn(), but
  31252. may be needed by subclasses for custom behaviours.
  31253. */
  31254. void startVoice (SynthesiserVoice* voice,
  31255. SynthesiserSound* sound,
  31256. int midiChannel,
  31257. int midiNoteNumber,
  31258. float velocity);
  31259. /** xxx Temporary method here to cause a compiler error - note the new parameters for this method. */
  31260. int findFreeVoice (const bool) const { return 0; }
  31261. private:
  31262. double sampleRate;
  31263. uint32 lastNoteOnCounter;
  31264. bool shouldStealNotes;
  31265. Synthesiser (const Synthesiser&);
  31266. Synthesiser& operator= (const Synthesiser&);
  31267. };
  31268. #endif // __JUCE_SYNTHESISER_JUCEHEADER__
  31269. /*** End of inlined file: juce_Synthesiser.h ***/
  31270. /**
  31271. A subclass of SynthesiserSound that represents a sampled audio clip.
  31272. This is a pretty basic sampler, and just attempts to load the whole audio stream
  31273. into memory.
  31274. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  31275. give it some SampledSound objects to play.
  31276. @see SamplerVoice, Synthesiser, SynthesiserSound
  31277. */
  31278. class JUCE_API SamplerSound : public SynthesiserSound
  31279. {
  31280. public:
  31281. /** Creates a sampled sound from an audio reader.
  31282. This will attempt to load the audio from the source into memory and store
  31283. it in this object.
  31284. @param name a name for the sample
  31285. @param source the audio to load. This object can be safely deleted by the
  31286. caller after this constructor returns
  31287. @param midiNotes the set of midi keys that this sound should be played on. This
  31288. is used by the SynthesiserSound::appliesToNote() method
  31289. @param midiNoteForNormalPitch the midi note at which the sample should be played
  31290. with its natural rate. All other notes will be pitched
  31291. up or down relative to this one
  31292. @param attackTimeSecs the attack (fade-in) time, in seconds
  31293. @param releaseTimeSecs the decay (fade-out) time, in seconds
  31294. @param maxSampleLengthSeconds a maximum length of audio to read from the audio
  31295. source, in seconds
  31296. */
  31297. SamplerSound (const String& name,
  31298. AudioFormatReader& source,
  31299. const BigInteger& midiNotes,
  31300. int midiNoteForNormalPitch,
  31301. double attackTimeSecs,
  31302. double releaseTimeSecs,
  31303. double maxSampleLengthSeconds);
  31304. /** Destructor. */
  31305. ~SamplerSound();
  31306. /** Returns the sample's name */
  31307. const String& getName() const { return name; }
  31308. /** Returns the audio sample data.
  31309. This could be 0 if there was a problem loading it.
  31310. */
  31311. AudioSampleBuffer* getAudioData() const { return data; }
  31312. bool appliesToNote (const int midiNoteNumber);
  31313. bool appliesToChannel (const int midiChannel);
  31314. juce_UseDebuggingNewOperator
  31315. private:
  31316. friend class SamplerVoice;
  31317. String name;
  31318. ScopedPointer <AudioSampleBuffer> data;
  31319. double sourceSampleRate;
  31320. BigInteger midiNotes;
  31321. int length, attackSamples, releaseSamples;
  31322. int midiRootNote;
  31323. };
  31324. /**
  31325. A subclass of SynthesiserVoice that can play a SamplerSound.
  31326. To use it, create a Synthesiser, add some SamplerVoice objects to it, then
  31327. give it some SampledSound objects to play.
  31328. @see SamplerSound, Synthesiser, SynthesiserVoice
  31329. */
  31330. class JUCE_API SamplerVoice : public SynthesiserVoice
  31331. {
  31332. public:
  31333. /** Creates a SamplerVoice.
  31334. */
  31335. SamplerVoice();
  31336. /** Destructor. */
  31337. ~SamplerVoice();
  31338. bool canPlaySound (SynthesiserSound* sound);
  31339. void startNote (const int midiNoteNumber,
  31340. const float velocity,
  31341. SynthesiserSound* sound,
  31342. const int currentPitchWheelPosition);
  31343. void stopNote (const bool allowTailOff);
  31344. void pitchWheelMoved (const int newValue);
  31345. void controllerMoved (const int controllerNumber,
  31346. const int newValue);
  31347. void renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples);
  31348. juce_UseDebuggingNewOperator
  31349. private:
  31350. double pitchRatio;
  31351. double sourceSamplePosition;
  31352. float lgain, rgain, attackReleaseLevel, attackDelta, releaseDelta;
  31353. bool isInAttack, isInRelease;
  31354. };
  31355. #endif // __JUCE_SAMPLER_JUCEHEADER__
  31356. /*** End of inlined file: juce_Sampler.h ***/
  31357. #endif
  31358. #ifndef __JUCE_SYNTHESISER_JUCEHEADER__
  31359. #endif
  31360. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31361. /*** Start of inlined file: juce_ActionBroadcaster.h ***/
  31362. #ifndef __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31363. #define __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31364. /*** Start of inlined file: juce_ActionListenerList.h ***/
  31365. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31366. #define __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31367. /**
  31368. A set of ActionListeners.
  31369. Listeners can be added and removed from the list, and messages can be
  31370. broadcast to all the listeners.
  31371. @see ActionListener, ActionBroadcaster
  31372. */
  31373. class JUCE_API ActionListenerList : public MessageListener
  31374. {
  31375. public:
  31376. /** Creates an empty list. */
  31377. ActionListenerList() throw();
  31378. /** Destructor. */
  31379. ~ActionListenerList() throw();
  31380. /** Adds a listener to the list.
  31381. (Trying to add a listener that's already on the list will have no effect).
  31382. */
  31383. void addActionListener (ActionListener* listener) throw();
  31384. /** Removes a listener from the list.
  31385. If the listener isn't on the list, this won't have any effect.
  31386. */
  31387. void removeActionListener (ActionListener* listener) throw();
  31388. /** Removes all listeners from the list. */
  31389. void removeAllActionListeners() throw();
  31390. /** Broadcasts a message to all the registered listeners.
  31391. This sends the message asynchronously.
  31392. If a listener is on the list when this method is called but is removed from
  31393. the list before the message arrives, it won't receive the message. Similarly
  31394. listeners that are added to the list after the message is sent but before it
  31395. arrives won't get the message either.
  31396. */
  31397. void sendActionMessage (const String& message) const;
  31398. /** @internal */
  31399. void handleMessage (const Message&);
  31400. juce_UseDebuggingNewOperator
  31401. private:
  31402. SortedSet <void*> actionListeners_;
  31403. CriticalSection actionListenerLock_;
  31404. ActionListenerList (const ActionListenerList&);
  31405. ActionListenerList& operator= (const ActionListenerList&);
  31406. };
  31407. #endif // __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31408. /*** End of inlined file: juce_ActionListenerList.h ***/
  31409. /** Manages a list of ActionListeners, and can send them messages.
  31410. To quickly add methods to your class that can add/remove action
  31411. listeners and broadcast to them, you can derive from this.
  31412. @see ActionListenerList, ActionListener
  31413. */
  31414. class JUCE_API ActionBroadcaster
  31415. {
  31416. public:
  31417. /** Creates an ActionBroadcaster. */
  31418. ActionBroadcaster() throw();
  31419. /** Destructor. */
  31420. virtual ~ActionBroadcaster();
  31421. /** Adds a listener to the list.
  31422. (Trying to add a listener that's already on the list will have no effect).
  31423. */
  31424. void addActionListener (ActionListener* listener);
  31425. /** Removes a listener from the list.
  31426. If the listener isn't on the list, this won't have any effect.
  31427. */
  31428. void removeActionListener (ActionListener* listener);
  31429. /** Removes all listeners from the list. */
  31430. void removeAllActionListeners();
  31431. /** Broadcasts a message to all the registered listeners.
  31432. @see ActionListenerList::sendActionMessage
  31433. */
  31434. void sendActionMessage (const String& message) const;
  31435. private:
  31436. ActionListenerList actionListenerList;
  31437. ActionBroadcaster (const ActionBroadcaster&);
  31438. ActionBroadcaster& operator= (const ActionBroadcaster&);
  31439. };
  31440. #endif // __JUCE_ACTIONBROADCASTER_JUCEHEADER__
  31441. /*** End of inlined file: juce_ActionBroadcaster.h ***/
  31442. #endif
  31443. #ifndef __JUCE_ACTIONLISTENER_JUCEHEADER__
  31444. #endif
  31445. #ifndef __JUCE_ACTIONLISTENERLIST_JUCEHEADER__
  31446. #endif
  31447. #ifndef __JUCE_ASYNCUPDATER_JUCEHEADER__
  31448. #endif
  31449. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31450. /*** Start of inlined file: juce_CallbackMessage.h ***/
  31451. #ifndef __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31452. #define __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31453. /**
  31454. A message that calls a custom function when it gets delivered.
  31455. You can use this class to fire off actions that you want to be performed later
  31456. on the message thread.
  31457. Unlike other Message objects, these don't get sent to a MessageListener, you
  31458. just call the post() method to send them, and when they arrive, your
  31459. messageCallback() method will automatically be invoked.
  31460. @see MessageListener, MessageManager, ActionListener, ChangeListener
  31461. */
  31462. class JUCE_API CallbackMessage : public Message
  31463. {
  31464. public:
  31465. CallbackMessage() throw();
  31466. /** Destructor. */
  31467. ~CallbackMessage() throw();
  31468. /** Called when the message is delivered.
  31469. You should implement this method and make it do whatever action you want
  31470. to perform.
  31471. Note that like all other messages, this object will be deleted immediately
  31472. after this method has been invoked.
  31473. */
  31474. virtual void messageCallback() = 0;
  31475. /** Instead of sending this message to a MessageListener, just call this method
  31476. to post it to the event queue.
  31477. After you've called this, this object will belong to the MessageManager,
  31478. which will delete it later. So make sure you don't delete the object yourself,
  31479. call post() more than once, or call post() on a stack-based obect!
  31480. */
  31481. void post();
  31482. juce_UseDebuggingNewOperator
  31483. private:
  31484. CallbackMessage (const CallbackMessage&);
  31485. CallbackMessage& operator= (const CallbackMessage&);
  31486. };
  31487. #endif // __JUCE_CALLBACKMESSAGE_JUCEHEADER__
  31488. /*** End of inlined file: juce_CallbackMessage.h ***/
  31489. #endif
  31490. #ifndef __JUCE_CHANGEBROADCASTER_JUCEHEADER__
  31491. #endif
  31492. #ifndef __JUCE_CHANGELISTENER_JUCEHEADER__
  31493. #endif
  31494. #ifndef __JUCE_CHANGELISTENERLIST_JUCEHEADER__
  31495. #endif
  31496. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31497. /*** Start of inlined file: juce_InterprocessConnection.h ***/
  31498. #ifndef __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31499. #define __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31500. class InterprocessConnectionServer;
  31501. /**
  31502. Manages a simple two-way messaging connection to another process, using either
  31503. a socket or a named pipe as the transport medium.
  31504. To connect to a waiting socket or an open pipe, use the connectToSocket() or
  31505. connectToPipe() methods. If this succeeds, messages can be sent to the other end,
  31506. and incoming messages will result in a callback via the messageReceived()
  31507. method.
  31508. To open a pipe and wait for another client to connect to it, use the createPipe()
  31509. method.
  31510. To act as a socket server and create connections for one or more client, see the
  31511. InterprocessConnectionServer class.
  31512. @see InterprocessConnectionServer, Socket, NamedPipe
  31513. */
  31514. class JUCE_API InterprocessConnection : public Thread,
  31515. private MessageListener
  31516. {
  31517. public:
  31518. /** Creates a connection.
  31519. Connections are created manually, connecting them with the connectToSocket()
  31520. or connectToPipe() methods, or they are created automatically by a InterprocessConnectionServer
  31521. when a client wants to connect.
  31522. @param callbacksOnMessageThread if true, callbacks to the connectionMade(),
  31523. connectionLost() and messageReceived() methods will
  31524. always be made using the message thread; if false,
  31525. these will be called immediately on the connection's
  31526. own thread.
  31527. @param magicMessageHeaderNumber a magic number to use in the header to check the
  31528. validity of the data blocks being sent and received. This
  31529. can be any number, but the sender and receiver must obviously
  31530. use matching values or they won't recognise each other.
  31531. */
  31532. InterprocessConnection (bool callbacksOnMessageThread = true,
  31533. uint32 magicMessageHeaderNumber = 0xf2b49e2c);
  31534. /** Destructor. */
  31535. ~InterprocessConnection();
  31536. /** Tries to connect this object to a socket.
  31537. For this to work, the machine on the other end needs to have a InterprocessConnectionServer
  31538. object waiting to receive client connections on this port number.
  31539. @param hostName the host computer, either a network address or name
  31540. @param portNumber the socket port number to try to connect to
  31541. @param timeOutMillisecs how long to keep trying before giving up
  31542. @returns true if the connection is established successfully
  31543. @see Socket
  31544. */
  31545. bool connectToSocket (const String& hostName,
  31546. int portNumber,
  31547. int timeOutMillisecs);
  31548. /** Tries to connect the object to an existing named pipe.
  31549. For this to work, another process on the same computer must already have opened
  31550. an InterprocessConnection object and used createPipe() to create a pipe for this
  31551. to connect to.
  31552. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31553. @returns true if it connects successfully.
  31554. @see createPipe, NamedPipe
  31555. */
  31556. bool connectToPipe (const String& pipeName,
  31557. int pipeReceiveMessageTimeoutMs = -1);
  31558. /** Tries to create a new pipe for other processes to connect to.
  31559. This creates a pipe with the given name, so that other processes can use
  31560. connectToPipe() to connect to the other end.
  31561. You can optionally specify a timeout length to be passed to the NamedPipe::read() method.
  31562. If another process is already using this pipe, this will fail and return false.
  31563. */
  31564. bool createPipe (const String& pipeName,
  31565. int pipeReceiveMessageTimeoutMs = -1);
  31566. /** Disconnects and closes any currently-open sockets or pipes. */
  31567. void disconnect();
  31568. /** True if a socket or pipe is currently active. */
  31569. bool isConnected() const;
  31570. /** Returns the socket that this connection is using (or null if it uses a pipe). */
  31571. StreamingSocket* getSocket() const throw() { return socket; }
  31572. /** Returns the pipe that this connection is using (or null if it uses a socket). */
  31573. NamedPipe* getPipe() const throw() { return pipe; }
  31574. /** Returns the name of the machine at the other end of this connection.
  31575. This will return an empty string if the other machine isn't known for
  31576. some reason.
  31577. */
  31578. const String getConnectedHostName() const;
  31579. /** Tries to send a message to the other end of this connection.
  31580. This will fail if it's not connected, or if there's some kind of write error. If
  31581. it succeeds, the connection object at the other end will receive the message by
  31582. a callback to its messageReceived() method.
  31583. @see messageReceived
  31584. */
  31585. bool sendMessage (const MemoryBlock& message);
  31586. /** Called when the connection is first connected.
  31587. If the connection was created with the callbacksOnMessageThread flag set, then
  31588. this will be called on the message thread; otherwise it will be called on a server
  31589. thread.
  31590. */
  31591. virtual void connectionMade() = 0;
  31592. /** Called when the connection is broken.
  31593. If the connection was created with the callbacksOnMessageThread flag set, then
  31594. this will be called on the message thread; otherwise it will be called on a server
  31595. thread.
  31596. */
  31597. virtual void connectionLost() = 0;
  31598. /** Called when a message arrives.
  31599. When the object at the other end of this connection sends us a message with sendMessage(),
  31600. this callback is used to deliver it to us.
  31601. If the connection was created with the callbacksOnMessageThread flag set, then
  31602. this will be called on the message thread; otherwise it will be called on a server
  31603. thread.
  31604. @see sendMessage
  31605. */
  31606. virtual void messageReceived (const MemoryBlock& message) = 0;
  31607. juce_UseDebuggingNewOperator
  31608. private:
  31609. CriticalSection pipeAndSocketLock;
  31610. ScopedPointer <StreamingSocket> socket;
  31611. ScopedPointer <NamedPipe> pipe;
  31612. bool callbackConnectionState;
  31613. const bool useMessageThread;
  31614. const uint32 magicMessageHeader;
  31615. int pipeReceiveMessageTimeout;
  31616. friend class InterprocessConnectionServer;
  31617. void initialiseWithSocket (StreamingSocket* socket_);
  31618. void initialiseWithPipe (NamedPipe* pipe_);
  31619. void handleMessage (const Message& message);
  31620. void connectionMadeInt();
  31621. void connectionLostInt();
  31622. void deliverDataInt (const MemoryBlock& data);
  31623. bool readNextMessageInt();
  31624. void run();
  31625. InterprocessConnection (const InterprocessConnection&);
  31626. InterprocessConnection& operator= (const InterprocessConnection&);
  31627. };
  31628. #endif // __JUCE_INTERPROCESSCONNECTION_JUCEHEADER__
  31629. /*** End of inlined file: juce_InterprocessConnection.h ***/
  31630. #endif
  31631. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31632. /*** Start of inlined file: juce_InterprocessConnectionServer.h ***/
  31633. #ifndef __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31634. #define __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31635. /**
  31636. An object that waits for client sockets to connect to a port on this host, and
  31637. creates InterprocessConnection objects for each one.
  31638. To use this, create a class derived from it which implements the createConnectionObject()
  31639. method, so that it creates suitable connection objects for each client that tries
  31640. to connect.
  31641. @see InterprocessConnection
  31642. */
  31643. class JUCE_API InterprocessConnectionServer : private Thread
  31644. {
  31645. public:
  31646. /** Creates an uninitialised server object.
  31647. */
  31648. InterprocessConnectionServer();
  31649. /** Destructor. */
  31650. ~InterprocessConnectionServer();
  31651. /** Starts an internal thread which listens on the given port number.
  31652. While this is running, in another process tries to connect with the
  31653. InterprocessConnection::connectToSocket() method, this object will call
  31654. createConnectionObject() to create a connection to that client.
  31655. Use stop() to stop the thread running.
  31656. @see createConnectionObject, stop
  31657. */
  31658. bool beginWaitingForSocket (int portNumber);
  31659. /** Terminates the listener thread, if it's active.
  31660. @see beginWaitingForSocket
  31661. */
  31662. void stop();
  31663. protected:
  31664. /** Creates a suitable connection object for a client process that wants to
  31665. connect to this one.
  31666. This will be called by the listener thread when a client process tries
  31667. to connect, and must return a new InterprocessConnection object that will
  31668. then run as this end of the connection.
  31669. @see InterprocessConnection
  31670. */
  31671. virtual InterprocessConnection* createConnectionObject() = 0;
  31672. public:
  31673. juce_UseDebuggingNewOperator
  31674. private:
  31675. ScopedPointer <StreamingSocket> socket;
  31676. void run();
  31677. InterprocessConnectionServer (const InterprocessConnectionServer&);
  31678. InterprocessConnectionServer& operator= (const InterprocessConnectionServer&);
  31679. };
  31680. #endif // __JUCE_INTERPROCESSCONNECTIONSERVER_JUCEHEADER__
  31681. /*** End of inlined file: juce_InterprocessConnectionServer.h ***/
  31682. #endif
  31683. #ifndef __JUCE_LISTENERLIST_JUCEHEADER__
  31684. #endif
  31685. #ifndef __JUCE_MESSAGE_JUCEHEADER__
  31686. #endif
  31687. #ifndef __JUCE_MESSAGELISTENER_JUCEHEADER__
  31688. #endif
  31689. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31690. /*** Start of inlined file: juce_MessageManager.h ***/
  31691. #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31692. #define __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31693. class Component;
  31694. class MessageManagerLock;
  31695. /** See MessageManager::callFunctionOnMessageThread() for use of this function type
  31696. */
  31697. typedef void* (MessageCallbackFunction) (void* userData);
  31698. /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop.
  31699. @see Message, MessageListener, MessageManagerLock, JUCEApplication
  31700. */
  31701. class JUCE_API MessageManager
  31702. {
  31703. public:
  31704. /** Returns the global instance of the MessageManager. */
  31705. static MessageManager* getInstance() throw();
  31706. /** Runs the event dispatch loop until a stop message is posted.
  31707. This method is only intended to be run by the application's startup routine,
  31708. as it blocks, and will only return after the stopDispatchLoop() method has been used.
  31709. @see stopDispatchLoop
  31710. */
  31711. void runDispatchLoop();
  31712. /** Sends a signal that the dispatch loop should terminate.
  31713. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods
  31714. will be interrupted and will return.
  31715. @see runDispatchLoop
  31716. */
  31717. void stopDispatchLoop();
  31718. /** Returns true if the stopDispatchLoop() method has been called.
  31719. */
  31720. bool hasStopMessageBeenSent() const throw() { return quitMessagePosted; }
  31721. /** Synchronously dispatches messages until a given time has elapsed.
  31722. Returns false if a quit message has been posted by a call to stopDispatchLoop(),
  31723. otherwise returns true.
  31724. */
  31725. bool runDispatchLoopUntil (int millisecondsToRunFor);
  31726. /** Calls a function using the message-thread.
  31727. This can be used by any thread to cause this function to be called-back
  31728. by the message thread. If it's the message-thread that's calling this method,
  31729. then the function will just be called; if another thread is calling, a message
  31730. will be posted to the queue, and this method will block until that message
  31731. is delivered, the function is called, and the result is returned.
  31732. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller
  31733. thread has a critical section locked, which an unrelated message callback then tries to lock
  31734. before the message thread gets round to processing this callback.
  31735. @param callback the function to call - its signature must be @code
  31736. void* myCallbackFunction (void*) @endcode
  31737. @param userData a user-defined pointer that will be passed to the function that gets called
  31738. @returns the value that the callback function returns.
  31739. @see MessageManagerLock
  31740. */
  31741. void* callFunctionOnMessageThread (MessageCallbackFunction* callback,
  31742. void* userData);
  31743. /** Returns true if the caller-thread is the message thread. */
  31744. bool isThisTheMessageThread() const throw();
  31745. /** Called to tell the manager that the current thread is the one that's running the dispatch loop.
  31746. (Best to ignore this method unless you really know what you're doing..)
  31747. @see getCurrentMessageThread
  31748. */
  31749. void setCurrentThreadAsMessageThread();
  31750. /** Returns the ID of the current message thread, as set by setCurrentMessageThread().
  31751. (Best to ignore this method unless you really know what you're doing..)
  31752. @see setCurrentMessageThread
  31753. */
  31754. Thread::ThreadID getCurrentMessageThread() const throw() { return messageThreadId; }
  31755. /** Returns true if the caller thread has currenltly got the message manager locked.
  31756. see the MessageManagerLock class for more info about this.
  31757. This will be true if the caller is the message thread, because that automatically
  31758. gains a lock while a message is being dispatched.
  31759. */
  31760. bool currentThreadHasLockedMessageManager() const throw();
  31761. /** Sends a message to all other JUCE applications that are running.
  31762. @param messageText the string that will be passed to the actionListenerCallback()
  31763. method of the broadcast listeners in the other app.
  31764. @see registerBroadcastListener, ActionListener
  31765. */
  31766. static void broadcastMessage (const String& messageText) throw();
  31767. /** Registers a listener to get told about broadcast messages.
  31768. The actionListenerCallback() callback's string parameter
  31769. is the message passed into broadcastMessage().
  31770. @see broadcastMessage
  31771. */
  31772. void registerBroadcastListener (ActionListener* listener) throw();
  31773. /** Deregisters a broadcast listener. */
  31774. void deregisterBroadcastListener (ActionListener* listener) throw();
  31775. /** @internal */
  31776. void deliverMessage (Message*);
  31777. /** @internal */
  31778. void deliverBroadcastMessage (const String&);
  31779. /** @internal */
  31780. ~MessageManager() throw();
  31781. juce_UseDebuggingNewOperator
  31782. private:
  31783. MessageManager() throw();
  31784. friend class MessageListener;
  31785. friend class ChangeBroadcaster;
  31786. friend class ActionBroadcaster;
  31787. friend class CallbackMessage;
  31788. static MessageManager* instance;
  31789. SortedSet <const MessageListener*> messageListeners;
  31790. ScopedPointer <ActionListenerList> broadcastListeners;
  31791. friend class JUCEApplication;
  31792. bool quitMessagePosted, quitMessageReceived;
  31793. Thread::ThreadID messageThreadId;
  31794. static void* exitModalLoopCallback (void*);
  31795. void postMessageToQueue (Message* message);
  31796. void postCallbackMessage (Message* message);
  31797. static void doPlatformSpecificInitialisation();
  31798. static void doPlatformSpecificShutdown();
  31799. friend class MessageManagerLock;
  31800. Thread::ThreadID volatile threadWithLock;
  31801. CriticalSection lockingLock;
  31802. MessageManager (const MessageManager&);
  31803. MessageManager& operator= (const MessageManager&);
  31804. };
  31805. /** Used to make sure that the calling thread has exclusive access to the message loop.
  31806. Because it's not thread-safe to call any of the Component or other UI classes
  31807. from threads other than the message thread, one of these objects can be used to
  31808. lock the message loop and allow this to be done. The message thread will be
  31809. suspended for the lifetime of the MessageManagerLock object, so create one on
  31810. the stack like this: @code
  31811. void MyThread::run()
  31812. {
  31813. someData = 1234;
  31814. const MessageManagerLock mmLock;
  31815. // the event loop will now be locked so it's safe to make a few calls..
  31816. myComponent->setBounds (newBounds);
  31817. myComponent->repaint();
  31818. // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope
  31819. }
  31820. @endcode
  31821. Obviously be careful not to create one of these and leave it lying around, or
  31822. your app will grind to a halt!
  31823. Another caveat is that using this in conjunction with other CriticalSections
  31824. can create lots of interesting ways of producing a deadlock! In particular, if
  31825. your message thread calls stopThread() for a thread that uses these locks,
  31826. you'll get an (occasional) deadlock..
  31827. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager
  31828. */
  31829. class JUCE_API MessageManagerLock
  31830. {
  31831. public:
  31832. /** Tries to acquire a lock on the message manager.
  31833. The constructor attempts to gain a lock on the message loop, and the lock will be
  31834. kept for the lifetime of this object.
  31835. Optionally, you can pass a thread object here, and while waiting to obtain the lock,
  31836. this method will keep checking whether the thread has been given the
  31837. Thread::signalThreadShouldExit() signal. If this happens, then it will return
  31838. without gaining the lock. If you pass a thread, you must check whether the lock was
  31839. successful by calling lockWasGained(). If this is false, your thread is being told to
  31840. die, so you should take evasive action.
  31841. If you pass zero for the thread object, it will wait indefinitely for the lock - be
  31842. careful when doing this, because it's very easy to deadlock if your message thread
  31843. attempts to call stopThread() on a thread just as that thread attempts to get the
  31844. message lock.
  31845. If the calling thread already has the lock, nothing will be done, so it's safe and
  31846. quick to use these locks recursively.
  31847. E.g.
  31848. @code
  31849. void run()
  31850. {
  31851. ...
  31852. while (! threadShouldExit())
  31853. {
  31854. MessageManagerLock mml (Thread::getCurrentThread());
  31855. if (! mml.lockWasGained())
  31856. return; // another thread is trying to kill us!
  31857. ..do some locked stuff here..
  31858. }
  31859. ..and now the MM is now unlocked..
  31860. }
  31861. @endcode
  31862. */
  31863. MessageManagerLock (Thread* threadToCheckForExitSignal = 0) throw();
  31864. /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob
  31865. instead of a thread.
  31866. See the MessageManagerLock (Thread*) constructor for details on how this works.
  31867. */
  31868. MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal) throw();
  31869. /** Releases the current thread's lock on the message manager.
  31870. Make sure this object is created and deleted by the same thread,
  31871. otherwise there are no guarantees what will happen!
  31872. */
  31873. ~MessageManagerLock() throw();
  31874. /** Returns true if the lock was successfully acquired.
  31875. (See the constructor that takes a Thread for more info).
  31876. */
  31877. bool lockWasGained() const throw() { return locked; }
  31878. private:
  31879. class SharedEvents;
  31880. class BlockingMessage;
  31881. friend class SharedEvents;
  31882. friend class BlockingMessage;
  31883. SharedEvents* sharedEvents;
  31884. bool locked;
  31885. void init (Thread* thread, ThreadPoolJob* job) throw();
  31886. MessageManagerLock (const MessageManagerLock&);
  31887. MessageManagerLock& operator= (const MessageManagerLock&);
  31888. };
  31889. #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
  31890. /*** End of inlined file: juce_MessageManager.h ***/
  31891. #endif
  31892. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31893. /*** Start of inlined file: juce_MultiTimer.h ***/
  31894. #ifndef __JUCE_MULTITIMER_JUCEHEADER__
  31895. #define __JUCE_MULTITIMER_JUCEHEADER__
  31896. /**
  31897. A type of timer class that can run multiple timers with different frequencies,
  31898. all of which share a single callback.
  31899. This class is very similar to the Timer class, but allows you run multiple
  31900. separate timers, where each one has a unique ID number. The methods in this
  31901. class are exactly equivalent to those in Timer, but with the addition of
  31902. this ID number.
  31903. To use it, you need to create a subclass of MultiTimer, implementing the
  31904. timerCallback() method. Then you can start timers with startTimer(), and
  31905. each time the callback is triggered, it passes in the ID of the timer that
  31906. caused it.
  31907. @see Timer
  31908. */
  31909. class JUCE_API MultiTimer
  31910. {
  31911. protected:
  31912. /** Creates a MultiTimer.
  31913. When created, no timers are running, so use startTimer() to start things off.
  31914. */
  31915. MultiTimer() throw();
  31916. /** Creates a copy of another timer.
  31917. Note that this timer will not contain any running timers, even if the one you're
  31918. copying from was running.
  31919. */
  31920. MultiTimer (const MultiTimer& other) throw();
  31921. public:
  31922. /** Destructor. */
  31923. virtual ~MultiTimer();
  31924. /** The user-defined callback routine that actually gets called by each of the
  31925. timers that are running.
  31926. It's perfectly ok to call startTimer() or stopTimer() from within this
  31927. callback to change the subsequent intervals.
  31928. */
  31929. virtual void timerCallback (int timerId) = 0;
  31930. /** Starts a timer and sets the length of interval required.
  31931. If the timer is already started, this will reset it, so the
  31932. time between calling this method and the next timer callback
  31933. will not be less than the interval length passed in.
  31934. @param timerId a unique Id number that identifies the timer to
  31935. start. This is the id that will be passed back
  31936. to the timerCallback() method when this timer is
  31937. triggered
  31938. @param intervalInMilliseconds the interval to use (any values less than 1 will be
  31939. rounded up to 1)
  31940. */
  31941. void startTimer (int timerId, int intervalInMilliseconds) throw();
  31942. /** Stops a timer.
  31943. If a timer has been started with the given ID number, it will be cancelled.
  31944. No more callbacks will be made for the specified timer after this method returns.
  31945. If this is called from a different thread, any callbacks that may
  31946. be currently executing may be allowed to finish before the method
  31947. returns.
  31948. */
  31949. void stopTimer (int timerId) throw();
  31950. /** Checks whether a timer has been started for a specified ID.
  31951. @returns true if a timer with the given ID is running.
  31952. */
  31953. bool isTimerRunning (int timerId) const throw();
  31954. /** Returns the interval for a specified timer ID.
  31955. @returns the timer's interval in milliseconds if it's running, or 0 if it's no timer
  31956. is running for the ID number specified.
  31957. */
  31958. int getTimerInterval (int timerId) const throw();
  31959. private:
  31960. class MultiTimerCallback;
  31961. CriticalSection timerListLock;
  31962. OwnedArray <MultiTimerCallback> timers;
  31963. MultiTimer& operator= (const MultiTimer&);
  31964. };
  31965. #endif // __JUCE_MULTITIMER_JUCEHEADER__
  31966. /*** End of inlined file: juce_MultiTimer.h ***/
  31967. #endif
  31968. #ifndef __JUCE_TIMER_JUCEHEADER__
  31969. #endif
  31970. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31971. /*** Start of inlined file: juce_ArrowButton.h ***/
  31972. #ifndef __JUCE_ARROWBUTTON_JUCEHEADER__
  31973. #define __JUCE_ARROWBUTTON_JUCEHEADER__
  31974. /*** Start of inlined file: juce_DropShadowEffect.h ***/
  31975. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31976. #define __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  31977. /**
  31978. An effect filter that adds a drop-shadow behind the image's content.
  31979. (This will only work on images/components that aren't opaque, of course).
  31980. When added to a component, this effect will draw a soft-edged
  31981. shadow based on what gets drawn inside it. The shadow will also
  31982. be applied to the component's children.
  31983. For speed, this doesn't use a proper gaussian blur, but cheats by
  31984. using a simple bilinear filter. If you need a really high-quality
  31985. shadow, check out ImageConvolutionKernel::createGaussianBlur()
  31986. @see Component::setComponentEffect
  31987. */
  31988. class JUCE_API DropShadowEffect : public ImageEffectFilter
  31989. {
  31990. public:
  31991. /** Creates a default drop-shadow effect.
  31992. To customise the shadow's appearance, use the setShadowProperties()
  31993. method.
  31994. */
  31995. DropShadowEffect();
  31996. /** Destructor. */
  31997. ~DropShadowEffect();
  31998. /** Sets up parameters affecting the shadow's appearance.
  31999. @param newRadius the (approximate) radius of the blur used
  32000. @param newOpacity the opacity with which the shadow is rendered
  32001. @param newShadowOffsetX allows the shadow to be shifted in relation to the
  32002. component's contents
  32003. @param newShadowOffsetY allows the shadow to be shifted in relation to the
  32004. component's contents
  32005. */
  32006. void setShadowProperties (float newRadius,
  32007. float newOpacity,
  32008. int newShadowOffsetX,
  32009. int newShadowOffsetY);
  32010. /** @internal */
  32011. void applyEffect (Image& sourceImage, Graphics& destContext);
  32012. juce_UseDebuggingNewOperator
  32013. private:
  32014. int offsetX, offsetY;
  32015. float radius, opacity;
  32016. };
  32017. #endif // __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  32018. /*** End of inlined file: juce_DropShadowEffect.h ***/
  32019. /**
  32020. A button with an arrow in it.
  32021. @see Button
  32022. */
  32023. class JUCE_API ArrowButton : public Button
  32024. {
  32025. public:
  32026. /** Creates an ArrowButton.
  32027. @param buttonName the name to give the button
  32028. @param arrowDirection the direction the arrow should point in, where 0.0 is
  32029. pointing right, 0.25 is down, 0.5 is left, 0.75 is up
  32030. @param arrowColour the colour to use for the arrow
  32031. */
  32032. ArrowButton (const String& buttonName,
  32033. float arrowDirection,
  32034. const Colour& arrowColour);
  32035. /** Destructor. */
  32036. ~ArrowButton();
  32037. juce_UseDebuggingNewOperator
  32038. protected:
  32039. /** @internal */
  32040. void paintButton (Graphics& g,
  32041. bool isMouseOverButton,
  32042. bool isButtonDown);
  32043. /** @internal */
  32044. void buttonStateChanged();
  32045. private:
  32046. Colour colour;
  32047. DropShadowEffect shadow;
  32048. Path path;
  32049. int offset;
  32050. ArrowButton (const ArrowButton&);
  32051. ArrowButton& operator= (const ArrowButton&);
  32052. };
  32053. #endif // __JUCE_ARROWBUTTON_JUCEHEADER__
  32054. /*** End of inlined file: juce_ArrowButton.h ***/
  32055. #endif
  32056. #ifndef __JUCE_BUTTON_JUCEHEADER__
  32057. #endif
  32058. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32059. /*** Start of inlined file: juce_DrawableButton.h ***/
  32060. #ifndef __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32061. #define __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32062. /*** Start of inlined file: juce_Drawable.h ***/
  32063. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  32064. #define __JUCE_DRAWABLE_JUCEHEADER__
  32065. /*** Start of inlined file: juce_RelativeCoordinate.h ***/
  32066. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32067. #define __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32068. /**
  32069. Expresses a coordinate as an absolute or proportional distance from other
  32070. named coordinates.
  32071. A RelativeCoordinate represents a position as either:
  32072. - an absolute distance from the origin
  32073. - an absolute distance from another named RelativeCoordinate
  32074. - a proportion of the distance between two other named RelativeCoordinates
  32075. Of course, the coordinates that this one is relative to may themselves be relative
  32076. to other coordinates, so complex arrangements can be built up (as long as you're careful
  32077. not to create recursive loops!)
  32078. Rather than keeping pointers to the coordinates that this one is dependent on, it
  32079. stores their names, and when resolving this coordinate to an absolute value, a
  32080. NamedCoordinateFinder class is required to retrieve these coordinates by name.
  32081. @see RelativePoint, RelativeRectangle
  32082. */
  32083. class JUCE_API RelativeCoordinate
  32084. {
  32085. public:
  32086. /** Creates a zero coordinate. */
  32087. RelativeCoordinate();
  32088. /** Creates an absolute position from the parent origin on either the X or Y axis.
  32089. @param absoluteDistanceFromOrigin the distance from the origin
  32090. */
  32091. RelativeCoordinate (double absoluteDistanceFromOrigin);
  32092. /** Creates an absolute position relative to a named coordinate.
  32093. @param absoluteDistanceFromAnchor the distance to add to the named anchor point
  32094. @param anchorPoint the name of the coordinate from which this one will be relative. See the constructor
  32095. notes for a description of the syntax for coordinate names.
  32096. */
  32097. RelativeCoordinate (double absoluteDistanceFromAnchor, const String& anchorPoint);
  32098. /** Creates a relative position between two named points.
  32099. @param relativeProportionBetweenAnchors a value between 0 and 1 indicating this coordinate's relative position
  32100. between anchorPoint1 and anchorPoint2.
  32101. @param anchorPoint1 the name of the first coordinate from which this one will be relative. See the constructor
  32102. notes for a description of the syntax for coordinate names.
  32103. @param anchorPoint2 the name of the first coordinate from which this one will be relative. See the constructor
  32104. notes for a description of the syntax for coordinate names.
  32105. */
  32106. RelativeCoordinate (double relativeProportionBetweenAnchors, const String& anchorPoint1, const String& anchorPoint2);
  32107. /** Recreates a coordinate from a string description.
  32108. The string can be in one of the following formats:
  32109. - "123" = 123 pixels from parent origin (this is equivalent to "parent.left + 123"
  32110. or "parent.top + 123", depending on which axis the coordinate is using)
  32111. - "anchor" = the same position as the coordinate named "anchor"
  32112. - "anchor + 123" = the coordinate named "anchor" + 123 pixels
  32113. - "anchor - 123" = the coordinate named "anchor" - 123 pixels
  32114. - "50%" = 50% of the distance between the coordinate space's top-left origin and its extent
  32115. (this is equivalent to "50% * parent.left -> parent.right" or "50% * parent.top -> parent.bottom")
  32116. - "50% * anchor" = 50% of the distance between the coordinate space's origin and the coordinate named "anchor"
  32117. (this is equivalent to "50% * parent.left -> anchor" or "50% * parent.top -> anchor")
  32118. - "50% * anchor1 -> anchor2" = 50% of the distance between the coordinate "anchor1" and the coordinate "anchor2"
  32119. An anchor name can either be just a single identifier (letters, digits and underscores only - no spaces),
  32120. e.g. "marker1", or it can be a two-part name in the form "objectName.edge". For example "parent.left" is
  32121. the origin, or "myComponent.top" is the top edge of a component called "myComponent". The exact names that
  32122. will be recognised are dependent on the NamedCoordinateFinder that you provide for looking them up, but
  32123. "parent.left" and "parent.top" are always available, meaning the origin. "parent.right" and "parent.bottom"
  32124. may also be available if the coordinate space has a fixed size.
  32125. @param stringVersion the string to parse
  32126. @param isHorizontal this must be true if this is an X coordinate, or false if it's on the Y axis.
  32127. @see toString
  32128. */
  32129. RelativeCoordinate (const String& stringVersion, bool isHorizontal);
  32130. /** Destructor. */
  32131. ~RelativeCoordinate();
  32132. bool operator== (const RelativeCoordinate& other) const throw();
  32133. bool operator!= (const RelativeCoordinate& other) const throw();
  32134. /**
  32135. Provides an interface for looking up the position of a named anchor when resolving a RelativeCoordinate.
  32136. When using RelativeCoordinates, to resolve their names you need to provide a subclass of this which
  32137. can retrieve a coordinate by name.
  32138. */
  32139. class JUCE_API NamedCoordinateFinder
  32140. {
  32141. public:
  32142. /** Destructor. */
  32143. virtual ~NamedCoordinateFinder() {}
  32144. /** Returns the coordinate for a given name.
  32145. The objectName parameter will be the first section of the name, and the edge the name of the second part.
  32146. E.g. for "parent.right", objectName would be "parent" and edge would be "right". If the name
  32147. has no dot, the edge parameter will be an empty string.
  32148. This method must be able to resolve "parent.left", "parent.top", "parent.right" and "parent.bottom", as
  32149. well as any other objects that your application uses.
  32150. */
  32151. virtual const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const = 0;
  32152. };
  32153. /** Calculates the absolute position of this coordinate.
  32154. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32155. be needed to calculate the result.
  32156. */
  32157. double resolve (const NamedCoordinateFinder* nameFinder) const;
  32158. /** Returns true if this coordinate uses the specified coord name at any level in its evaluation.
  32159. This will recursively check any coordinates upon which this one depends.
  32160. */
  32161. bool references (const String& coordName, const NamedCoordinateFinder* nameFinder) const;
  32162. /** Returns true if there's a recursive loop when trying to resolve this coordinate's position. */
  32163. bool isRecursive (const NamedCoordinateFinder* nameFinder) const;
  32164. /** Returns true if this coordinate depends on any other coordinates for its position. */
  32165. bool isDynamic() const;
  32166. /** Changes the value of this coord to make it resolve to the specified position.
  32167. Calling this will leave the anchor points unchanged, but will set this coordinate's absolute
  32168. or relative position to whatever value is necessary to make its resultant position
  32169. match the position that is provided.
  32170. */
  32171. void moveToAbsolute (double absoluteTargetPosition, const NamedCoordinateFinder* nameFinder);
  32172. /** Returns true if the coordinate is calculated as a proportion of the distance between two other points.
  32173. @see toggleProportionality
  32174. */
  32175. bool isProportional() const throw() { return anchor2.isNotEmpty(); }
  32176. /** Toggles the coordinate between using a proportional or absolute position.
  32177. Note that calling this will reset the names of any anchor points, and just make the
  32178. coordinate relative to the parent origin and parent size.
  32179. */
  32180. void toggleProportionality (const NamedCoordinateFinder* nameFinder,
  32181. const String& proportionalAnchor1, const String& proportionalAnchor2);
  32182. /** Returns a value that can be edited to set this coordinate's position.
  32183. The meaning of this number depends on the coordinate's mode. If the coordinate is
  32184. proportional, the number will be a percentage between 0 and 100. If the
  32185. coordinate is absolute, then it will be the number of pixels from its anchor point.
  32186. @see setEditableNumber
  32187. */
  32188. const double getEditableNumber() const;
  32189. /** Sets the value that controls this coordinate's position.
  32190. The meaning of this number depends on the coordinate's mode. If the coordinate is
  32191. proportional, the number must be a percentage between 0 and 100. If the
  32192. coordinate is absolute, then it indicates the number of pixels from its anchor point.
  32193. @see setEditableNumber
  32194. */
  32195. void setEditableNumber (const double newValue);
  32196. /** Returns the name of the first anchor point from which this coordinate is relative.
  32197. */
  32198. const String getAnchorName1 (const String& returnValueIfOrigin) const;
  32199. /** Returns the name of the second anchor point from which this coordinate is relative.
  32200. The second anchor is only valid if the coordinate is in proportional mode.
  32201. */
  32202. const String getAnchorName2 (const String& returnValueIfOrigin) const;
  32203. /** Returns the first anchor point as a coordinate. */
  32204. const RelativeCoordinate getAnchorCoordinate1() const;
  32205. /** Returns the first anchor point as a coordinate.
  32206. The second anchor is only valid if the coordinate is in proportional mode.
  32207. */
  32208. const RelativeCoordinate getAnchorCoordinate2() const;
  32209. /** Changes the first anchor point, keeping the resultant position of this coordinate in
  32210. the same place it was previously.
  32211. */
  32212. void changeAnchor1 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  32213. /** Changes the second anchor point, keeping the resultant position of this coordinate in
  32214. the same place it was previously.
  32215. */
  32216. void changeAnchor2 (const String& newAnchor, const NamedCoordinateFinder* nameFinder);
  32217. /** Tells the coordinate that an object is changing its name or being deleted.
  32218. If either of this coordinates anchor points match this name, they will be replaced.
  32219. If the newName string is empty, it indicates that the object is being removed, so if
  32220. this coordinate was using it, the coordinate is changed to be relative to the origin
  32221. instead.
  32222. */
  32223. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32224. const NamedCoordinateFinder* nameFinder);
  32225. /** Returns a string which represents this coordinate.
  32226. For details of the string syntax, see the constructor notes.
  32227. */
  32228. const String toString() const;
  32229. /** A set of static strings that are commonly used by the RelativeCoordinate class.
  32230. As well as avoiding using string literals in your code, using these preset values
  32231. has the advantage that all instances of the same string will share the same, reference-counted
  32232. String object, so if you have thousands of points which all refer to the same
  32233. anchor points, this can save a significant amount of memory allocation.
  32234. */
  32235. struct Strings
  32236. {
  32237. static const String parent; /**< "parent" */
  32238. static const String left; /**< "left" */
  32239. static const String right; /**< "right" */
  32240. static const String top; /**< "top" */
  32241. static const String bottom; /**< "bottom" */
  32242. static const String parentLeft; /**< "parent.left" */
  32243. static const String parentTop; /**< "parent.top" */
  32244. static const String parentRight; /**< "parent.right" */
  32245. static const String parentBottom; /**< "parent.bottom" */
  32246. };
  32247. private:
  32248. String anchor1, anchor2;
  32249. double value;
  32250. double resolve (const NamedCoordinateFinder* nameFinder, int recursionCounter) const;
  32251. static double resolveAnchor (const String& anchorName, const NamedCoordinateFinder* nameFinder, int recursionCounter);
  32252. };
  32253. /**
  32254. An X-Y position stored as a pair of RelativeCoordinate values.
  32255. @see RelativeCoordinate, RelativeRectangle
  32256. */
  32257. class JUCE_API RelativePoint
  32258. {
  32259. public:
  32260. /** Creates a point at the origin. */
  32261. RelativePoint();
  32262. /** Creates an absolute point, relative to the origin. */
  32263. RelativePoint (const Point<float>& absolutePoint);
  32264. /** Creates an absolute point, relative to the origin. */
  32265. RelativePoint (float absoluteX, float absoluteY);
  32266. /** Creates an absolute point from two coordinates. */
  32267. RelativePoint (const RelativeCoordinate& x, const RelativeCoordinate& y);
  32268. /** Creates a point from a stringified representation.
  32269. The string must contain a pair of coordinates, separated by space or a comma. The syntax for the coordinate
  32270. strings is explained in the RelativeCoordinate class.
  32271. @see toString
  32272. */
  32273. RelativePoint (const String& stringVersion);
  32274. bool operator== (const RelativePoint& other) const throw();
  32275. bool operator!= (const RelativePoint& other) const throw();
  32276. /** Calculates the absolute position of this point.
  32277. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32278. be needed to calculate the result.
  32279. */
  32280. const Point<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  32281. /** Changes the values of this point's coordinates to make it resolve to the specified position.
  32282. Calling this will leave any anchor points unchanged, but will set any absolute
  32283. or relative positions to whatever values are necessary to make the resultant position
  32284. match the position that is provided.
  32285. */
  32286. void moveToAbsolute (const Point<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32287. /** Returns a string which represents this point.
  32288. This returns a comma-separated pair of coordinates. For details of the string syntax used by the
  32289. coordinates, see the RelativeCoordinate constructor notes.
  32290. The string that is returned can be passed to the RelativePoint constructor to recreate the point.
  32291. */
  32292. const String toString() const;
  32293. /** Tells the point that an object is changing its name or being deleted.
  32294. This calls RelativeCoordinate::renameAnchorIfUsed() on its X and Y coordinates.
  32295. */
  32296. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32297. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32298. /** Returns true if this point depends on any other coordinates for its position. */
  32299. bool isDynamic() const;
  32300. // The actual X and Y coords...
  32301. RelativeCoordinate x, y;
  32302. };
  32303. /**
  32304. An rectangle stored as a set of RelativeCoordinate values.
  32305. The rectangle's top, left, bottom and right edge positions are each stored as a RelativeCoordinate.
  32306. @see RelativeCoordinate, RelativePoint
  32307. */
  32308. class JUCE_API RelativeRectangle
  32309. {
  32310. public:
  32311. /** Creates a zero-size rectangle at the origin. */
  32312. RelativeRectangle();
  32313. /** Creates an absolute rectangle, relative to the origin. */
  32314. explicit RelativeRectangle (const Rectangle<float>& rect, const String& componentName);
  32315. /** Creates a rectangle from four coordinates. */
  32316. RelativeRectangle (const RelativeCoordinate& left, const RelativeCoordinate& right,
  32317. const RelativeCoordinate& top, const RelativeCoordinate& bottom);
  32318. /** Creates a rectangle from a stringified representation.
  32319. The string must contain a sequence of 4 coordinates, separated by commas, in the order
  32320. left, top, right, bottom. The syntax for the coordinate strings is explained in the
  32321. RelativeCoordinate class.
  32322. @see toString
  32323. */
  32324. explicit RelativeRectangle (const String& stringVersion);
  32325. bool operator== (const RelativeRectangle& other) const throw();
  32326. bool operator!= (const RelativeRectangle& other) const throw();
  32327. /** Calculates the absolute position of this rectangle.
  32328. You'll need to provide a suitable NamedCoordinateFinder for looking up any coordinates that may
  32329. be needed to calculate the result.
  32330. */
  32331. const Rectangle<float> resolve (const RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  32332. /** Changes the values of this rectangle's coordinates to make it resolve to the specified position.
  32333. Calling this will leave any anchor points unchanged, but will set any absolute
  32334. or relative positions to whatever values are necessary to make the resultant position
  32335. match the position that is provided.
  32336. */
  32337. void moveToAbsolute (const Rectangle<float>& newPos, const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32338. /** Returns a string which represents this point.
  32339. This returns a comma-separated list of coordinates, in the order left, top, right, bottom. For details of
  32340. the string syntax used by the coordinates, see the RelativeCoordinate constructor notes.
  32341. The string that is returned can be passed to the RelativeRectangle constructor to recreate the rectangle.
  32342. */
  32343. const String toString() const;
  32344. /** Tells the rectangle that an object is changing its name or being deleted.
  32345. This calls RelativeCoordinate::renameAnchorIfUsed() on the rectangle's coordinates.
  32346. */
  32347. void renameAnchorIfUsed (const String& oldName, const String& newName,
  32348. const RelativeCoordinate::NamedCoordinateFinder* nameFinder);
  32349. // The actual rectangle coords...
  32350. RelativeCoordinate left, right, top, bottom;
  32351. };
  32352. /**
  32353. A path object that consists of RelativePoint coordinates rather than the normal fixed ones.
  32354. One of these paths can be converted into a Path object for drawing and manipulation, but
  32355. unlike a Path, its points can be dynamic instead of just fixed.
  32356. @see RelativePoint, RelativeCoordinate
  32357. */
  32358. class JUCE_API RelativePointPath
  32359. {
  32360. public:
  32361. RelativePointPath();
  32362. RelativePointPath (const RelativePointPath& other);
  32363. RelativePointPath (const ValueTree& drawable);
  32364. RelativePointPath (const Path& path);
  32365. ~RelativePointPath();
  32366. /** Resolves this points in this path and adds them to a normal Path object. */
  32367. void createPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32368. /** Returns true if the path contains any non-fixed points. */
  32369. bool containsAnyDynamicPoints() const;
  32370. /** Writes the path to this drawable encoding. */
  32371. void writeTo (ValueTree state, UndoManager* undoManager) const;
  32372. /** Quickly swaps the contents of this path with another. */
  32373. void swapWith (RelativePointPath& other) throw();
  32374. /** The types of element that may be contained in this path.
  32375. @see RelativePointPath::ElementBase
  32376. */
  32377. enum ElementType
  32378. {
  32379. nullElement,
  32380. startSubPathElement,
  32381. closeSubPathElement,
  32382. lineToElement,
  32383. quadraticToElement,
  32384. cubicToElement
  32385. };
  32386. /** Base class for the elements that make up a RelativePointPath.
  32387. */
  32388. class JUCE_API ElementBase
  32389. {
  32390. public:
  32391. ElementBase (ElementType type);
  32392. virtual ~ElementBase() {}
  32393. virtual const ValueTree createTree() const = 0;
  32394. virtual void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const = 0;
  32395. virtual RelativePoint* getControlPoints (int& numPoints) = 0;
  32396. const ElementType type;
  32397. private:
  32398. ElementBase (const ElementBase&);
  32399. ElementBase& operator= (const ElementBase&);
  32400. };
  32401. class JUCE_API StartSubPath : public ElementBase
  32402. {
  32403. public:
  32404. StartSubPath (const RelativePoint& pos);
  32405. ~StartSubPath() {}
  32406. const ValueTree createTree() const;
  32407. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32408. RelativePoint* getControlPoints (int& numPoints);
  32409. RelativePoint startPos;
  32410. private:
  32411. StartSubPath (const StartSubPath&);
  32412. StartSubPath& operator= (const StartSubPath&);
  32413. };
  32414. class JUCE_API CloseSubPath : public ElementBase
  32415. {
  32416. public:
  32417. CloseSubPath();
  32418. ~CloseSubPath() {}
  32419. const ValueTree createTree() const;
  32420. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32421. RelativePoint* getControlPoints (int& numPoints);
  32422. private:
  32423. CloseSubPath (const CloseSubPath&);
  32424. CloseSubPath& operator= (const CloseSubPath&);
  32425. };
  32426. class JUCE_API LineTo : public ElementBase
  32427. {
  32428. public:
  32429. LineTo (const RelativePoint& endPoint);
  32430. ~LineTo() {}
  32431. const ValueTree createTree() const;
  32432. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32433. RelativePoint* getControlPoints (int& numPoints);
  32434. RelativePoint endPoint;
  32435. private:
  32436. LineTo (const LineTo&);
  32437. LineTo& operator= (const LineTo&);
  32438. };
  32439. class JUCE_API QuadraticTo : public ElementBase
  32440. {
  32441. public:
  32442. QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint);
  32443. ~QuadraticTo() {}
  32444. const ValueTree createTree() const;
  32445. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32446. RelativePoint* getControlPoints (int& numPoints);
  32447. RelativePoint controlPoints[2];
  32448. private:
  32449. QuadraticTo (const QuadraticTo&);
  32450. QuadraticTo& operator= (const QuadraticTo&);
  32451. };
  32452. class JUCE_API CubicTo : public ElementBase
  32453. {
  32454. public:
  32455. CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint);
  32456. ~CubicTo() {}
  32457. const ValueTree createTree() const;
  32458. void addToPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32459. RelativePoint* getControlPoints (int& numPoints);
  32460. RelativePoint controlPoints[3];
  32461. private:
  32462. CubicTo (const CubicTo&);
  32463. CubicTo& operator= (const CubicTo&);
  32464. };
  32465. OwnedArray <ElementBase> elements;
  32466. bool usesNonZeroWinding;
  32467. private:
  32468. bool containsDynamicPoints;
  32469. void parse (const ValueTree& state);
  32470. RelativePointPath& operator= (const RelativePointPath&);
  32471. };
  32472. /**
  32473. A parallelogram defined by three RelativePoint positions.
  32474. @see RelativePoint, RelativeCoordinate
  32475. */
  32476. class JUCE_API RelativeParallelogram
  32477. {
  32478. public:
  32479. RelativeParallelogram();
  32480. RelativeParallelogram (const RelativePoint& topLeft, const RelativePoint& topRight, const RelativePoint& bottomLeft);
  32481. RelativeParallelogram (const String& topLeft, const String& topRight, const String& bottomLeft);
  32482. ~RelativeParallelogram();
  32483. void resolveThreePoints (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32484. void resolveFourCorners (Point<float>* points, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32485. const Rectangle<float> getBounds (RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32486. void getPath (Path& path, RelativeCoordinate::NamedCoordinateFinder* coordFinder) const;
  32487. const AffineTransform resetToPerpendicular (RelativeCoordinate::NamedCoordinateFinder* coordFinder);
  32488. bool operator== (const RelativeParallelogram& other) const throw();
  32489. bool operator!= (const RelativeParallelogram& other) const throw();
  32490. static const Point<float> getInternalCoordForPoint (const Point<float>* parallelogramCorners, Point<float> point) throw();
  32491. static const Point<float> getPointForInternalCoord (const Point<float>* parallelogramCorners, const Point<float>& internalPoint) throw();
  32492. RelativePoint topLeft, topRight, bottomLeft;
  32493. };
  32494. #endif // __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  32495. /*** End of inlined file: juce_RelativeCoordinate.h ***/
  32496. class DrawableComposite;
  32497. /**
  32498. The base class for objects which can draw themselves, e.g. polygons, images, etc.
  32499. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32500. */
  32501. class JUCE_API Drawable
  32502. {
  32503. protected:
  32504. /** The base class can't be instantiated directly.
  32505. @see DrawableComposite, DrawableImage, DrawablePath, DrawableText
  32506. */
  32507. Drawable();
  32508. public:
  32509. /** Destructor. */
  32510. virtual ~Drawable();
  32511. /** Creates a deep copy of this Drawable object.
  32512. Use this to create a new copy of this and any sub-objects in the tree.
  32513. */
  32514. virtual Drawable* createCopy() const = 0;
  32515. /** Renders this Drawable object.
  32516. @see drawWithin
  32517. */
  32518. void draw (Graphics& g, float opacity,
  32519. const AffineTransform& transform = AffineTransform::identity) const;
  32520. /** Renders the Drawable at a given offset within the Graphics context.
  32521. The co-ordinates passed-in are used to translate the object relative to its own
  32522. origin before drawing it - this is basically a quick way of saying:
  32523. @code
  32524. draw (g, AffineTransform::translation (x, y)).
  32525. @endcode
  32526. */
  32527. void drawAt (Graphics& g,
  32528. float x, float y,
  32529. float opacity) const;
  32530. /** Renders the Drawable within a rectangle, scaling it to fit neatly inside without
  32531. changing its aspect-ratio.
  32532. The object can placed arbitrarily within the rectangle based on a Justification type,
  32533. and can either be made as big as possible, or just reduced to fit.
  32534. @param g the graphics context to render onto
  32535. @param destX top-left of the target rectangle to fit it into
  32536. @param destY top-left of the target rectangle to fit it into
  32537. @param destWidth size of the target rectangle to fit the image into
  32538. @param destHeight size of the target rectangle to fit the image into
  32539. @param placement defines the alignment and rescaling to use to fit
  32540. this object within the target rectangle.
  32541. @param opacity the opacity to use, in the range 0 to 1.0
  32542. */
  32543. void drawWithin (Graphics& g,
  32544. int destX,
  32545. int destY,
  32546. int destWidth,
  32547. int destHeight,
  32548. const RectanglePlacement& placement,
  32549. float opacity) const;
  32550. /** Holds the information needed when telling a drawable to render itself.
  32551. @see Drawable::draw
  32552. */
  32553. class RenderingContext
  32554. {
  32555. public:
  32556. RenderingContext (Graphics& g, const AffineTransform& transform, float opacity) throw();
  32557. Graphics& g;
  32558. AffineTransform transform;
  32559. float opacity;
  32560. private:
  32561. RenderingContext& operator= (const RenderingContext&);
  32562. };
  32563. /** Renders this Drawable object.
  32564. @see draw
  32565. */
  32566. virtual void render (const RenderingContext& context) const = 0;
  32567. /** Returns the smallest rectangle that can contain this Drawable object.
  32568. Co-ordinates are relative to the object's own origin.
  32569. */
  32570. virtual const Rectangle<float> getBounds() const = 0;
  32571. /** Returns true if the given point is somewhere inside this Drawable.
  32572. Co-ordinates are relative to the object's own origin.
  32573. */
  32574. virtual bool hitTest (float x, float y) const = 0;
  32575. /** Returns the name given to this drawable.
  32576. @see setName
  32577. */
  32578. const String& getName() const throw() { return name; }
  32579. /** Assigns a name to this drawable. */
  32580. void setName (const String& newName) throw() { name = newName; }
  32581. /** Returns the DrawableComposite that contains this object, if there is one. */
  32582. DrawableComposite* getParent() const throw() { return parent; }
  32583. /** Tries to turn some kind of image file into a drawable.
  32584. The data could be an image that the ImageFileFormat class understands, or it
  32585. could be SVG.
  32586. */
  32587. static Drawable* createFromImageData (const void* data, size_t numBytes);
  32588. /** Tries to turn a stream containing some kind of image data into a drawable.
  32589. The data could be an image that the ImageFileFormat class understands, or it
  32590. could be SVG.
  32591. */
  32592. static Drawable* createFromImageDataStream (InputStream& dataSource);
  32593. /** Tries to turn a file containing some kind of image data into a drawable.
  32594. The data could be an image that the ImageFileFormat class understands, or it
  32595. could be SVG.
  32596. */
  32597. static Drawable* createFromImageFile (const File& file);
  32598. /** Attempts to parse an SVG (Scalable Vector Graphics) document, and to turn this
  32599. into a Drawable tree.
  32600. The object returned must be deleted by the caller. If something goes wrong
  32601. while parsing, it may return 0.
  32602. SVG is a pretty large and complex spec, and this doesn't aim to be a full
  32603. implementation, but it can return the basic vector objects.
  32604. */
  32605. static Drawable* createFromSVG (const XmlElement& svgDocument);
  32606. /** This class is used when loading Drawables that contain images, and retrieves
  32607. the image for a stored identifier.
  32608. @see Drawable::createFromValueTree
  32609. */
  32610. class JUCE_API ImageProvider
  32611. {
  32612. public:
  32613. ImageProvider() {}
  32614. virtual ~ImageProvider() {}
  32615. /** Retrieves the image associated with this identifier, which could be any
  32616. kind of string, number, filename, etc.
  32617. The image that is returned will be owned by the caller, but it may come
  32618. from the ImageCache.
  32619. */
  32620. virtual const Image getImageForIdentifier (const var& imageIdentifier) = 0;
  32621. /** Returns an identifier to be used to refer to a given image.
  32622. This is used when converting a drawable into a ValueTree, so if you're
  32623. only loading drawables, you can just return a var::null here.
  32624. */
  32625. virtual const var getIdentifierForImage (const Image& image) = 0;
  32626. };
  32627. /** Tries to create a Drawable from a previously-saved ValueTree.
  32628. The ValueTree must have been created by the createValueTree() method.
  32629. If there are any images used within the drawable, you'll need to provide a valid
  32630. ImageProvider object that can be used to retrieve these images from whatever type
  32631. of identifier is used to represent them.
  32632. */
  32633. static Drawable* createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  32634. /** Tries to refresh a Drawable from the same ValueTree that was used to create it.
  32635. @returns the damage rectangle that will need repainting due to any changes that were made.
  32636. */
  32637. virtual const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider) = 0;
  32638. /** Creates a ValueTree to represent this Drawable.
  32639. The VarTree that is returned can be turned back into a Drawable with
  32640. createFromValueTree().
  32641. If there are any images used in this drawable, you'll need to provide a valid
  32642. ImageProvider object that can be used to create storable representations of them.
  32643. */
  32644. virtual const ValueTree createValueTree (ImageProvider* imageProvider) const = 0;
  32645. /** Returns the tag ID that is used for a ValueTree that stores this type of drawable. */
  32646. virtual const Identifier getValueTreeType() const = 0;
  32647. /** Internal class used to manage ValueTrees that represent Drawables. */
  32648. class ValueTreeWrapperBase
  32649. {
  32650. public:
  32651. ValueTreeWrapperBase (const ValueTree& state);
  32652. ~ValueTreeWrapperBase();
  32653. ValueTree& getState() throw() { return state; }
  32654. const String getID() const;
  32655. void setID (const String& newID, UndoManager* undoManager);
  32656. static const Identifier idProperty;
  32657. static const FillType readFillType (const ValueTree& v, RelativePoint* gradientPoint1,
  32658. RelativePoint* gradientPoint2, RelativePoint* gradientPoint3,
  32659. RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  32660. ImageProvider* imageProvider);
  32661. static void writeFillType (ValueTree& v, const FillType& fillType,
  32662. const RelativePoint* gradientPoint1, const RelativePoint* gradientPoint2,
  32663. const RelativePoint* gradientPoint3, ImageProvider* imageProvider,
  32664. UndoManager* undoManager);
  32665. ValueTree state;
  32666. static const Identifier type, gradientPoint1, gradientPoint2, gradientPoint3,
  32667. colour, radial, colours, imageId, imageOpacity;
  32668. };
  32669. juce_UseDebuggingNewOperator
  32670. protected:
  32671. friend class DrawableComposite;
  32672. DrawableComposite* parent;
  32673. virtual void invalidatePoints() = 0;
  32674. static Drawable* createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider);
  32675. private:
  32676. String name;
  32677. Drawable (const Drawable&);
  32678. Drawable& operator= (const Drawable&);
  32679. };
  32680. #endif // __JUCE_DRAWABLE_JUCEHEADER__
  32681. /*** End of inlined file: juce_Drawable.h ***/
  32682. /**
  32683. A button that displays a Drawable.
  32684. Up to three Drawable objects can be given to this button, to represent the
  32685. 'normal', 'over' and 'down' states.
  32686. @see Button
  32687. */
  32688. class JUCE_API DrawableButton : public Button
  32689. {
  32690. public:
  32691. enum ButtonStyle
  32692. {
  32693. ImageFitted, /**< The button will just display the images, but will resize and centre them to fit inside it. */
  32694. ImageRaw, /**< The button will just display the images in their normal size and position.
  32695. This leaves it up to the caller to make sure the images are the correct size and position for the button. */
  32696. ImageAboveTextLabel, /**< Draws the button as a text label across the bottom with the image resized and scaled to fit above it. */
  32697. ImageOnButtonBackground /**< Draws the button as a standard rounded-rectangle button with the image on top. */
  32698. };
  32699. /** Creates a DrawableButton.
  32700. After creating one of these, use setImages() to specify the drawables to use.
  32701. @param buttonName the name to give the component
  32702. @param buttonStyle the layout to use
  32703. @see ButtonStyle, setButtonStyle, setImages
  32704. */
  32705. DrawableButton (const String& buttonName,
  32706. ButtonStyle buttonStyle);
  32707. /** Destructor. */
  32708. ~DrawableButton();
  32709. /** Sets up the images to draw for the various button states.
  32710. The button will keep its own internal copies of these drawables.
  32711. @param normalImage the thing to draw for the button's 'normal' state. An internal copy
  32712. will be made of the object passed-in if it is non-zero.
  32713. @param overImage the thing to draw for the button's 'over' state - if this is
  32714. zero, the button's normal image will be used when the mouse is
  32715. over it. An internal copy will be made of the object passed-in
  32716. if it is non-zero.
  32717. @param downImage the thing to draw for the button's 'down' state - if this is
  32718. zero, the 'over' image will be used instead (or the normal image
  32719. as a last resort). An internal copy will be made of the object
  32720. passed-in if it is non-zero.
  32721. @param disabledImage an image to draw when the button is disabled. If this is zero,
  32722. the normal image will be drawn with a reduced opacity instead.
  32723. An internal copy will be made of the object passed-in if it is
  32724. non-zero.
  32725. @param normalImageOn same as the normalImage, but this is used when the button's toggle
  32726. state is 'on'. If this is 0, the normal image is used instead
  32727. @param overImageOn same as the overImage, but this is used when the button's toggle
  32728. state is 'on'. If this is 0, the normalImageOn is drawn instead
  32729. @param downImageOn same as the downImage, but this is used when the button's toggle
  32730. state is 'on'. If this is 0, the overImageOn is drawn instead
  32731. @param disabledImageOn same as the disabledImage, but this is used when the button's toggle
  32732. state is 'on'. If this is 0, the normal image will be drawn instead
  32733. with a reduced opacity
  32734. */
  32735. void setImages (const Drawable* normalImage,
  32736. const Drawable* overImage = 0,
  32737. const Drawable* downImage = 0,
  32738. const Drawable* disabledImage = 0,
  32739. const Drawable* normalImageOn = 0,
  32740. const Drawable* overImageOn = 0,
  32741. const Drawable* downImageOn = 0,
  32742. const Drawable* disabledImageOn = 0);
  32743. /** Changes the button's style.
  32744. @see ButtonStyle
  32745. */
  32746. void setButtonStyle (ButtonStyle newStyle);
  32747. /** Changes the button's background colours.
  32748. The toggledOffColour is the colour to use when the button's toggle state
  32749. is off, and toggledOnColour when it's on.
  32750. For an ImageOnly or ImageAboveTextLabel style, the background colour is
  32751. used to fill the background of the component.
  32752. For an ImageOnButtonBackground style, the colour is used to draw the
  32753. button's lozenge shape and exactly how the colour's used will depend
  32754. on the LookAndFeel.
  32755. */
  32756. void setBackgroundColours (const Colour& toggledOffColour,
  32757. const Colour& toggledOnColour);
  32758. /** Returns the current background colour being used.
  32759. @see setBackgroundColour
  32760. */
  32761. const Colour& getBackgroundColour() const throw();
  32762. /** Gives the button an optional amount of space around the edge of the drawable.
  32763. This will only apply to ImageFitted or ImageRaw styles, it won't affect the
  32764. ones on a button background. If the button is too small for the given gap, a
  32765. smaller gap will be used.
  32766. By default there's a gap of about 3 pixels.
  32767. */
  32768. void setEdgeIndent (int numPixelsIndent);
  32769. /** Returns the image that the button is currently displaying. */
  32770. const Drawable* getCurrentImage() const throw();
  32771. const Drawable* getNormalImage() const throw();
  32772. const Drawable* getOverImage() const throw();
  32773. const Drawable* getDownImage() const throw();
  32774. juce_UseDebuggingNewOperator
  32775. protected:
  32776. /** @internal */
  32777. void paintButton (Graphics& g,
  32778. bool isMouseOverButton,
  32779. bool isButtonDown);
  32780. private:
  32781. ButtonStyle style;
  32782. ScopedPointer <Drawable> normalImage, overImage, downImage, disabledImage;
  32783. ScopedPointer <Drawable> normalImageOn, overImageOn, downImageOn, disabledImageOn;
  32784. Colour backgroundOff, backgroundOn;
  32785. int edgeIndent;
  32786. void deleteImages();
  32787. DrawableButton (const DrawableButton&);
  32788. DrawableButton& operator= (const DrawableButton&);
  32789. };
  32790. #endif // __JUCE_DRAWABLEBUTTON_JUCEHEADER__
  32791. /*** End of inlined file: juce_DrawableButton.h ***/
  32792. #endif
  32793. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32794. /*** Start of inlined file: juce_HyperlinkButton.h ***/
  32795. #ifndef __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32796. #define __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32797. /**
  32798. A button showing an underlined weblink, that will launch the link
  32799. when it's clicked.
  32800. @see Button
  32801. */
  32802. class JUCE_API HyperlinkButton : public Button
  32803. {
  32804. public:
  32805. /** Creates a HyperlinkButton.
  32806. @param linkText the text that will be displayed in the button - this is
  32807. also set as the Component's name, but the text can be
  32808. changed later with the Button::getButtonText() method
  32809. @param linkURL the URL to launch when the user clicks the button
  32810. */
  32811. HyperlinkButton (const String& linkText,
  32812. const URL& linkURL);
  32813. /** Destructor. */
  32814. ~HyperlinkButton();
  32815. /** Changes the font to use for the text.
  32816. If resizeToMatchComponentHeight is true, the font's height will be adjusted
  32817. to match the size of the component.
  32818. */
  32819. void setFont (const Font& newFont,
  32820. bool resizeToMatchComponentHeight,
  32821. const Justification& justificationType = Justification::horizontallyCentred);
  32822. /** A set of colour IDs to use to change the colour of various aspects of the link.
  32823. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  32824. methods.
  32825. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  32826. */
  32827. enum ColourIds
  32828. {
  32829. textColourId = 0x1001f00, /**< The colour to use for the URL text. */
  32830. };
  32831. /** Changes the URL that the button will trigger. */
  32832. void setURL (const URL& newURL) throw();
  32833. /** Returns the URL that the button will trigger. */
  32834. const URL& getURL() const throw() { return url; }
  32835. /** Resizes the button horizontally to fit snugly around the text.
  32836. This won't affect the button's height.
  32837. */
  32838. void changeWidthToFitText();
  32839. juce_UseDebuggingNewOperator
  32840. protected:
  32841. /** @internal */
  32842. void clicked();
  32843. /** @internal */
  32844. void colourChanged();
  32845. /** @internal */
  32846. void paintButton (Graphics& g,
  32847. bool isMouseOverButton,
  32848. bool isButtonDown);
  32849. private:
  32850. URL url;
  32851. Font font;
  32852. bool resizeFont;
  32853. Justification justification;
  32854. const Font getFontToUse() const;
  32855. HyperlinkButton (const HyperlinkButton&);
  32856. HyperlinkButton& operator= (const HyperlinkButton&);
  32857. };
  32858. #endif // __JUCE_HYPERLINKBUTTON_JUCEHEADER__
  32859. /*** End of inlined file: juce_HyperlinkButton.h ***/
  32860. #endif
  32861. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32862. /*** Start of inlined file: juce_ImageButton.h ***/
  32863. #ifndef __JUCE_IMAGEBUTTON_JUCEHEADER__
  32864. #define __JUCE_IMAGEBUTTON_JUCEHEADER__
  32865. /**
  32866. As the title suggests, this is a button containing an image.
  32867. The colour and transparency of the image can be set to vary when the
  32868. button state changes.
  32869. @see Button, ShapeButton, TextButton
  32870. */
  32871. class JUCE_API ImageButton : public Button
  32872. {
  32873. public:
  32874. /** Creates an ImageButton.
  32875. Use setImage() to specify the image to use. The colours and opacities that
  32876. are specified here can be changed later using setDrawingOptions().
  32877. @param name the name to give the component
  32878. */
  32879. explicit ImageButton (const String& name);
  32880. /** Destructor. */
  32881. ~ImageButton();
  32882. /** Sets up the images to draw in various states.
  32883. @param resizeButtonNowToFitThisImage if true, the button will be immediately
  32884. resized to the same dimensions as the normal image
  32885. @param rescaleImagesWhenButtonSizeChanges if true, the image will be rescaled to fit the
  32886. button when the button's size changes
  32887. @param preserveImageProportions if true then any rescaling of the image to fit
  32888. the button will keep the image's x and y proportions
  32889. correct - i.e. it won't distort its shape, although
  32890. this might create gaps around the edges
  32891. @param normalImage the image to use when the button is in its normal state.
  32892. button no longer needs it.
  32893. @param imageOpacityWhenNormal the opacity to use when drawing the normal image.
  32894. @param overlayColourWhenNormal an overlay colour to use to fill the alpha channel of the
  32895. normal image - if this colour is transparent, no overlay
  32896. will be drawn. The overlay will be drawn over the top of the
  32897. image, so you can basically add a solid or semi-transparent
  32898. colour to the image to brighten or darken it
  32899. @param overImage the image to use when the mouse is over the button. If
  32900. you want to use the same image as was set in the normalImage
  32901. parameter, this value can be a null image.
  32902. @param imageOpacityWhenOver the opacity to use when drawing the image when the mouse
  32903. is over the button
  32904. @param overlayColourWhenOver an overlay colour to use to fill the alpha channel of the
  32905. image when the mouse is over - if this colour is transparent,
  32906. no overlay will be drawn
  32907. @param downImage an image to use when the button is pressed down. If set
  32908. to a null image, the 'over' image will be drawn instead (or the
  32909. normal image if there isn't an 'over' image either).
  32910. @param imageOpacityWhenDown the opacity to use when drawing the image when the button
  32911. is pressed
  32912. @param overlayColourWhenDown an overlay colour to use to fill the alpha channel of the
  32913. image when the button is pressed down - if this colour is
  32914. transparent, no overlay will be drawn
  32915. @param hitTestAlphaThreshold if set to zero, the mouse is considered to be over the button
  32916. whenever it's inside the button's bounding rectangle. If
  32917. set to values higher than 0, the mouse will only be
  32918. considered to be over the image when the value of the
  32919. image's alpha channel at that position is greater than
  32920. this level.
  32921. */
  32922. void setImages (bool resizeButtonNowToFitThisImage,
  32923. bool rescaleImagesWhenButtonSizeChanges,
  32924. bool preserveImageProportions,
  32925. const Image& normalImage,
  32926. float imageOpacityWhenNormal,
  32927. const Colour& overlayColourWhenNormal,
  32928. const Image& overImage,
  32929. float imageOpacityWhenOver,
  32930. const Colour& overlayColourWhenOver,
  32931. const Image& downImage,
  32932. float imageOpacityWhenDown,
  32933. const Colour& overlayColourWhenDown,
  32934. float hitTestAlphaThreshold = 0.0f);
  32935. /** Returns the currently set 'normal' image. */
  32936. const Image getNormalImage() const;
  32937. /** Returns the image that's drawn when the mouse is over the button.
  32938. If a valid 'over' image has been set, this will return it; otherwise it'll
  32939. just return the normal image.
  32940. */
  32941. const Image getOverImage() const;
  32942. /** Returns the image that's drawn when the button is held down.
  32943. If a valid 'down' image has been set, this will return it; otherwise it'll
  32944. return the 'over' image or normal image, depending on what's available.
  32945. */
  32946. const Image getDownImage() const;
  32947. juce_UseDebuggingNewOperator
  32948. protected:
  32949. /** @internal */
  32950. bool hitTest (int x, int y);
  32951. /** @internal */
  32952. void paintButton (Graphics& g,
  32953. bool isMouseOverButton,
  32954. bool isButtonDown);
  32955. private:
  32956. bool scaleImageToFit, preserveProportions;
  32957. unsigned char alphaThreshold;
  32958. int imageX, imageY, imageW, imageH;
  32959. Image normalImage, overImage, downImage;
  32960. float normalOpacity, overOpacity, downOpacity;
  32961. Colour normalOverlay, overOverlay, downOverlay;
  32962. const Image getCurrentImage() const;
  32963. ImageButton (const ImageButton&);
  32964. ImageButton& operator= (const ImageButton&);
  32965. };
  32966. #endif // __JUCE_IMAGEBUTTON_JUCEHEADER__
  32967. /*** End of inlined file: juce_ImageButton.h ***/
  32968. #endif
  32969. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32970. /*** Start of inlined file: juce_ShapeButton.h ***/
  32971. #ifndef __JUCE_SHAPEBUTTON_JUCEHEADER__
  32972. #define __JUCE_SHAPEBUTTON_JUCEHEADER__
  32973. /**
  32974. A button that contains a filled shape.
  32975. @see Button, ImageButton, TextButton, ArrowButton
  32976. */
  32977. class JUCE_API ShapeButton : public Button
  32978. {
  32979. public:
  32980. /** Creates a ShapeButton.
  32981. @param name a name to give the component - see Component::setName()
  32982. @param normalColour the colour to fill the shape with when the mouse isn't over
  32983. @param overColour the colour to use when the mouse is over the shape
  32984. @param downColour the colour to use when the button is in the pressed-down state
  32985. */
  32986. ShapeButton (const String& name,
  32987. const Colour& normalColour,
  32988. const Colour& overColour,
  32989. const Colour& downColour);
  32990. /** Destructor. */
  32991. ~ShapeButton();
  32992. /** Sets the shape to use.
  32993. @param newShape the shape to use
  32994. @param resizeNowToFitThisShape if true, the button will be resized to fit the shape's bounds
  32995. @param maintainShapeProportions if true, the shape's proportions will be kept fixed when
  32996. the button is resized
  32997. @param hasDropShadow if true, the button will be given a drop-shadow effect
  32998. */
  32999. void setShape (const Path& newShape,
  33000. bool resizeNowToFitThisShape,
  33001. bool maintainShapeProportions,
  33002. bool hasDropShadow);
  33003. /** Set the colours to use for drawing the shape.
  33004. @param normalColour the colour to fill the shape with when the mouse isn't over
  33005. @param overColour the colour to use when the mouse is over the shape
  33006. @param downColour the colour to use when the button is in the pressed-down state
  33007. */
  33008. void setColours (const Colour& normalColour,
  33009. const Colour& overColour,
  33010. const Colour& downColour);
  33011. /** Sets up an outline to draw around the shape.
  33012. @param outlineColour the colour to use
  33013. @param outlineStrokeWidth the thickness of line to draw
  33014. */
  33015. void setOutline (const Colour& outlineColour,
  33016. float outlineStrokeWidth);
  33017. juce_UseDebuggingNewOperator
  33018. protected:
  33019. /** @internal */
  33020. void paintButton (Graphics& g,
  33021. bool isMouseOverButton,
  33022. bool isButtonDown);
  33023. private:
  33024. Colour normalColour, overColour, downColour, outlineColour;
  33025. DropShadowEffect shadow;
  33026. Path shape;
  33027. bool maintainShapeProportions;
  33028. float outlineWidth;
  33029. ShapeButton (const ShapeButton&);
  33030. ShapeButton& operator= (const ShapeButton&);
  33031. };
  33032. #endif // __JUCE_SHAPEBUTTON_JUCEHEADER__
  33033. /*** End of inlined file: juce_ShapeButton.h ***/
  33034. #endif
  33035. #ifndef __JUCE_TEXTBUTTON_JUCEHEADER__
  33036. #endif
  33037. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33038. /*** Start of inlined file: juce_ToggleButton.h ***/
  33039. #ifndef __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33040. #define __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33041. /**
  33042. A button that can be toggled on/off.
  33043. All buttons can be toggle buttons, but this lets you create one of the
  33044. standard ones which has a tick-box and a text label next to it.
  33045. @see Button, DrawableButton, TextButton
  33046. */
  33047. class JUCE_API ToggleButton : public Button
  33048. {
  33049. public:
  33050. /** Creates a ToggleButton.
  33051. @param buttonText the text to put in the button (the component's name is also
  33052. initially set to this string, but these can be changed later
  33053. using the setName() and setButtonText() methods)
  33054. */
  33055. explicit ToggleButton (const String& buttonText = String::empty);
  33056. /** Destructor. */
  33057. ~ToggleButton();
  33058. /** Resizes the button to fit neatly around its current text.
  33059. The button's height won't be affected, only its width.
  33060. */
  33061. void changeWidthToFitText();
  33062. /** A set of colour IDs to use to change the colour of various aspects of the button.
  33063. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33064. methods.
  33065. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33066. */
  33067. enum ColourIds
  33068. {
  33069. textColourId = 0x1006501 /**< The colour to use for the button's text. */
  33070. };
  33071. juce_UseDebuggingNewOperator
  33072. protected:
  33073. /** @internal */
  33074. void paintButton (Graphics& g,
  33075. bool isMouseOverButton,
  33076. bool isButtonDown);
  33077. /** @internal */
  33078. void colourChanged();
  33079. private:
  33080. ToggleButton (const ToggleButton&);
  33081. ToggleButton& operator= (const ToggleButton&);
  33082. };
  33083. #endif // __JUCE_TOGGLEBUTTON_JUCEHEADER__
  33084. /*** End of inlined file: juce_ToggleButton.h ***/
  33085. #endif
  33086. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33087. /*** Start of inlined file: juce_ToolbarButton.h ***/
  33088. #ifndef __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33089. #define __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33090. /*** Start of inlined file: juce_ToolbarItemComponent.h ***/
  33091. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33092. #define __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33093. /*** Start of inlined file: juce_Toolbar.h ***/
  33094. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  33095. #define __JUCE_TOOLBAR_JUCEHEADER__
  33096. /*** Start of inlined file: juce_DragAndDropContainer.h ***/
  33097. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33098. #define __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33099. /*** Start of inlined file: juce_DragAndDropTarget.h ***/
  33100. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33101. #define __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33102. /**
  33103. Components derived from this class can have things dropped onto them by a DragAndDropContainer.
  33104. To create a component that can receive things drag-and-dropped by a DragAndDropContainer,
  33105. derive your component from this class, and make sure that it is somewhere inside a
  33106. DragAndDropContainer component.
  33107. Note: If all that you need to do is to respond to files being drag-and-dropped from
  33108. the operating system onto your component, you don't need any of these classes: instead
  33109. see the FileDragAndDropTarget class.
  33110. @see DragAndDropContainer, FileDragAndDropTarget
  33111. */
  33112. class JUCE_API DragAndDropTarget
  33113. {
  33114. public:
  33115. /** Destructor. */
  33116. virtual ~DragAndDropTarget() {}
  33117. /** Callback to check whether this target is interested in the type of object being
  33118. dragged.
  33119. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33120. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33121. @returns true if this component wants to receive the other callbacks regarging this
  33122. type of object; if it returns false, no other callbacks will be made.
  33123. */
  33124. virtual bool isInterestedInDragSource (const String& sourceDescription,
  33125. Component* sourceComponent) = 0;
  33126. /** Callback to indicate that something is being dragged over this component.
  33127. This gets called when the user moves the mouse into this component while dragging
  33128. something.
  33129. Use this callback as a trigger to make your component repaint itself to give the
  33130. user feedback about whether the item can be dropped here or not.
  33131. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33132. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33133. @param x the mouse x position, relative to this component
  33134. @param y the mouse y position, relative to this component
  33135. @see itemDragExit
  33136. */
  33137. virtual void itemDragEnter (const String& sourceDescription,
  33138. Component* sourceComponent,
  33139. int x, int y);
  33140. /** Callback to indicate that the user is dragging something over this component.
  33141. This gets called when the user moves the mouse over this component while dragging
  33142. something. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  33143. this lets you know what happens in-between.
  33144. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33145. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33146. @param x the mouse x position, relative to this component
  33147. @param y the mouse y position, relative to this component
  33148. */
  33149. virtual void itemDragMove (const String& sourceDescription,
  33150. Component* sourceComponent,
  33151. int x, int y);
  33152. /** Callback to indicate that something has been dragged off the edge of this component.
  33153. This gets called when the user moves the mouse out of this component while dragging
  33154. something.
  33155. If you've used itemDragEnter() to repaint your component and give feedback, use this
  33156. as a signal to repaint it in its normal state.
  33157. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33158. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33159. @see itemDragEnter
  33160. */
  33161. virtual void itemDragExit (const String& sourceDescription,
  33162. Component* sourceComponent);
  33163. /** Callback to indicate that the user has dropped something onto this component.
  33164. When the user drops an item this get called, and you can use the description to
  33165. work out whether your object wants to deal with it or not.
  33166. Note that after this is called, the itemDragExit method may not be called, so you should
  33167. clean up in here if there's anything you need to do when the drag finishes.
  33168. @param sourceDescription the description string passed into DragAndDropContainer::startDragging()
  33169. @param sourceComponent the component that was passed into DragAndDropContainer::startDragging()
  33170. @param x the mouse x position, relative to this component
  33171. @param y the mouse y position, relative to this component
  33172. */
  33173. virtual void itemDropped (const String& sourceDescription,
  33174. Component* sourceComponent,
  33175. int x, int y) = 0;
  33176. /** Overriding this allows the target to tell the drag container whether to
  33177. draw the drag image while the cursor is over it.
  33178. By default it returns true, but if you return false, then the normal drag
  33179. image will not be shown when the cursor is over this target.
  33180. */
  33181. virtual bool shouldDrawDragImageWhenOver();
  33182. };
  33183. #endif // __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  33184. /*** End of inlined file: juce_DragAndDropTarget.h ***/
  33185. /**
  33186. Enables drag-and-drop behaviour for a component and all its sub-components.
  33187. For a component to be able to make or receive drag-and-drop events, one of its parent
  33188. components must derive from this class. It's probably best for the top-level
  33189. component to implement it.
  33190. Then to start a drag operation, any sub-component can just call the startDragging()
  33191. method, and this object will take over, tracking the mouse and sending appropriate
  33192. callbacks to any child components derived from DragAndDropTarget which the mouse
  33193. moves over.
  33194. Note: If all that you need to do is to respond to files being drag-and-dropped from
  33195. the operating system onto your component, you don't need any of these classes: you can do this
  33196. simply by overriding Component::filesDropped().
  33197. @see DragAndDropTarget
  33198. */
  33199. class JUCE_API DragAndDropContainer
  33200. {
  33201. public:
  33202. /** Creates a DragAndDropContainer.
  33203. The object that derives from this class must also be a Component.
  33204. */
  33205. DragAndDropContainer();
  33206. /** Destructor. */
  33207. virtual ~DragAndDropContainer();
  33208. /** Begins a drag-and-drop operation.
  33209. This starts a drag-and-drop operation - call it when the user drags the
  33210. mouse in your drag-source component, and this object will track mouse
  33211. movements until the user lets go of the mouse button, and will send
  33212. appropriate messages to DragAndDropTarget objects that the mouse moves
  33213. over.
  33214. findParentDragContainerFor() is a handy method to call to find the
  33215. drag container to use for a component.
  33216. @param sourceDescription a string to use as the description of the thing being
  33217. dragged - this will be passed to the objects that might be
  33218. dropped-onto so they can decide if they want to handle it or
  33219. not
  33220. @param sourceComponent the component that is being dragged
  33221. @param dragImage the image to drag around underneath the mouse. If this is a null image,
  33222. a snapshot of the sourceComponent will be used instead.
  33223. @param allowDraggingToOtherJuceWindows if true, the dragged component will appear as a desktop
  33224. window, and can be dragged to DragAndDropTargets that are the
  33225. children of components other than this one.
  33226. @param imageOffsetFromMouse if an image has been passed-in, this specifies the offset
  33227. at which the image should be drawn from the mouse. If it isn't
  33228. specified, then the image will be centred around the mouse. If
  33229. an image hasn't been passed-in, this will be ignored.
  33230. */
  33231. void startDragging (const String& sourceDescription,
  33232. Component* sourceComponent,
  33233. const Image& dragImage = Image(),
  33234. bool allowDraggingToOtherJuceWindows = false,
  33235. const Point<int>* imageOffsetFromMouse = 0);
  33236. /** Returns true if something is currently being dragged. */
  33237. bool isDragAndDropActive() const;
  33238. /** Returns the description of the thing that's currently being dragged.
  33239. If nothing's being dragged, this will return an empty string, otherwise it's the
  33240. string that was passed into startDragging().
  33241. @see startDragging
  33242. */
  33243. const String getCurrentDragDescription() const;
  33244. /** Utility to find the DragAndDropContainer for a given Component.
  33245. This will search up this component's parent hierarchy looking for the first
  33246. parent component which is a DragAndDropContainer.
  33247. It's useful when a component wants to call startDragging but doesn't know
  33248. the DragAndDropContainer it should to use.
  33249. Obviously this may return 0 if it doesn't find a suitable component.
  33250. */
  33251. static DragAndDropContainer* findParentDragContainerFor (Component* childComponent);
  33252. /** This performs a synchronous drag-and-drop of a set of files to some external
  33253. application.
  33254. You can call this function in response to a mouseDrag callback, and it will
  33255. block, running its own internal message loop and tracking the mouse, while it
  33256. uses a native operating system drag-and-drop operation to move or copy some
  33257. files to another application.
  33258. @param files a list of filenames to drag
  33259. @param canMoveFiles if true, the app that receives the files is allowed to move the files to a new location
  33260. (if this is appropriate). If false, the receiver is expected to make a copy of them.
  33261. @returns true if the files were successfully dropped somewhere, or false if it
  33262. was interrupted
  33263. @see performExternalDragDropOfText
  33264. */
  33265. static bool performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles);
  33266. /** This performs a synchronous drag-and-drop of a block of text to some external
  33267. application.
  33268. You can call this function in response to a mouseDrag callback, and it will
  33269. block, running its own internal message loop and tracking the mouse, while it
  33270. uses a native operating system drag-and-drop operation to move or copy some
  33271. text to another application.
  33272. @param text the text to copy
  33273. @returns true if the text was successfully dropped somewhere, or false if it
  33274. was interrupted
  33275. @see performExternalDragDropOfFiles
  33276. */
  33277. static bool performExternalDragDropOfText (const String& text);
  33278. juce_UseDebuggingNewOperator
  33279. protected:
  33280. /** Override this if you want to be able to perform an external drag a set of files
  33281. when the user drags outside of this container component.
  33282. This method will be called when a drag operation moves outside the Juce-based window,
  33283. and if you want it to then perform a file drag-and-drop, add the filenames you want
  33284. to the array passed in, and return true.
  33285. @param dragSourceDescription the description passed into the startDrag() call when the drag began
  33286. @param dragSourceComponent the component passed into the startDrag() call when the drag began
  33287. @param files on return, the filenames you want to drag
  33288. @param canMoveFiles on return, true if it's ok for the receiver to move the files; false if
  33289. it must make a copy of them (see the performExternalDragDropOfFiles()
  33290. method)
  33291. @see performExternalDragDropOfFiles
  33292. */
  33293. virtual bool shouldDropFilesWhenDraggedExternally (const String& dragSourceDescription,
  33294. Component* dragSourceComponent,
  33295. StringArray& files,
  33296. bool& canMoveFiles);
  33297. private:
  33298. friend class DragImageComponent;
  33299. ScopedPointer <Component> dragImageComponent;
  33300. String currentDragDesc;
  33301. };
  33302. #endif // __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  33303. /*** End of inlined file: juce_DragAndDropContainer.h ***/
  33304. /*** Start of inlined file: juce_ComponentAnimator.h ***/
  33305. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33306. #define __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33307. /**
  33308. Animates a set of components, moving it to a new position.
  33309. To use this, create a ComponentAnimator, and use its animateComponent() method
  33310. to tell it to move components to destination positions. Any number of
  33311. components can be animated by one ComponentAnimator object (if you've got a
  33312. lot of components to move, it's much more efficient to share a single animator
  33313. than to have many animators running at once).
  33314. You'll need to make sure the animator object isn't deleted before it finishes
  33315. moving the components.
  33316. The class is a ChangeBroadcaster and sends a notification when any components
  33317. start or finish being animated.
  33318. */
  33319. class JUCE_API ComponentAnimator : public ChangeBroadcaster,
  33320. private Timer
  33321. {
  33322. public:
  33323. /** Creates a ComponentAnimator. */
  33324. ComponentAnimator();
  33325. /** Destructor. */
  33326. ~ComponentAnimator();
  33327. /** Starts a component moving from its current position to a specified position.
  33328. If the component is already in the middle of an animation, that will be abandoned,
  33329. and a new animation will begin, moving the component from its current location.
  33330. The start and end speed parameters let you apply some acceleration to the component's
  33331. movement.
  33332. @param component the component to move
  33333. @param finalPosition the destination position and size to move it to
  33334. @param millisecondsToSpendMoving how long, in milliseconds, it should take
  33335. to arrive at its destination
  33336. @param startSpeed a value to indicate the relative start speed of the
  33337. animation. If this is 0, the component will start
  33338. by accelerating from rest; higher values mean that it
  33339. will have an initial speed greater than zero. If the
  33340. value if greater than 1, it will decelerate towards the
  33341. middle of its journey. To move the component at a constant
  33342. rate for its entire animation, set both the start and
  33343. end speeds to 1.0
  33344. @param endSpeed a relative speed at which the component should be moving
  33345. when the animation finishes. If this is 0, the component
  33346. will decelerate to a standstill at its final position; higher
  33347. values mean the component will still be moving when it stops.
  33348. To move the component at a constant rate for its entire
  33349. animation, set both the start and end speeds to 1.0
  33350. */
  33351. void animateComponent (Component* component,
  33352. const Rectangle<int>& finalPosition,
  33353. int millisecondsToSpendMoving,
  33354. double startSpeed = 1.0,
  33355. double endSpeed = 1.0);
  33356. /** Stops a component if it's currently being animated.
  33357. If moveComponentToItsFinalPosition is true, then the component will
  33358. be immediately moved to its destination position and size. If false, it will be
  33359. left in whatever location it currently occupies.
  33360. */
  33361. void cancelAnimation (Component* component,
  33362. bool moveComponentToItsFinalPosition);
  33363. /** Clears all of the active animations.
  33364. If moveComponentsToTheirFinalPositions is true, all the components will
  33365. be immediately set to their final positions. If false, they will be
  33366. left in whatever locations they currently occupy.
  33367. */
  33368. void cancelAllAnimations (bool moveComponentsToTheirFinalPositions);
  33369. /** Returns the destination position for a component.
  33370. If the component is being animated, this will return the target position that
  33371. was specified when animateComponent() was called.
  33372. If the specified component isn't currently being animated, this method will just
  33373. return its current position.
  33374. */
  33375. const Rectangle<int> getComponentDestination (Component* component);
  33376. /** Returns true if the specified component is currently being animated.
  33377. */
  33378. bool isAnimating (Component* component) const;
  33379. juce_UseDebuggingNewOperator
  33380. private:
  33381. class AnimationTask;
  33382. Array <AnimationTask*> tasks;
  33383. uint32 lastTime;
  33384. AnimationTask* findTaskFor (Component* component) const;
  33385. void timerCallback();
  33386. };
  33387. #endif // __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  33388. /*** End of inlined file: juce_ComponentAnimator.h ***/
  33389. class ToolbarItemComponent;
  33390. class ToolbarItemFactory;
  33391. class MissingItemsComponent;
  33392. /**
  33393. A toolbar component.
  33394. A toolbar contains a horizontal or vertical strip of ToolbarItemComponents,
  33395. and looks after their order and layout.
  33396. Items (icon buttons or other custom components) are added to a toolbar using a
  33397. ToolbarItemFactory - each type of item is given a unique ID number, and a
  33398. toolbar might contain more than one instance of a particular item type.
  33399. Toolbars can be interactively customised, allowing the user to drag the items
  33400. around, and to drag items onto or off the toolbar, using the ToolbarItemPalette
  33401. component as a source of new items.
  33402. @see ToolbarItemFactory, ToolbarItemComponent, ToolbarItemPalette
  33403. */
  33404. class JUCE_API Toolbar : public Component,
  33405. public DragAndDropContainer,
  33406. public DragAndDropTarget,
  33407. private ButtonListener
  33408. {
  33409. public:
  33410. /** Creates an empty toolbar component.
  33411. To add some icons or other components to your toolbar, you'll need to
  33412. create a ToolbarItemFactory class that can create a suitable set of
  33413. ToolbarItemComponents.
  33414. @see ToolbarItemFactory, ToolbarItemComponents
  33415. */
  33416. Toolbar();
  33417. /** Destructor.
  33418. Any items on the bar will be deleted when the toolbar is deleted.
  33419. */
  33420. ~Toolbar();
  33421. /** Changes the bar's orientation.
  33422. @see isVertical
  33423. */
  33424. void setVertical (bool shouldBeVertical);
  33425. /** Returns true if the bar is set to be vertical, or false if it's horizontal.
  33426. You can change the bar's orientation with setVertical().
  33427. */
  33428. bool isVertical() const throw() { return vertical; }
  33429. /** Returns the depth of the bar.
  33430. If the bar is horizontal, this will return its height; if it's vertical, it
  33431. will return its width.
  33432. @see getLength
  33433. */
  33434. int getThickness() const throw();
  33435. /** Returns the length of the bar.
  33436. If the bar is horizontal, this will return its width; if it's vertical, it
  33437. will return its height.
  33438. @see getThickness
  33439. */
  33440. int getLength() const throw();
  33441. /** Deletes all items from the bar.
  33442. */
  33443. void clear();
  33444. /** Adds an item to the toolbar.
  33445. The factory's ToolbarItemFactory::createItem() will be called by this method
  33446. to create the component that will actually be added to the bar.
  33447. The new item will be inserted at the specified index (if the index is -1, it
  33448. will be added to the right-hand or bottom end of the bar).
  33449. Once added, the component will be automatically deleted by this object when it
  33450. is no longer needed.
  33451. @see ToolbarItemFactory
  33452. */
  33453. void addItem (ToolbarItemFactory& factory,
  33454. int itemId,
  33455. int insertIndex = -1);
  33456. /** Deletes one of the items from the bar.
  33457. */
  33458. void removeToolbarItem (int itemIndex);
  33459. /** Returns the number of items currently on the toolbar.
  33460. @see getItemId, getItemComponent
  33461. */
  33462. int getNumItems() const throw();
  33463. /** Returns the ID of the item with the given index.
  33464. If the index is less than zero or greater than the number of items,
  33465. this will return 0.
  33466. @see getNumItems
  33467. */
  33468. int getItemId (int itemIndex) const throw();
  33469. /** Returns the component being used for the item with the given index.
  33470. If the index is less than zero or greater than the number of items,
  33471. this will return 0.
  33472. @see getNumItems
  33473. */
  33474. ToolbarItemComponent* getItemComponent (int itemIndex) const throw();
  33475. /** Clears this toolbar and adds to it the default set of items that the specified
  33476. factory creates.
  33477. @see ToolbarItemFactory::getDefaultItemSet
  33478. */
  33479. void addDefaultItems (ToolbarItemFactory& factoryToUse);
  33480. /** Options for the way items should be displayed.
  33481. @see setStyle, getStyle
  33482. */
  33483. enum ToolbarItemStyle
  33484. {
  33485. iconsOnly, /**< Means that the toolbar should just contain icons. */
  33486. iconsWithText, /**< Means that the toolbar should have text labels under each icon. */
  33487. textOnly /**< Means that the toolbar only display text labels for each item. */
  33488. };
  33489. /** Returns the toolbar's current style.
  33490. @see ToolbarItemStyle, setStyle
  33491. */
  33492. ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33493. /** Changes the toolbar's current style.
  33494. @see ToolbarItemStyle, getStyle, ToolbarItemComponent::setStyle
  33495. */
  33496. void setStyle (const ToolbarItemStyle& newStyle);
  33497. /** Flags used by the showCustomisationDialog() method. */
  33498. enum CustomisationFlags
  33499. {
  33500. allowIconsOnlyChoice = 1, /**< If this flag is specified, the customisation dialog can
  33501. show the "icons only" option on its choice of toolbar styles. */
  33502. allowIconsWithTextChoice = 2, /**< If this flag is specified, the customisation dialog can
  33503. show the "icons with text" option on its choice of toolbar styles. */
  33504. allowTextOnlyChoice = 4, /**< If this flag is specified, the customisation dialog can
  33505. show the "text only" option on its choice of toolbar styles. */
  33506. showResetToDefaultsButton = 8, /**< If this flag is specified, the customisation dialog can
  33507. show a button to reset the toolbar to its default set of items. */
  33508. allCustomisationOptionsEnabled = (allowIconsOnlyChoice | allowIconsWithTextChoice | allowTextOnlyChoice | showResetToDefaultsButton)
  33509. };
  33510. /** Pops up a modal dialog box that allows this toolbar to be customised by the user.
  33511. The dialog contains a ToolbarItemPalette and various controls for editing other
  33512. aspects of the toolbar. This method will block and run the dialog box modally,
  33513. returning when the user closes it.
  33514. The factory is used to determine the set of items that will be shown on the
  33515. palette.
  33516. The optionFlags parameter is a bitwise-or of values from the CustomisationFlags
  33517. enum.
  33518. @see ToolbarItemPalette
  33519. */
  33520. void showCustomisationDialog (ToolbarItemFactory& factory,
  33521. int optionFlags = allCustomisationOptionsEnabled);
  33522. /** Turns on or off the toolbar's editing mode, in which its items can be
  33523. rearranged by the user.
  33524. (In most cases it's easier just to use showCustomisationDialog() instead of
  33525. trying to enable editing directly).
  33526. @see ToolbarItemPalette
  33527. */
  33528. void setEditingActive (bool editingEnabled);
  33529. /** A set of colour IDs to use to change the colour of various aspects of the toolbar.
  33530. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  33531. methods.
  33532. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  33533. */
  33534. enum ColourIds
  33535. {
  33536. backgroundColourId = 0x1003200, /**< A colour to use to fill the toolbar's background. For
  33537. more control over this, override LookAndFeel::paintToolbarBackground(). */
  33538. separatorColourId = 0x1003210, /**< A colour to use to draw the separator lines. */
  33539. buttonMouseOverBackgroundColourId = 0x1003220, /**< A colour used to paint the background of buttons when the mouse is
  33540. over them. */
  33541. buttonMouseDownBackgroundColourId = 0x1003230, /**< A colour used to paint the background of buttons when the mouse is
  33542. held down on them. */
  33543. labelTextColourId = 0x1003240, /**< A colour to use for drawing the text under buttons
  33544. when the style is set to iconsWithText or textOnly. */
  33545. editingModeOutlineColourId = 0x1003250 /**< A colour to use for an outline around buttons when
  33546. the customisation dialog is active and the mouse moves over them. */
  33547. };
  33548. /** Returns a string that represents the toolbar's current set of items.
  33549. This lets you later restore the same item layout using restoreFromString().
  33550. @see restoreFromString
  33551. */
  33552. const String toString() const;
  33553. /** Restores a set of items that was previously stored in a string by the toString()
  33554. method.
  33555. The factory object is used to create any item components that are needed.
  33556. @see toString
  33557. */
  33558. bool restoreFromString (ToolbarItemFactory& factoryToUse,
  33559. const String& savedVersion);
  33560. /** @internal */
  33561. void paint (Graphics& g);
  33562. /** @internal */
  33563. void resized();
  33564. /** @internal */
  33565. void buttonClicked (Button*);
  33566. /** @internal */
  33567. void mouseDown (const MouseEvent&);
  33568. /** @internal */
  33569. bool isInterestedInDragSource (const String&, Component*);
  33570. /** @internal */
  33571. void itemDragMove (const String&, Component*, int, int);
  33572. /** @internal */
  33573. void itemDragExit (const String&, Component*);
  33574. /** @internal */
  33575. void itemDropped (const String&, Component*, int, int);
  33576. /** @internal */
  33577. void updateAllItemPositions (const bool animate);
  33578. /** @internal */
  33579. static ToolbarItemComponent* createItem (ToolbarItemFactory&, const int itemId);
  33580. juce_UseDebuggingNewOperator
  33581. private:
  33582. Button* missingItemsButton;
  33583. bool vertical, isEditingActive;
  33584. ToolbarItemStyle toolbarStyle;
  33585. ComponentAnimator animator;
  33586. friend class MissingItemsComponent;
  33587. Array <ToolbarItemComponent*> items;
  33588. friend class ItemDragAndDropOverlayComponent;
  33589. static const char* const toolbarDragDescriptor;
  33590. void addItemInternal (ToolbarItemFactory& factory, const int itemId, const int insertIndex);
  33591. ToolbarItemComponent* getNextActiveComponent (int index, const int delta) const;
  33592. Toolbar (const Toolbar&);
  33593. Toolbar& operator= (const Toolbar&);
  33594. };
  33595. #endif // __JUCE_TOOLBAR_JUCEHEADER__
  33596. /*** End of inlined file: juce_Toolbar.h ***/
  33597. class ItemDragAndDropOverlayComponent;
  33598. /**
  33599. A component that can be used as one of the items in a Toolbar.
  33600. Each of the items on a toolbar must be a component derived from ToolbarItemComponent,
  33601. and these objects are always created by a ToolbarItemFactory - see the ToolbarItemFactory
  33602. class for further info about creating them.
  33603. The ToolbarItemComponent class is actually a button, but can be used to hold non-button
  33604. components too. To do this, set the value of isBeingUsedAsAButton to false when
  33605. calling the constructor, and override contentAreaChanged(), in which you can position
  33606. any sub-components you need to add.
  33607. To add basic buttons without writing a special subclass, have a look at the
  33608. ToolbarButton class.
  33609. @see ToolbarButton, Toolbar, ToolbarItemFactory
  33610. */
  33611. class JUCE_API ToolbarItemComponent : public Button
  33612. {
  33613. public:
  33614. /** Constructor.
  33615. @param itemId the ID of the type of toolbar item which this represents
  33616. @param labelText the text to display if the toolbar's style is set to
  33617. Toolbar::iconsWithText or Toolbar::textOnly
  33618. @param isBeingUsedAsAButton set this to false if you don't want the button
  33619. to draw itself with button over/down states when the mouse
  33620. moves over it or clicks
  33621. */
  33622. ToolbarItemComponent (int itemId,
  33623. const String& labelText,
  33624. bool isBeingUsedAsAButton);
  33625. /** Destructor. */
  33626. ~ToolbarItemComponent();
  33627. /** Returns the item type ID that this component represents.
  33628. This value is in the constructor.
  33629. */
  33630. int getItemId() const throw() { return itemId; }
  33631. /** Returns the toolbar that contains this component, or 0 if it's not currently
  33632. inside one.
  33633. */
  33634. Toolbar* getToolbar() const;
  33635. /** Returns true if this component is currently inside a toolbar which is vertical.
  33636. @see Toolbar::isVertical
  33637. */
  33638. bool isToolbarVertical() const;
  33639. /** Returns the current style setting of this item.
  33640. Styles are listed in the Toolbar::ToolbarItemStyle enum.
  33641. @see setStyle, Toolbar::getStyle
  33642. */
  33643. Toolbar::ToolbarItemStyle getStyle() const throw() { return toolbarStyle; }
  33644. /** Changes the current style setting of this item.
  33645. Styles are listed in the Toolbar::ToolbarItemStyle enum, and are automatically updated
  33646. by the toolbar that holds this item.
  33647. @see setStyle, Toolbar::setStyle
  33648. */
  33649. virtual void setStyle (const Toolbar::ToolbarItemStyle& newStyle);
  33650. /** Returns the area of the component that should be used to display the button image or
  33651. other contents of the item.
  33652. This content area may change when the item's style changes, and may leave a space around the
  33653. edge of the component where the text label can be shown.
  33654. @see contentAreaChanged
  33655. */
  33656. const Rectangle<int> getContentArea() const throw() { return contentArea; }
  33657. /** This method must return the size criteria for this item, based on a given toolbar
  33658. size and orientation.
  33659. The preferredSize, minSize and maxSize values must all be set by your implementation
  33660. method. If the toolbar is horizontal, these will be the width of the item; for a vertical
  33661. toolbar, they refer to the item's height.
  33662. The preferredSize is the size that the component would like to be, and this must be
  33663. between the min and max sizes. For a fixed-size item, simply set all three variables to
  33664. the same value.
  33665. The toolbarThickness parameter tells you the depth of the toolbar - the same as calling
  33666. Toolbar::getThickness().
  33667. The isToolbarVertical parameter tells you whether the bar is oriented horizontally or
  33668. vertically.
  33669. */
  33670. virtual bool getToolbarItemSizes (int toolbarThickness,
  33671. bool isToolbarVertical,
  33672. int& preferredSize,
  33673. int& minSize,
  33674. int& maxSize) = 0;
  33675. /** Your subclass should use this method to draw its content area.
  33676. The graphics object that is passed-in will have been clipped and had its origin
  33677. moved to fit the content area as specified get getContentArea(). The width and height
  33678. parameters are the width and height of the content area.
  33679. If the component you're writing isn't a button, you can just do nothing in this method.
  33680. */
  33681. virtual void paintButtonArea (Graphics& g,
  33682. int width, int height,
  33683. bool isMouseOver, bool isMouseDown) = 0;
  33684. /** Callback to indicate that the content area of this item has changed.
  33685. This might be because the component was resized, or because the style changed and
  33686. the space needed for the text label is different.
  33687. See getContentArea() for a description of what the area is.
  33688. */
  33689. virtual void contentAreaChanged (const Rectangle<int>& newBounds) = 0;
  33690. /** Editing modes.
  33691. These are used by setEditingMode(), but will be rarely needed in user code.
  33692. */
  33693. enum ToolbarEditingMode
  33694. {
  33695. normalMode = 0, /**< Means that the component is active, inside a toolbar. */
  33696. editableOnToolbar, /**< Means that the component is on a toolbar, but the toolbar is in
  33697. customisation mode, and the items can be dragged around. */
  33698. editableOnPalette /**< Means that the component is on an new-item palette, so it can be
  33699. dragged onto a toolbar to add it to that bar.*/
  33700. };
  33701. /** Changes the editing mode of this component.
  33702. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33703. and is unlikely to be of much use in end-user-code.
  33704. */
  33705. void setEditingMode (const ToolbarEditingMode newMode);
  33706. /** Returns the current editing mode of this component.
  33707. This is used by the ToolbarItemPalette and related classes for making the items draggable,
  33708. and is unlikely to be of much use in end-user-code.
  33709. */
  33710. ToolbarEditingMode getEditingMode() const throw() { return mode; }
  33711. /** @internal */
  33712. void paintButton (Graphics& g, bool isMouseOver, bool isMouseDown);
  33713. /** @internal */
  33714. void resized();
  33715. juce_UseDebuggingNewOperator
  33716. private:
  33717. friend class Toolbar;
  33718. friend class ItemDragAndDropOverlayComponent;
  33719. const int itemId;
  33720. ToolbarEditingMode mode;
  33721. Toolbar::ToolbarItemStyle toolbarStyle;
  33722. ScopedPointer <Component> overlayComp;
  33723. int dragOffsetX, dragOffsetY;
  33724. bool isActive, isBeingDragged, isBeingUsedAsAButton;
  33725. Rectangle<int> contentArea;
  33726. ToolbarItemComponent (const ToolbarItemComponent&);
  33727. ToolbarItemComponent& operator= (const ToolbarItemComponent&);
  33728. };
  33729. #endif // __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  33730. /*** End of inlined file: juce_ToolbarItemComponent.h ***/
  33731. /**
  33732. A type of button designed to go on a toolbar.
  33733. This simple button can have two Drawable objects specified - one for normal
  33734. use and another one (optionally) for the button's "on" state if it's a
  33735. toggle button.
  33736. @see Toolbar, ToolbarItemFactory, ToolbarItemComponent, Drawable, Button
  33737. */
  33738. class JUCE_API ToolbarButton : public ToolbarItemComponent
  33739. {
  33740. public:
  33741. /** Creates a ToolbarButton.
  33742. @param itemId the ID for this toolbar item type. This is passed through to the
  33743. ToolbarItemComponent constructor
  33744. @param labelText the text to display on the button (if the toolbar is using a style
  33745. that shows text labels). This is passed through to the
  33746. ToolbarItemComponent constructor
  33747. @param normalImage a drawable object that the button should use as its icon. The object
  33748. that is passed-in here will be kept by this object and will be
  33749. deleted when no longer needed or when this button is deleted.
  33750. @param toggledOnImage a drawable object that the button can use as its icon if the button
  33751. is in a toggled-on state (see the Button::getToggleState() method). If
  33752. 0 is passed-in here, then the normal image will be used instead, regardless
  33753. of the toggle state. The object that is passed-in here will be kept by
  33754. this object and will be deleted when no longer needed or when this button
  33755. is deleted.
  33756. */
  33757. ToolbarButton (int itemId,
  33758. const String& labelText,
  33759. Drawable* normalImage,
  33760. Drawable* toggledOnImage);
  33761. /** Destructor. */
  33762. ~ToolbarButton();
  33763. /** @internal */
  33764. bool getToolbarItemSizes (int toolbarDepth, bool isToolbarVertical, int& preferredSize,
  33765. int& minSize, int& maxSize);
  33766. /** @internal */
  33767. void paintButtonArea (Graphics& g, int width, int height, bool isMouseOver, bool isMouseDown);
  33768. /** @internal */
  33769. void contentAreaChanged (const Rectangle<int>& newBounds);
  33770. juce_UseDebuggingNewOperator
  33771. private:
  33772. ScopedPointer <Drawable> normalImage, toggledOnImage;
  33773. ToolbarButton (const ToolbarButton&);
  33774. ToolbarButton& operator= (const ToolbarButton&);
  33775. };
  33776. #endif // __JUCE_TOOLBARBUTTON_JUCEHEADER__
  33777. /*** End of inlined file: juce_ToolbarButton.h ***/
  33778. #endif
  33779. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33780. /*** Start of inlined file: juce_CodeDocument.h ***/
  33781. #ifndef __JUCE_CODEDOCUMENT_JUCEHEADER__
  33782. #define __JUCE_CODEDOCUMENT_JUCEHEADER__
  33783. class CodeDocumentLine;
  33784. /**
  33785. A class for storing and manipulating a source code file.
  33786. When using a CodeEditorComponent, it takes one of these as its source object.
  33787. The CodeDocument stores its content as an array of lines, which makes it
  33788. quick to insert and delete.
  33789. @see CodeEditorComponent
  33790. */
  33791. class JUCE_API CodeDocument
  33792. {
  33793. public:
  33794. /** Creates a new, empty document.
  33795. */
  33796. CodeDocument();
  33797. /** Destructor. */
  33798. ~CodeDocument();
  33799. /** A position in a code document.
  33800. Using this class you can find a position in a code document and quickly get its
  33801. character position, line, and index. By calling setPositionMaintained (true), the
  33802. position is automatically updated when text is inserted or deleted in the document,
  33803. so that it maintains its original place in the text.
  33804. */
  33805. class JUCE_API Position
  33806. {
  33807. public:
  33808. /** Creates an uninitialised postion.
  33809. Don't attempt to call any methods on this until you've given it an owner document
  33810. to refer to!
  33811. */
  33812. Position() throw();
  33813. /** Creates a position based on a line and index in a document.
  33814. Note that this index is NOT the column number, it's the number of characters from the
  33815. start of the line. The "column" number isn't quite the same, because if the line
  33816. contains any tab characters, the relationship of the index to its visual column depends on
  33817. the number of spaces per tab being used!
  33818. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33819. they will be adjusted to keep them within its limits.
  33820. */
  33821. Position (const CodeDocument* ownerDocument,
  33822. int line, int indexInLine) throw();
  33823. /** Creates a position based on a character index in a document.
  33824. This position is placed at the specified number of characters from the start of the
  33825. document. The line and column are auto-calculated.
  33826. If the position is beyond the range of the document, it'll be adjusted to keep it
  33827. inside.
  33828. */
  33829. Position (const CodeDocument* ownerDocument,
  33830. int charactersFromStartOfDocument) throw();
  33831. /** Creates a copy of another position.
  33832. This will copy the position, but the new object will not be set to maintain its position,
  33833. even if the source object was set to do so.
  33834. */
  33835. Position (const Position& other) throw();
  33836. /** Destructor. */
  33837. ~Position() throw();
  33838. Position& operator= (const Position& other) throw();
  33839. bool operator== (const Position& other) const throw();
  33840. bool operator!= (const Position& other) const throw();
  33841. /** Points this object at a new position within the document.
  33842. If the position is beyond the range of the document, it'll be adjusted to keep it
  33843. inside.
  33844. @see getPosition, setLineAndIndex
  33845. */
  33846. void setPosition (int charactersFromStartOfDocument) throw();
  33847. /** Returns the position as the number of characters from the start of the document.
  33848. @see setPosition, getLineNumber, getIndexInLine
  33849. */
  33850. int getPosition() const throw() { return characterPos; }
  33851. /** Moves the position to a new line and index within the line.
  33852. Note that the index is NOT the column at which the position appears in an editor.
  33853. If the line contains any tab characters, the relationship of the index to its
  33854. visual position depends on the number of spaces per tab being used!
  33855. Lines are numbered from zero, and if the line or index are beyond the bounds of the document,
  33856. they will be adjusted to keep them within its limits.
  33857. */
  33858. void setLineAndIndex (int newLine, int newIndexInLine) throw();
  33859. /** Returns the line number of this position.
  33860. The first line in the document is numbered zero, not one!
  33861. */
  33862. int getLineNumber() const throw() { return line; }
  33863. /** Returns the number of characters from the start of the line.
  33864. Note that this value is NOT the column at which the position appears in an editor.
  33865. If the line contains any tab characters, the relationship of the index to its
  33866. visual position depends on the number of spaces per tab being used!
  33867. */
  33868. int getIndexInLine() const throw() { return indexInLine; }
  33869. /** Allows the position to be automatically updated when the document changes.
  33870. If this is set to true, the positon will register with its document so that
  33871. when the document has text inserted or deleted, this position will be automatically
  33872. moved to keep it at the same position in the text.
  33873. */
  33874. void setPositionMaintained (bool isMaintained) throw();
  33875. /** Moves the position forwards or backwards by the specified number of characters.
  33876. @see movedBy
  33877. */
  33878. void moveBy (int characterDelta) throw();
  33879. /** Returns a position which is the same as this one, moved by the specified number of
  33880. characters.
  33881. @see moveBy
  33882. */
  33883. const Position movedBy (int characterDelta) const throw();
  33884. /** Returns a position which is the same as this one, moved up or down by the specified
  33885. number of lines.
  33886. @see movedBy
  33887. */
  33888. const Position movedByLines (int deltaLines) const throw();
  33889. /** Returns the character in the document at this position.
  33890. @see getLineText
  33891. */
  33892. const juce_wchar getCharacter() const throw();
  33893. /** Returns the line from the document that this position is within.
  33894. @see getCharacter, getLineNumber
  33895. */
  33896. const String getLineText() const throw();
  33897. private:
  33898. CodeDocument* owner;
  33899. int characterPos, line, indexInLine;
  33900. bool positionMaintained;
  33901. };
  33902. /** Returns the full text of the document. */
  33903. const String getAllContent() const throw();
  33904. /** Returns a section of the document's text. */
  33905. const String getTextBetween (const Position& start, const Position& end) const throw();
  33906. /** Returns a line from the document. */
  33907. const String getLine (int lineIndex) const throw();
  33908. /** Returns the number of characters in the document. */
  33909. int getNumCharacters() const throw();
  33910. /** Returns the number of lines in the document. */
  33911. int getNumLines() const throw() { return lines.size(); }
  33912. /** Returns the number of characters in the longest line of the document. */
  33913. int getMaximumLineLength() throw();
  33914. /** Deletes a section of the text.
  33915. This operation is undoable.
  33916. */
  33917. void deleteSection (const Position& startPosition, const Position& endPosition);
  33918. /** Inserts some text into the document at a given position.
  33919. This operation is undoable.
  33920. */
  33921. void insertText (const Position& position, const String& text);
  33922. /** Clears the document and replaces it with some new text.
  33923. This operation is undoable - if you're trying to completely reset the document, you
  33924. might want to also call clearUndoHistory() and setSavePoint() after using this method.
  33925. */
  33926. void replaceAllContent (const String& newContent);
  33927. /** Replaces the editor's contents with the contents of a stream.
  33928. This will also reset the undo history and save point marker.
  33929. */
  33930. bool loadFromStream (InputStream& stream);
  33931. /** Writes the editor's current contents to a stream. */
  33932. bool writeToStream (OutputStream& stream);
  33933. /** Returns the preferred new-line characters for the document.
  33934. This will be either "\n", "\r\n", or (rarely) "\r".
  33935. @see setNewLineCharacters
  33936. */
  33937. const String getNewLineCharacters() const throw() { return newLineChars; }
  33938. /** Sets the new-line characters that the document should use.
  33939. The string must be either "\n", "\r\n", or (rarely) "\r".
  33940. @see getNewLineCharacters
  33941. */
  33942. void setNewLineCharacters (const String& newLine) throw();
  33943. /** Begins a new undo transaction.
  33944. The document itself will not call this internally, so relies on whatever is using the
  33945. document to periodically call this to break up the undo sequence into sensible chunks.
  33946. @see UndoManager::beginNewTransaction
  33947. */
  33948. void newTransaction();
  33949. /** Undo the last operation.
  33950. @see UndoManager::undo
  33951. */
  33952. void undo();
  33953. /** Redo the last operation.
  33954. @see UndoManager::redo
  33955. */
  33956. void redo();
  33957. /** Clears the undo history.
  33958. @see UndoManager::clearUndoHistory
  33959. */
  33960. void clearUndoHistory();
  33961. /** Returns the document's UndoManager */
  33962. UndoManager& getUndoManager() throw() { return undoManager; }
  33963. /** Makes a note that the document's current state matches the one that is saved.
  33964. After this has been called, hasChangedSinceSavePoint() will return false until
  33965. the document has been altered, and then it'll start returning true. If the document is
  33966. altered, but then undone until it gets back to this state, hasChangedSinceSavePoint()
  33967. will again return false.
  33968. @see hasChangedSinceSavePoint
  33969. */
  33970. void setSavePoint() throw();
  33971. /** Returns true if the state of the document differs from the state it was in when
  33972. setSavePoint() was last called.
  33973. @see setSavePoint
  33974. */
  33975. bool hasChangedSinceSavePoint() const throw();
  33976. /** Searches for a word-break. */
  33977. const Position findWordBreakAfter (const Position& position) const throw();
  33978. /** Searches for a word-break. */
  33979. const Position findWordBreakBefore (const Position& position) const throw();
  33980. /** An object that receives callbacks from the CodeDocument when its text changes.
  33981. @see CodeDocument::addListener, CodeDocument::removeListener
  33982. */
  33983. class JUCE_API Listener
  33984. {
  33985. public:
  33986. Listener() {}
  33987. virtual ~Listener() {}
  33988. /** Called by a CodeDocument when it is altered.
  33989. */
  33990. virtual void codeDocumentChanged (const Position& affectedTextStart,
  33991. const Position& affectedTextEnd) = 0;
  33992. };
  33993. /** Registers a listener object to receive callbacks when the document changes.
  33994. If the listener is already registered, this method has no effect.
  33995. @see removeListener
  33996. */
  33997. void addListener (Listener* listener) throw();
  33998. /** Deregisters a listener.
  33999. @see addListener
  34000. */
  34001. void removeListener (Listener* listener) throw();
  34002. /** Iterates the text in a CodeDocument.
  34003. This class lets you read characters from a CodeDocument. It's designed to be used
  34004. by a SyntaxAnalyser object.
  34005. @see CodeDocument, SyntaxAnalyser
  34006. */
  34007. class Iterator
  34008. {
  34009. public:
  34010. Iterator (CodeDocument* document);
  34011. Iterator (const Iterator& other);
  34012. Iterator& operator= (const Iterator& other) throw();
  34013. ~Iterator() throw();
  34014. /** Reads the next character and returns it.
  34015. @see peekNextChar
  34016. */
  34017. juce_wchar nextChar();
  34018. /** Reads the next character without advancing the current position. */
  34019. juce_wchar peekNextChar() const;
  34020. /** Advances the position by one character. */
  34021. void skip();
  34022. /** Returns the position of the next character as its position within the
  34023. whole document.
  34024. */
  34025. int getPosition() const throw() { return position; }
  34026. /** Skips over any whitespace characters until the next character is non-whitespace. */
  34027. void skipWhitespace();
  34028. /** Skips forward until the next character will be the first character on the next line */
  34029. void skipToEndOfLine();
  34030. /** Returns the line number of the next character. */
  34031. int getLine() const throw() { return line; }
  34032. /** Returns true if the iterator has reached the end of the document. */
  34033. bool isEOF() const throw();
  34034. private:
  34035. CodeDocument* document;
  34036. CodeDocumentLine* currentLine;
  34037. int line, position;
  34038. };
  34039. juce_UseDebuggingNewOperator
  34040. private:
  34041. friend class CodeDocumentInsertAction;
  34042. friend class CodeDocumentDeleteAction;
  34043. friend class Iterator;
  34044. friend class Position;
  34045. OwnedArray <CodeDocumentLine> lines;
  34046. Array <Position*> positionsToMaintain;
  34047. UndoManager undoManager;
  34048. int currentActionIndex, indexOfSavedState;
  34049. int maximumLineLength;
  34050. ListenerList <Listener> listeners;
  34051. String newLineChars;
  34052. void sendListenerChangeMessage (int startLine, int endLine);
  34053. void insert (const String& text, int insertPos, bool undoable);
  34054. void remove (int startPos, int endPos, bool undoable);
  34055. void checkLastLineStatus();
  34056. CodeDocument (const CodeDocument&);
  34057. CodeDocument& operator= (const CodeDocument&);
  34058. };
  34059. #endif // __JUCE_CODEDOCUMENT_JUCEHEADER__
  34060. /*** End of inlined file: juce_CodeDocument.h ***/
  34061. #endif
  34062. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34063. /*** Start of inlined file: juce_CodeEditorComponent.h ***/
  34064. #ifndef __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34065. #define __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34066. /*** Start of inlined file: juce_CodeTokeniser.h ***/
  34067. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  34068. #define __JUCE_CODETOKENISER_JUCEHEADER__
  34069. /**
  34070. A base class for tokenising code so that the syntax can be displayed in a
  34071. code editor.
  34072. @see CodeDocument, CodeEditorComponent
  34073. */
  34074. class JUCE_API CodeTokeniser
  34075. {
  34076. public:
  34077. CodeTokeniser() {}
  34078. virtual ~CodeTokeniser() {}
  34079. /** Reads the next token from the source and returns its token type.
  34080. This must leave the source pointing to the first character in the
  34081. next token.
  34082. */
  34083. virtual int readNextToken (CodeDocument::Iterator& source) = 0;
  34084. /** Returns a list of the names of the token types this analyser uses.
  34085. The index in this list must match the token type numbers that are
  34086. returned by readNextToken().
  34087. */
  34088. virtual const StringArray getTokenTypes() = 0;
  34089. /** Returns a suggested syntax highlighting colour for a specified
  34090. token type.
  34091. */
  34092. virtual const Colour getDefaultColour (int tokenType) = 0;
  34093. juce_UseDebuggingNewOperator
  34094. };
  34095. #endif // __JUCE_CODETOKENISER_JUCEHEADER__
  34096. /*** End of inlined file: juce_CodeTokeniser.h ***/
  34097. /**
  34098. A text editor component designed specifically for source code.
  34099. This is designed to handle syntax highlighting and fast editing of very large
  34100. files.
  34101. */
  34102. class JUCE_API CodeEditorComponent : public Component,
  34103. public TextInputTarget,
  34104. public Timer,
  34105. public ScrollBarListener,
  34106. public CodeDocument::Listener,
  34107. public AsyncUpdater
  34108. {
  34109. public:
  34110. /** Creates an editor for a document.
  34111. The tokeniser object is optional - pass 0 to disable syntax highlighting.
  34112. The object that you pass in is not owned or deleted by the editor - you must
  34113. make sure that it doesn't get deleted while this component is still using it.
  34114. @see CodeDocument
  34115. */
  34116. CodeEditorComponent (CodeDocument& document,
  34117. CodeTokeniser* codeTokeniser);
  34118. /** Destructor. */
  34119. ~CodeEditorComponent();
  34120. /** Returns the code document that this component is editing. */
  34121. CodeDocument& getDocument() const throw() { return document; }
  34122. /** Loads the given content into the document.
  34123. This will completely reset the CodeDocument object, clear its undo history,
  34124. and fill it with this text.
  34125. */
  34126. void loadContent (const String& newContent);
  34127. /** Returns the standard character width. */
  34128. float getCharWidth() const throw() { return charWidth; }
  34129. /** Returns the height of a line of text, in pixels. */
  34130. int getLineHeight() const throw() { return lineHeight; }
  34131. /** Returns the number of whole lines visible on the screen,
  34132. This doesn't include a cut-off line that might be visible at the bottom if the
  34133. component's height isn't an exact multiple of the line-height.
  34134. */
  34135. int getNumLinesOnScreen() const throw() { return linesOnScreen; }
  34136. /** Returns the number of whole columns visible on the screen.
  34137. This doesn't include any cut-off columns at the right-hand edge.
  34138. */
  34139. int getNumColumnsOnScreen() const throw() { return columnsOnScreen; }
  34140. /** Returns the current caret position. */
  34141. const CodeDocument::Position getCaretPos() const { return caretPos; }
  34142. /** Moves the caret.
  34143. If selecting is true, the section of the document between the current
  34144. caret position and the new one will become selected. If false, any currently
  34145. selected region will be deselected.
  34146. */
  34147. void moveCaretTo (const CodeDocument::Position& newPos, bool selecting);
  34148. /** Returns the on-screen position of a character in the document.
  34149. The rectangle returned is relative to this component's top-left origin.
  34150. */
  34151. const Rectangle<int> getCharacterBounds (const CodeDocument::Position& pos) const throw();
  34152. /** Finds the character at a given on-screen position.
  34153. The co-ordinates are relative to this component's top-left origin.
  34154. */
  34155. const CodeDocument::Position getPositionAt (int x, int y);
  34156. void cursorLeft (bool moveInWholeWordSteps, bool selecting);
  34157. void cursorRight (bool moveInWholeWordSteps, bool selecting);
  34158. void cursorDown (bool selecting);
  34159. void cursorUp (bool selecting);
  34160. void pageDown (bool selecting);
  34161. void pageUp (bool selecting);
  34162. void scrollDown();
  34163. void scrollUp();
  34164. void scrollToLine (int newFirstLineOnScreen);
  34165. void scrollBy (int deltaLines);
  34166. void scrollToColumn (int newFirstColumnOnScreen);
  34167. void scrollToKeepCaretOnScreen();
  34168. void goToStartOfDocument (bool selecting);
  34169. void goToStartOfLine (bool selecting);
  34170. void goToEndOfDocument (bool selecting);
  34171. void goToEndOfLine (bool selecting);
  34172. void deselectAll();
  34173. void selectAll();
  34174. void insertTextAtCaret (const String& textToInsert);
  34175. void insertTabAtCaret();
  34176. void cut();
  34177. void copy();
  34178. void copyThenCut();
  34179. void paste();
  34180. void backspace (bool moveInWholeWordSteps);
  34181. void deleteForward (bool moveInWholeWordSteps);
  34182. void undo();
  34183. void redo();
  34184. const Range<int> getHighlightedRegion() const;
  34185. void setHighlightedRegion (const Range<int>& newRange);
  34186. const String getTextInRange (const Range<int>& range) const;
  34187. /** Changes the current tab settings.
  34188. This lets you change the tab size and whether pressing the tab key inserts a
  34189. tab character, or its equivalent number of spaces.
  34190. */
  34191. void setTabSize (int numSpacesPerTab,
  34192. bool insertSpacesInsteadOfTabCharacters) throw();
  34193. /** Returns the current number of spaces per tab.
  34194. @see setTabSize
  34195. */
  34196. int getTabSize() const throw() { return spacesPerTab; }
  34197. /** Returns true if the tab key will insert spaces instead of actual tab characters.
  34198. @see setTabSize
  34199. */
  34200. bool areSpacesInsertedForTabs() const { return useSpacesForTabs; }
  34201. /** Changes the font.
  34202. Make sure you only use a fixed-width font, or this component will look pretty nasty!
  34203. */
  34204. void setFont (const Font& newFont);
  34205. /** Returns the font that the editor is using. */
  34206. const Font& getFont() const throw() { return font; }
  34207. /** Resets the syntax highlighting colours to the default ones provided by the
  34208. code tokeniser.
  34209. @see CodeTokeniser::getDefaultColour
  34210. */
  34211. void resetToDefaultColours();
  34212. /** Changes one of the syntax highlighting colours.
  34213. The token type values are dependent on the tokeniser being used - use
  34214. CodeTokeniser::getTokenTypes() to get a list of the token types.
  34215. @see getColourForTokenType
  34216. */
  34217. void setColourForTokenType (int tokenType, const Colour& colour);
  34218. /** Returns one of the syntax highlighting colours.
  34219. The token type values are dependent on the tokeniser being used - use
  34220. CodeTokeniser::getTokenTypes() to get a list of the token types.
  34221. @see setColourForTokenType
  34222. */
  34223. const Colour getColourForTokenType (int tokenType) const throw();
  34224. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  34225. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34226. methods.
  34227. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34228. */
  34229. enum ColourIds
  34230. {
  34231. backgroundColourId = 0x1004500, /**< A colour to use to fill the editor's background. */
  34232. caretColourId = 0x1004501, /**< The colour to draw the caret. */
  34233. highlightColourId = 0x1004502, /**< The colour to use for the highlighted background under
  34234. selected text. */
  34235. defaultTextColourId = 0x1004503 /**< The colour to use for text when no syntax colouring is
  34236. enabled. */
  34237. };
  34238. /** Changes the size of the scrollbars. */
  34239. void setScrollbarThickness (int thickness) throw();
  34240. /** Returns the thickness of the scrollbars. */
  34241. int getScrollbarThickness() const throw() { return scrollbarThickness; }
  34242. /** @internal */
  34243. void resized();
  34244. /** @internal */
  34245. void paint (Graphics& g);
  34246. /** @internal */
  34247. bool keyPressed (const KeyPress& key);
  34248. /** @internal */
  34249. void mouseDown (const MouseEvent& e);
  34250. /** @internal */
  34251. void mouseDrag (const MouseEvent& e);
  34252. /** @internal */
  34253. void mouseUp (const MouseEvent& e);
  34254. /** @internal */
  34255. void mouseDoubleClick (const MouseEvent& e);
  34256. /** @internal */
  34257. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  34258. /** @internal */
  34259. void focusGained (FocusChangeType cause);
  34260. /** @internal */
  34261. void focusLost (FocusChangeType cause);
  34262. /** @internal */
  34263. void timerCallback();
  34264. /** @internal */
  34265. void scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart);
  34266. /** @internal */
  34267. void handleAsyncUpdate();
  34268. /** @internal */
  34269. void codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  34270. const CodeDocument::Position& affectedTextEnd);
  34271. /** @internal */
  34272. bool isTextInputActive() const;
  34273. juce_UseDebuggingNewOperator
  34274. private:
  34275. CodeDocument& document;
  34276. Font font;
  34277. int firstLineOnScreen, gutter, spacesPerTab;
  34278. float charWidth;
  34279. int lineHeight, linesOnScreen, columnsOnScreen;
  34280. int scrollbarThickness, columnToTryToMaintain;
  34281. bool useSpacesForTabs;
  34282. double xOffset;
  34283. CodeDocument::Position caretPos;
  34284. CodeDocument::Position selectionStart, selectionEnd;
  34285. class CaretComponent;
  34286. CaretComponent* caret;
  34287. ScrollBar* verticalScrollBar;
  34288. ScrollBar* horizontalScrollBar;
  34289. enum DragType
  34290. {
  34291. notDragging,
  34292. draggingSelectionStart,
  34293. draggingSelectionEnd
  34294. };
  34295. DragType dragType;
  34296. CodeTokeniser* codeTokeniser;
  34297. Array <Colour> coloursForTokenCategories;
  34298. class CodeEditorLine;
  34299. OwnedArray <CodeEditorLine> lines;
  34300. void rebuildLineTokens();
  34301. OwnedArray <CodeDocument::Iterator> cachedIterators;
  34302. void clearCachedIterators (int firstLineToBeInvalid) throw();
  34303. void updateCachedIterators (int maxLineNum);
  34304. void getIteratorForPosition (int position, CodeDocument::Iterator& result);
  34305. void moveLineDelta (int delta, bool selecting);
  34306. void updateScrollBars();
  34307. void scrollToLineInternal (int line);
  34308. void scrollToColumnInternal (double column);
  34309. void newTransaction();
  34310. int indexToColumn (int line, int index) const throw();
  34311. int columnToIndex (int line, int column) const throw();
  34312. CodeEditorComponent (const CodeEditorComponent&);
  34313. CodeEditorComponent& operator= (const CodeEditorComponent&);
  34314. };
  34315. #endif // __JUCE_CODEEDITORCOMPONENT_JUCEHEADER__
  34316. /*** End of inlined file: juce_CodeEditorComponent.h ***/
  34317. #endif
  34318. #ifndef __JUCE_CODETOKENISER_JUCEHEADER__
  34319. #endif
  34320. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34321. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  34322. #ifndef __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34323. #define __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34324. /**
  34325. A simple lexical analyser for syntax colouring of C++ code.
  34326. @see SyntaxAnalyser, CodeEditorComponent, CodeDocument
  34327. */
  34328. class JUCE_API CPlusPlusCodeTokeniser : public CodeTokeniser
  34329. {
  34330. public:
  34331. CPlusPlusCodeTokeniser();
  34332. ~CPlusPlusCodeTokeniser();
  34333. enum TokenType
  34334. {
  34335. tokenType_error = 0,
  34336. tokenType_comment,
  34337. tokenType_builtInKeyword,
  34338. tokenType_identifier,
  34339. tokenType_integerLiteral,
  34340. tokenType_floatLiteral,
  34341. tokenType_stringLiteral,
  34342. tokenType_operator,
  34343. tokenType_bracket,
  34344. tokenType_punctuation,
  34345. tokenType_preprocessor
  34346. };
  34347. int readNextToken (CodeDocument::Iterator& source);
  34348. const StringArray getTokenTypes();
  34349. const Colour getDefaultColour (int tokenType);
  34350. /** This is a handy method for checking whether a string is a c++ reserved keyword. */
  34351. static bool isReservedKeyword (const String& token) throw();
  34352. juce_UseDebuggingNewOperator
  34353. };
  34354. #endif // __JUCE_CPLUSPLUSCODETOKENISER_JUCEHEADER__
  34355. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.h ***/
  34356. #endif
  34357. #ifndef __JUCE_COMBOBOX_JUCEHEADER__
  34358. #endif
  34359. #ifndef __JUCE_LABEL_JUCEHEADER__
  34360. #endif
  34361. #ifndef __JUCE_LISTBOX_JUCEHEADER__
  34362. #endif
  34363. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34364. /*** Start of inlined file: juce_ProgressBar.h ***/
  34365. #ifndef __JUCE_PROGRESSBAR_JUCEHEADER__
  34366. #define __JUCE_PROGRESSBAR_JUCEHEADER__
  34367. /**
  34368. A progress bar component.
  34369. To use this, just create one and make it visible. It'll run its own timer
  34370. to keep an eye on a variable that you give it, and will automatically
  34371. redraw itself when the variable changes.
  34372. For an easy way of running a background task with a dialog box showing its
  34373. progress, see the ThreadWithProgressWindow class.
  34374. @see ThreadWithProgressWindow
  34375. */
  34376. class JUCE_API ProgressBar : public Component,
  34377. public SettableTooltipClient,
  34378. private Timer
  34379. {
  34380. public:
  34381. /** Creates a ProgressBar.
  34382. @param progress pass in a reference to a double that you're going to
  34383. update with your task's progress. The ProgressBar will
  34384. monitor the value of this variable and will redraw itself
  34385. when the value changes. The range is from 0 to 1.0. Obviously
  34386. you'd better be careful not to delete this variable while the
  34387. ProgressBar still exists!
  34388. */
  34389. explicit ProgressBar (double& progress);
  34390. /** Destructor. */
  34391. ~ProgressBar();
  34392. /** Turns the percentage display on or off.
  34393. By default this is on, and the progress bar will display a text string showing
  34394. its current percentage.
  34395. */
  34396. void setPercentageDisplay (const bool shouldDisplayPercentage);
  34397. /** Gives the progress bar a string to display inside it.
  34398. If you call this, it will turn off the percentage display.
  34399. @see setPercentageDisplay
  34400. */
  34401. void setTextToDisplay (const String& text);
  34402. /** A set of colour IDs to use to change the colour of various aspects of the bar.
  34403. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34404. methods.
  34405. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34406. */
  34407. enum ColourIds
  34408. {
  34409. backgroundColourId = 0x1001900, /**< The background colour, behind the bar. */
  34410. foregroundColourId = 0x1001a00, /**< The colour to use to draw the bar itself. LookAndFeel
  34411. classes will probably use variations on this colour. */
  34412. };
  34413. juce_UseDebuggingNewOperator
  34414. protected:
  34415. /** @internal */
  34416. void paint (Graphics& g);
  34417. /** @internal */
  34418. void lookAndFeelChanged();
  34419. /** @internal */
  34420. void visibilityChanged();
  34421. /** @internal */
  34422. void colourChanged();
  34423. private:
  34424. double& progress;
  34425. double currentValue;
  34426. bool displayPercentage;
  34427. String displayedMessage, currentMessage;
  34428. uint32 lastCallbackTime;
  34429. void timerCallback();
  34430. ProgressBar (const ProgressBar&);
  34431. ProgressBar& operator= (const ProgressBar&);
  34432. };
  34433. #endif // __JUCE_PROGRESSBAR_JUCEHEADER__
  34434. /*** End of inlined file: juce_ProgressBar.h ***/
  34435. #endif
  34436. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34437. /*** Start of inlined file: juce_Slider.h ***/
  34438. #ifndef __JUCE_SLIDER_JUCEHEADER__
  34439. #define __JUCE_SLIDER_JUCEHEADER__
  34440. /*** Start of inlined file: juce_SliderListener.h ***/
  34441. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  34442. #define __JUCE_SLIDERLISTENER_JUCEHEADER__
  34443. class Slider;
  34444. /**
  34445. A class for receiving callbacks from a Slider.
  34446. To be told when a slider's value changes, you can register a SliderListener
  34447. object using Slider::addListener().
  34448. @see Slider::addListener, Slider::removeListener
  34449. */
  34450. class JUCE_API SliderListener
  34451. {
  34452. public:
  34453. /** Destructor. */
  34454. virtual ~SliderListener() {}
  34455. /** Called when the slider's value is changed.
  34456. This may be caused by dragging it, or by typing in its text entry box,
  34457. or by a call to Slider::setValue().
  34458. You can find out the new value using Slider::getValue().
  34459. @see Slider::valueChanged
  34460. */
  34461. virtual void sliderValueChanged (Slider* slider) = 0;
  34462. /** Called when the slider is about to be dragged.
  34463. This is called when a drag begins, then it's followed by multiple calls
  34464. to sliderValueChanged(), and then sliderDragEnded() is called after the
  34465. user lets go.
  34466. @see sliderDragEnded, Slider::startedDragging
  34467. */
  34468. virtual void sliderDragStarted (Slider* slider);
  34469. /** Called after a drag operation has finished.
  34470. @see sliderDragStarted, Slider::stoppedDragging
  34471. */
  34472. virtual void sliderDragEnded (Slider* slider);
  34473. };
  34474. #endif // __JUCE_SLIDERLISTENER_JUCEHEADER__
  34475. /*** End of inlined file: juce_SliderListener.h ***/
  34476. /**
  34477. A slider control for changing a value.
  34478. The slider can be horizontal, vertical, or rotary, and can optionally have
  34479. a text-box inside it to show an editable display of the current value.
  34480. To use it, create a Slider object and use the setSliderStyle() method
  34481. to set up the type you want. To set up the text-entry box, use setTextBoxStyle().
  34482. To define the values that it can be set to, see the setRange() and setValue() methods.
  34483. There are also lots of custom tweaks you can do by subclassing and overriding
  34484. some of the virtual methods, such as changing the scaling, changing the format of
  34485. the text display, custom ways of limiting the values, etc.
  34486. You can register SliderListeners with a slider, which will be informed when the value
  34487. changes, or a subclass can override valueChanged() to be informed synchronously.
  34488. @see SliderListener
  34489. */
  34490. class JUCE_API Slider : public Component,
  34491. public SettableTooltipClient,
  34492. private AsyncUpdater,
  34493. private ButtonListener,
  34494. private LabelListener,
  34495. private Value::Listener
  34496. {
  34497. public:
  34498. /** Creates a slider.
  34499. When created, you'll need to set up the slider's style and range with setSliderStyle(),
  34500. setRange(), etc.
  34501. */
  34502. explicit Slider (const String& componentName = String::empty);
  34503. /** Destructor. */
  34504. ~Slider();
  34505. /** The types of slider available.
  34506. @see setSliderStyle, setRotaryParameters
  34507. */
  34508. enum SliderStyle
  34509. {
  34510. LinearHorizontal, /**< A traditional horizontal slider. */
  34511. LinearVertical, /**< A traditional vertical slider. */
  34512. LinearBar, /**< A horizontal bar slider with the text label drawn on top of it. */
  34513. Rotary, /**< A rotary control that you move by dragging the mouse in a circular motion, like a knob.
  34514. @see setRotaryParameters */
  34515. RotaryHorizontalDrag, /**< A rotary control that you move by dragging the mouse left-to-right.
  34516. @see setRotaryParameters */
  34517. RotaryVerticalDrag, /**< A rotary control that you move by dragging the mouse up-and-down.
  34518. @see setRotaryParameters */
  34519. IncDecButtons, /**< A pair of buttons that increment or decrement the slider's value by the increment set in setRange(). */
  34520. TwoValueHorizontal, /**< A horizontal slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34521. @see setMinValue, setMaxValue */
  34522. TwoValueVertical, /**< A vertical slider that has two thumbs instead of one, so it can show a minimum and maximum value.
  34523. @see setMinValue, setMaxValue */
  34524. ThreeValueHorizontal, /**< A horizontal slider that has three thumbs instead of one, so it can show a minimum and maximum
  34525. value, with the current value being somewhere between them.
  34526. @see setMinValue, setMaxValue */
  34527. ThreeValueVertical, /**< A vertical slider that has three thumbs instead of one, so it can show a minimum and maximum
  34528. value, with the current value being somewhere between them.
  34529. @see setMinValue, setMaxValue */
  34530. };
  34531. /** Changes the type of slider interface being used.
  34532. @param newStyle the type of interface
  34533. @see setRotaryParameters, setVelocityBasedMode,
  34534. */
  34535. void setSliderStyle (SliderStyle newStyle);
  34536. /** Returns the slider's current style.
  34537. @see setSliderStyle
  34538. */
  34539. SliderStyle getSliderStyle() const { return style; }
  34540. /** Changes the properties of a rotary slider.
  34541. @param startAngleRadians the angle (in radians, clockwise from the top) at which
  34542. the slider's minimum value is represented
  34543. @param endAngleRadians the angle (in radians, clockwise from the top) at which
  34544. the slider's maximum value is represented. This must be
  34545. greater than startAngleRadians
  34546. @param stopAtEnd if true, then when the slider is dragged around past the
  34547. minimum or maximum, it'll stop there; if false, it'll wrap
  34548. back to the opposite value
  34549. */
  34550. void setRotaryParameters (float startAngleRadians,
  34551. float endAngleRadians,
  34552. bool stopAtEnd);
  34553. /** Sets the distance the mouse has to move to drag the slider across
  34554. the full extent of its range.
  34555. This only applies when in modes like RotaryHorizontalDrag, where it's using
  34556. relative mouse movements to adjust the slider.
  34557. */
  34558. void setMouseDragSensitivity (int distanceForFullScaleDrag);
  34559. /** Changes the way the the mouse is used when dragging the slider.
  34560. If true, this will turn on velocity-sensitive dragging, so that
  34561. the faster the mouse moves, the bigger the movement to the slider. This
  34562. helps when making accurate adjustments if the slider's range is quite large.
  34563. If false, the slider will just try to snap to wherever the mouse is.
  34564. */
  34565. void setVelocityBasedMode (bool isVelocityBased);
  34566. /** Returns true if velocity-based mode is active.
  34567. @see setVelocityBasedMode
  34568. */
  34569. bool getVelocityBasedMode() const { return isVelocityBased; }
  34570. /** Changes aspects of the scaling used when in velocity-sensitive mode.
  34571. These apply when you've used setVelocityBasedMode() to turn on velocity mode,
  34572. or if you're holding down ctrl.
  34573. @param sensitivity higher values than 1.0 increase the range of acceleration used
  34574. @param threshold the minimum number of pixels that the mouse needs to move for it
  34575. to be treated as a movement
  34576. @param offset values greater than 0.0 increase the minimum speed that will be used when
  34577. the threshold is reached
  34578. @param userCanPressKeyToSwapMode if true, then the user can hold down the ctrl or command
  34579. key to toggle velocity-sensitive mode
  34580. */
  34581. void setVelocityModeParameters (double sensitivity = 1.0,
  34582. int threshold = 1,
  34583. double offset = 0.0,
  34584. bool userCanPressKeyToSwapMode = true);
  34585. /** Returns the velocity sensitivity setting.
  34586. @see setVelocityModeParameters
  34587. */
  34588. double getVelocitySensitivity() const { return velocityModeSensitivity; }
  34589. /** Returns the velocity threshold setting.
  34590. @see setVelocityModeParameters
  34591. */
  34592. int getVelocityThreshold() const { return velocityModeThreshold; }
  34593. /** Returns the velocity offset setting.
  34594. @see setVelocityModeParameters
  34595. */
  34596. double getVelocityOffset() const { return velocityModeOffset; }
  34597. /** Returns the velocity user key setting.
  34598. @see setVelocityModeParameters
  34599. */
  34600. bool getVelocityModeIsSwappable() const { return userKeyOverridesVelocity; }
  34601. /** Sets up a skew factor to alter the way values are distributed.
  34602. You may want to use a range of values on the slider where more accuracy
  34603. is required towards one end of the range, so this will logarithmically
  34604. spread the values across the length of the slider.
  34605. If the factor is < 1.0, the lower end of the range will fill more of the
  34606. slider's length; if the factor is > 1.0, the upper end of the range
  34607. will be expanded instead. A factor of 1.0 doesn't skew it at all.
  34608. To set the skew position by using a mid-point, use the setSkewFactorFromMidPoint()
  34609. method instead.
  34610. @see getSkewFactor, setSkewFactorFromMidPoint
  34611. */
  34612. void setSkewFactor (double factor);
  34613. /** Sets up a skew factor to alter the way values are distributed.
  34614. This allows you to specify the slider value that should appear in the
  34615. centre of the slider's visible range.
  34616. @see setSkewFactor, getSkewFactor
  34617. */
  34618. void setSkewFactorFromMidPoint (double sliderValueToShowAtMidPoint);
  34619. /** Returns the current skew factor.
  34620. See setSkewFactor for more info.
  34621. @see setSkewFactor, setSkewFactorFromMidPoint
  34622. */
  34623. double getSkewFactor() const { return skewFactor; }
  34624. /** Used by setIncDecButtonsMode().
  34625. */
  34626. enum IncDecButtonMode
  34627. {
  34628. incDecButtonsNotDraggable,
  34629. incDecButtonsDraggable_AutoDirection,
  34630. incDecButtonsDraggable_Horizontal,
  34631. incDecButtonsDraggable_Vertical
  34632. };
  34633. /** When the style is IncDecButtons, this lets you turn on a mode where the mouse
  34634. can be dragged on the buttons to drag the values.
  34635. By default this is turned off. When enabled, clicking on the buttons still works
  34636. them as normal, but by holding down the mouse on a button and dragging it a little
  34637. distance, it flips into a mode where the value can be dragged. The drag direction can
  34638. either be set explicitly to be vertical or horizontal, or can be set to
  34639. incDecButtonsDraggable_AutoDirection so that it depends on whether the buttons
  34640. are side-by-side or above each other.
  34641. */
  34642. void setIncDecButtonsMode (IncDecButtonMode mode);
  34643. /** The position of the slider's text-entry box.
  34644. @see setTextBoxStyle
  34645. */
  34646. enum TextEntryBoxPosition
  34647. {
  34648. NoTextBox, /**< Doesn't display a text box. */
  34649. TextBoxLeft, /**< Puts the text box to the left of the slider, vertically centred. */
  34650. TextBoxRight, /**< Puts the text box to the right of the slider, vertically centred. */
  34651. TextBoxAbove, /**< Puts the text box above the slider, horizontally centred. */
  34652. TextBoxBelow /**< Puts the text box below the slider, horizontally centred. */
  34653. };
  34654. /** Changes the location and properties of the text-entry box.
  34655. @param newPosition where it should go (or NoTextBox to not have one at all)
  34656. @param isReadOnly if true, it's a read-only display
  34657. @param textEntryBoxWidth the width of the text-box in pixels. Make sure this leaves enough
  34658. room for the slider as well!
  34659. @param textEntryBoxHeight the height of the text-box in pixels. Make sure this leaves enough
  34660. room for the slider as well!
  34661. @see setTextBoxIsEditable, getValueFromText, getTextFromValue
  34662. */
  34663. void setTextBoxStyle (TextEntryBoxPosition newPosition,
  34664. bool isReadOnly,
  34665. int textEntryBoxWidth,
  34666. int textEntryBoxHeight);
  34667. /** Returns the status of the text-box.
  34668. @see setTextBoxStyle
  34669. */
  34670. const TextEntryBoxPosition getTextBoxPosition() const { return textBoxPos; }
  34671. /** Returns the width used for the text-box.
  34672. @see setTextBoxStyle
  34673. */
  34674. int getTextBoxWidth() const { return textBoxWidth; }
  34675. /** Returns the height used for the text-box.
  34676. @see setTextBoxStyle
  34677. */
  34678. int getTextBoxHeight() const { return textBoxHeight; }
  34679. /** Makes the text-box editable.
  34680. By default this is true, and the user can enter values into the textbox,
  34681. but it can be turned off if that's not suitable.
  34682. @see setTextBoxStyle, getValueFromText, getTextFromValue
  34683. */
  34684. void setTextBoxIsEditable (bool shouldBeEditable);
  34685. /** Returns true if the text-box is read-only.
  34686. @see setTextBoxStyle
  34687. */
  34688. bool isTextBoxEditable() const { return editableText; }
  34689. /** If the text-box is editable, this will give it the focus so that the user can
  34690. type directly into it.
  34691. This is basically the effect as the user clicking on it.
  34692. */
  34693. void showTextBox();
  34694. /** If the text-box currently has focus and is being edited, this resets it and takes keyboard
  34695. focus away from it.
  34696. @param discardCurrentEditorContents if true, the slider's value will be left
  34697. unchanged; if false, the current contents of the
  34698. text editor will be used to set the slider position
  34699. before it is hidden.
  34700. */
  34701. void hideTextBox (bool discardCurrentEditorContents);
  34702. /** Changes the slider's current value.
  34703. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34704. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34705. want to handle it.
  34706. @param newValue the new value to set - this will be restricted by the
  34707. minimum and maximum range, and will be snapped to the
  34708. nearest interval if one has been set
  34709. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34710. any SliderListeners or the valueChanged() method
  34711. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34712. synchronously; if false, it will be asynchronous
  34713. */
  34714. void setValue (double newValue,
  34715. bool sendUpdateMessage = true,
  34716. bool sendMessageSynchronously = false);
  34717. /** Returns the slider's current value. */
  34718. double getValue() const;
  34719. /** Returns the Value object that represents the slider's current position.
  34720. You can use this Value object to connect the slider's position to external values or setters,
  34721. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34722. your own Value object.
  34723. @see Value, getMaxValue, getMinValueObject
  34724. */
  34725. Value& getValueObject() { return currentValue; }
  34726. /** Sets the limits that the slider's value can take.
  34727. @param newMinimum the lowest value allowed
  34728. @param newMaximum the highest value allowed
  34729. @param newInterval the steps in which the value is allowed to increase - if this
  34730. is not zero, the value will always be (newMinimum + (newInterval * an integer)).
  34731. */
  34732. void setRange (double newMinimum,
  34733. double newMaximum,
  34734. double newInterval = 0);
  34735. /** Returns the current maximum value.
  34736. @see setRange
  34737. */
  34738. double getMaximum() const { return maximum; }
  34739. /** Returns the current minimum value.
  34740. @see setRange
  34741. */
  34742. double getMinimum() const { return minimum; }
  34743. /** Returns the current step-size for values.
  34744. @see setRange
  34745. */
  34746. double getInterval() const { return interval; }
  34747. /** For a slider with two or three thumbs, this returns the lower of its values.
  34748. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34749. A slider with three values also uses the normal getValue() and setValue() methods to
  34750. control the middle value.
  34751. @see setMinValue, getMaxValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34752. */
  34753. double getMinValue() const;
  34754. /** For a slider with two or three thumbs, this returns the lower of its values.
  34755. You can use this Value object to connect the slider's position to external values or setters,
  34756. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34757. your own Value object.
  34758. @see Value, getMinValue, getMaxValueObject
  34759. */
  34760. Value& getMinValueObject() { return valueMin; }
  34761. /** For a slider with two or three thumbs, this sets the lower of its values.
  34762. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34763. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34764. want to handle it.
  34765. @param newValue the new value to set - this will be restricted by the
  34766. minimum and maximum range, and will be snapped to the nearest
  34767. interval if one has been set.
  34768. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34769. any SliderListeners or the valueChanged() method
  34770. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34771. synchronously; if false, it will be asynchronous
  34772. @param allowNudgingOfOtherValues if false, this value will be restricted to being below the
  34773. max value (in a two-value slider) or the mid value (in a three-value
  34774. slider). If false, then if this value goes beyond those values,
  34775. it will push them along with it.
  34776. @see getMinValue, setMaxValue, setValue
  34777. */
  34778. void setMinValue (double newValue,
  34779. bool sendUpdateMessage = true,
  34780. bool sendMessageSynchronously = false,
  34781. bool allowNudgingOfOtherValues = false);
  34782. /** For a slider with two or three thumbs, this returns the higher of its values.
  34783. For a two-value slider, the values are controlled with getMinValue() and getMaxValue().
  34784. A slider with three values also uses the normal getValue() and setValue() methods to
  34785. control the middle value.
  34786. @see getMinValue, TwoValueHorizontal, TwoValueVertical, ThreeValueHorizontal, ThreeValueVertical
  34787. */
  34788. double getMaxValue() const;
  34789. /** For a slider with two or three thumbs, this returns the higher of its values.
  34790. You can use this Value object to connect the slider's position to external values or setters,
  34791. either by taking a copy of the Value, or by using Value::referTo() to make it point to
  34792. your own Value object.
  34793. @see Value, getMaxValue, getMinValueObject
  34794. */
  34795. Value& getMaxValueObject() { return valueMax; }
  34796. /** For a slider with two or three thumbs, this sets the lower of its values.
  34797. This will trigger a callback to SliderListener::sliderValueChanged() for any listeners
  34798. that are registered, and will synchronously call the valueChanged() method in case subclasses
  34799. want to handle it.
  34800. @param newValue the new value to set - this will be restricted by the
  34801. minimum and maximum range, and will be snapped to the nearest
  34802. interval if one has been set.
  34803. @param sendUpdateMessage if false, a change to the value will not trigger a call to
  34804. any SliderListeners or the valueChanged() method
  34805. @param sendMessageSynchronously if true, then a call to the SliderListeners will be made
  34806. synchronously; if false, it will be asynchronous
  34807. @param allowNudgingOfOtherValues if false, this value will be restricted to being above the
  34808. min value (in a two-value slider) or the mid value (in a three-value
  34809. slider). If false, then if this value goes beyond those values,
  34810. it will push them along with it.
  34811. @see getMaxValue, setMinValue, setValue
  34812. */
  34813. void setMaxValue (double newValue,
  34814. bool sendUpdateMessage = true,
  34815. bool sendMessageSynchronously = false,
  34816. bool allowNudgingOfOtherValues = false);
  34817. /** Adds a listener to be called when this slider's value changes. */
  34818. void addListener (SliderListener* listener);
  34819. /** Removes a previously-registered listener. */
  34820. void removeListener (SliderListener* listener);
  34821. /** This lets you choose whether double-clicking moves the slider to a given position.
  34822. By default this is turned off, but it's handy if you want a double-click to act
  34823. as a quick way of resetting a slider. Just pass in the value you want it to
  34824. go to when double-clicked.
  34825. @see getDoubleClickReturnValue
  34826. */
  34827. void setDoubleClickReturnValue (bool isDoubleClickEnabled,
  34828. double valueToSetOnDoubleClick);
  34829. /** Returns the values last set by setDoubleClickReturnValue() method.
  34830. Sets isEnabled to true if double-click is enabled, and returns the value
  34831. that was set.
  34832. @see setDoubleClickReturnValue
  34833. */
  34834. double getDoubleClickReturnValue (bool& isEnabled) const;
  34835. /** Tells the slider whether to keep sending change messages while the user
  34836. is dragging the slider.
  34837. If set to true, a change message will only be sent when the user has
  34838. dragged the slider and let go. If set to false (the default), then messages
  34839. will be continuously sent as they drag it while the mouse button is still
  34840. held down.
  34841. */
  34842. void setChangeNotificationOnlyOnRelease (bool onlyNotifyOnRelease);
  34843. /** This lets you change whether the slider thumb jumps to the mouse position
  34844. when you click.
  34845. By default, this is true. If it's false, then the slider moves with relative
  34846. motion when you drag it.
  34847. This only applies to linear bars, and won't affect two- or three- value
  34848. sliders.
  34849. */
  34850. void setSliderSnapsToMousePosition (bool shouldSnapToMouse);
  34851. /** If enabled, this gives the slider a pop-up bubble which appears while the
  34852. slider is being dragged.
  34853. This can be handy if your slider doesn't have a text-box, so that users can
  34854. see the value just when they're changing it.
  34855. If you pass a component as the parentComponentToUse parameter, the pop-up
  34856. bubble will be added as a child of that component when it's needed. If you
  34857. pass 0, the pop-up will be placed on the desktop instead (note that it's a
  34858. transparent window, so if you're using an OS that can't do transparent windows
  34859. you'll have to add it to a parent component instead).
  34860. */
  34861. void setPopupDisplayEnabled (bool isEnabled,
  34862. Component* parentComponentToUse);
  34863. /** If this is set to true, then right-clicking on the slider will pop-up
  34864. a menu to let the user change the way it works.
  34865. By default this is turned off, but when turned on, the menu will include
  34866. things like velocity sensitivity, and for rotary sliders, whether they
  34867. use a linear or rotary mouse-drag to move them.
  34868. */
  34869. void setPopupMenuEnabled (bool menuEnabled);
  34870. /** This can be used to stop the mouse scroll-wheel from moving the slider.
  34871. By default it's enabled.
  34872. */
  34873. void setScrollWheelEnabled (bool enabled);
  34874. /** Returns a number to indicate which thumb is currently being dragged by the
  34875. mouse.
  34876. This will return 0 for the main thumb, 1 for the minimum-value thumb, 2 for
  34877. the maximum-value thumb, or -1 if none is currently down.
  34878. */
  34879. int getThumbBeingDragged() const { return sliderBeingDragged; }
  34880. /** Callback to indicate that the user is about to start dragging the slider.
  34881. @see SliderListener::sliderDragStarted
  34882. */
  34883. virtual void startedDragging();
  34884. /** Callback to indicate that the user has just stopped dragging the slider.
  34885. @see SliderListener::sliderDragEnded
  34886. */
  34887. virtual void stoppedDragging();
  34888. /** Callback to indicate that the user has just moved the slider.
  34889. @see SliderListener::sliderValueChanged
  34890. */
  34891. virtual void valueChanged();
  34892. /** Subclasses can override this to convert a text string to a value.
  34893. When the user enters something into the text-entry box, this method is
  34894. called to convert it to a value.
  34895. The default routine just tries to convert it to a double.
  34896. @see getTextFromValue
  34897. */
  34898. virtual double getValueFromText (const String& text);
  34899. /** Turns the slider's current value into a text string.
  34900. Subclasses can override this to customise the formatting of the text-entry box.
  34901. The default implementation just turns the value into a string, using
  34902. a number of decimal places based on the range interval. If a suffix string
  34903. has been set using setTextValueSuffix(), this will be appended to the text.
  34904. @see getValueFromText
  34905. */
  34906. virtual const String getTextFromValue (double value);
  34907. /** Sets a suffix to append to the end of the numeric value when it's displayed as
  34908. a string.
  34909. This is used by the default implementation of getTextFromValue(), and is just
  34910. appended to the numeric value. For more advanced formatting, you can override
  34911. getTextFromValue() and do something else.
  34912. */
  34913. void setTextValueSuffix (const String& suffix);
  34914. /** Returns the suffix that was set by setTextValueSuffix(). */
  34915. const String getTextValueSuffix() const;
  34916. /** Allows a user-defined mapping of distance along the slider to its value.
  34917. The default implementation for this performs the skewing operation that
  34918. can be set up in the setSkewFactor() method. Override it if you need
  34919. some kind of custom mapping instead, but make sure you also implement the
  34920. inverse function in valueToProportionOfLength().
  34921. @param proportion a value 0 to 1.0, indicating a distance along the slider
  34922. @returns the slider value that is represented by this position
  34923. @see valueToProportionOfLength
  34924. */
  34925. virtual double proportionOfLengthToValue (double proportion);
  34926. /** Allows a user-defined mapping of value to the position of the slider along its length.
  34927. The default implementation for this performs the skewing operation that
  34928. can be set up in the setSkewFactor() method. Override it if you need
  34929. some kind of custom mapping instead, but make sure you also implement the
  34930. inverse function in proportionOfLengthToValue().
  34931. @param value a valid slider value, between the range of values specified in
  34932. setRange()
  34933. @returns a value 0 to 1.0 indicating the distance along the slider that
  34934. represents this value
  34935. @see proportionOfLengthToValue
  34936. */
  34937. virtual double valueToProportionOfLength (double value);
  34938. /** Returns the X or Y coordinate of a value along the slider's length.
  34939. If the slider is horizontal, this will be the X coordinate of the given
  34940. value, relative to the left of the slider. If it's vertical, then this will
  34941. be the Y coordinate, relative to the top of the slider.
  34942. If the slider is rotary, this will throw an assertion and return 0. If the
  34943. value is out-of-range, it will be constrained to the length of the slider.
  34944. */
  34945. float getPositionOfValue (double value);
  34946. /** This can be overridden to allow the slider to snap to user-definable values.
  34947. If overridden, it will be called when the user tries to move the slider to
  34948. a given position, and allows a subclass to sanity-check this value, possibly
  34949. returning a different value to use instead.
  34950. @param attemptedValue the value the user is trying to enter
  34951. @param userIsDragging true if the user is dragging with the mouse; false if
  34952. they are entering the value using the text box
  34953. @returns the value to use instead
  34954. */
  34955. virtual double snapValue (double attemptedValue, bool userIsDragging);
  34956. /** This can be called to force the text box to update its contents.
  34957. (Not normally needed, as this is done automatically).
  34958. */
  34959. void updateText();
  34960. /** True if the slider moves horizontally. */
  34961. bool isHorizontal() const;
  34962. /** True if the slider moves vertically. */
  34963. bool isVertical() const;
  34964. /** A set of colour IDs to use to change the colour of various aspects of the slider.
  34965. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  34966. methods.
  34967. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  34968. */
  34969. enum ColourIds
  34970. {
  34971. backgroundColourId = 0x1001200, /**< A colour to use to fill the slider's background. */
  34972. thumbColourId = 0x1001300, /**< The colour to draw the thumb with. It's up to the look
  34973. and feel class how this is used. */
  34974. trackColourId = 0x1001310, /**< The colour to draw the groove that the thumb moves along. */
  34975. rotarySliderFillColourId = 0x1001311, /**< For rotary sliders, this colour fills the outer curve. */
  34976. rotarySliderOutlineColourId = 0x1001312, /**< For rotary sliders, this colour is used to draw the outer curve's outline. */
  34977. textBoxTextColourId = 0x1001400, /**< The colour for the text in the text-editor box used for editing the value. */
  34978. textBoxBackgroundColourId = 0x1001500, /**< The background colour for the text-editor box. */
  34979. textBoxHighlightColourId = 0x1001600, /**< The text highlight colour for the text-editor box. */
  34980. textBoxOutlineColourId = 0x1001700 /**< The colour to use for a border around the text-editor box. */
  34981. };
  34982. juce_UseDebuggingNewOperator
  34983. protected:
  34984. /** @internal */
  34985. void labelTextChanged (Label*);
  34986. /** @internal */
  34987. void paint (Graphics& g);
  34988. /** @internal */
  34989. void resized();
  34990. /** @internal */
  34991. void mouseDown (const MouseEvent& e);
  34992. /** @internal */
  34993. void mouseUp (const MouseEvent& e);
  34994. /** @internal */
  34995. void mouseDrag (const MouseEvent& e);
  34996. /** @internal */
  34997. void mouseDoubleClick (const MouseEvent& e);
  34998. /** @internal */
  34999. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  35000. /** @internal */
  35001. void modifierKeysChanged (const ModifierKeys& modifiers);
  35002. /** @internal */
  35003. void buttonClicked (Button* button);
  35004. /** @internal */
  35005. void lookAndFeelChanged();
  35006. /** @internal */
  35007. void enablementChanged();
  35008. /** @internal */
  35009. void focusOfChildComponentChanged (FocusChangeType cause);
  35010. /** @internal */
  35011. void handleAsyncUpdate();
  35012. /** @internal */
  35013. void colourChanged();
  35014. /** @internal */
  35015. void valueChanged (Value& value);
  35016. /** Returns the best number of decimal places to use when displaying numbers.
  35017. This is calculated from the slider's interval setting.
  35018. */
  35019. int getNumDecimalPlacesToDisplay() const throw() { return numDecimalPlaces; }
  35020. private:
  35021. ListenerList <SliderListener> listeners;
  35022. Value currentValue, valueMin, valueMax;
  35023. double lastCurrentValue, lastValueMin, lastValueMax;
  35024. double minimum, maximum, interval, doubleClickReturnValue;
  35025. double valueWhenLastDragged, valueOnMouseDown, skewFactor, lastAngle;
  35026. double velocityModeSensitivity, velocityModeOffset, minMaxDiff;
  35027. int velocityModeThreshold;
  35028. float rotaryStart, rotaryEnd;
  35029. int numDecimalPlaces, mouseXWhenLastDragged, mouseYWhenLastDragged;
  35030. int mouseDragStartX, mouseDragStartY;
  35031. int sliderRegionStart, sliderRegionSize;
  35032. int sliderBeingDragged;
  35033. int pixelsForFullDragExtent;
  35034. Rectangle<int> sliderRect;
  35035. String textSuffix;
  35036. SliderStyle style;
  35037. TextEntryBoxPosition textBoxPos;
  35038. int textBoxWidth, textBoxHeight;
  35039. IncDecButtonMode incDecButtonMode;
  35040. bool editableText : 1, doubleClickToValue : 1;
  35041. bool isVelocityBased : 1, userKeyOverridesVelocity : 1, rotaryStop : 1;
  35042. bool incDecButtonsSideBySide : 1, sendChangeOnlyOnRelease : 1, popupDisplayEnabled : 1;
  35043. bool menuEnabled : 1, menuShown : 1, mouseWasHidden : 1, incDecDragged : 1;
  35044. bool scrollWheelEnabled : 1, snapsToMousePos : 1;
  35045. Label* valueBox;
  35046. Button* incButton;
  35047. Button* decButton;
  35048. ScopedPointer <Component> popupDisplay;
  35049. Component* parentForPopupDisplay;
  35050. float getLinearSliderPos (double value);
  35051. void restoreMouseIfHidden();
  35052. void sendDragStart();
  35053. void sendDragEnd();
  35054. double constrainedValue (double value) const;
  35055. void triggerChangeMessage (bool synchronous);
  35056. bool incDecDragDirectionIsHorizontal() const;
  35057. Slider (const Slider&);
  35058. Slider& operator= (const Slider&);
  35059. };
  35060. #endif // __JUCE_SLIDER_JUCEHEADER__
  35061. /*** End of inlined file: juce_Slider.h ***/
  35062. #endif
  35063. #ifndef __JUCE_SLIDERLISTENER_JUCEHEADER__
  35064. #endif
  35065. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35066. /*** Start of inlined file: juce_TableHeaderComponent.h ***/
  35067. #ifndef __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35068. #define __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35069. class TableHeaderComponent;
  35070. /**
  35071. Receives events from a TableHeaderComponent when columns are resized, moved, etc.
  35072. You can register one of these objects for table events using TableHeaderComponent::addListener()
  35073. and TableHeaderComponent::removeListener().
  35074. @see TableHeaderComponent
  35075. */
  35076. class JUCE_API TableHeaderListener
  35077. {
  35078. public:
  35079. TableHeaderListener() {}
  35080. /** Destructor. */
  35081. virtual ~TableHeaderListener() {}
  35082. /** This is called when some of the table's columns are added, removed, hidden,
  35083. or rearranged.
  35084. */
  35085. virtual void tableColumnsChanged (TableHeaderComponent* tableHeader) = 0;
  35086. /** This is called when one or more of the table's columns are resized.
  35087. */
  35088. virtual void tableColumnsResized (TableHeaderComponent* tableHeader) = 0;
  35089. /** This is called when the column by which the table should be sorted is changed.
  35090. */
  35091. virtual void tableSortOrderChanged (TableHeaderComponent* tableHeader) = 0;
  35092. /** This is called when the user begins or ends dragging one of the columns around.
  35093. When the user starts dragging a column, this is called with the ID of that
  35094. column. When they finish dragging, it is called again with 0 as the ID.
  35095. */
  35096. virtual void tableColumnDraggingChanged (TableHeaderComponent* tableHeader,
  35097. int columnIdNowBeingDragged);
  35098. };
  35099. /**
  35100. A component that displays a strip of column headings for a table, and allows these
  35101. to be resized, dragged around, etc.
  35102. This is just the component that goes at the top of a table. You can use it
  35103. directly for custom components, or to create a simple table, use the
  35104. TableListBox class.
  35105. To use one of these, create it and use addColumn() to add all the columns that you need.
  35106. Each column must be given a unique ID number that's used to refer to it.
  35107. @see TableListBox, TableHeaderListener
  35108. */
  35109. class JUCE_API TableHeaderComponent : public Component,
  35110. private AsyncUpdater
  35111. {
  35112. public:
  35113. /** Creates an empty table header.
  35114. */
  35115. TableHeaderComponent();
  35116. /** Destructor. */
  35117. ~TableHeaderComponent();
  35118. /** A combination of these flags are passed into the addColumn() method to specify
  35119. the properties of a column.
  35120. */
  35121. enum ColumnPropertyFlags
  35122. {
  35123. 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. */
  35124. resizable = 2, /**< If this is set, the column can be resized by dragging it. */
  35125. draggable = 4, /**< If this is set, the column can be dragged around to change its order in the table. */
  35126. appearsOnColumnMenu = 8, /**< If this is set, the column will be shown on the pop-up menu allowing it to be hidden/shown. */
  35127. 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. */
  35128. sortedForwards = 32, /**< If this is set, the column is currently the one by which the table is sorted (forwards). */
  35129. sortedBackwards = 64, /**< If this is set, the column is currently the one by which the table is sorted (backwards). */
  35130. /** This set of default flags is used as the default parameter value in addColumn(). */
  35131. defaultFlags = (visible | resizable | draggable | appearsOnColumnMenu | sortable),
  35132. /** A quick way of combining flags for a column that's not resizable. */
  35133. notResizable = (visible | draggable | appearsOnColumnMenu | sortable),
  35134. /** A quick way of combining flags for a column that's not resizable or sortable. */
  35135. notResizableOrSortable = (visible | draggable | appearsOnColumnMenu),
  35136. /** A quick way of combining flags for a column that's not sortable. */
  35137. notSortable = (visible | resizable | draggable | appearsOnColumnMenu)
  35138. };
  35139. /** Adds a column to the table.
  35140. This will add a column, and asynchronously call the tableColumnsChanged() method of any
  35141. registered listeners.
  35142. @param columnName the name of the new column. It's ok to have two or more columns with the same name
  35143. @param columnId an ID for this column. The ID can be any number apart from 0, but every column must have
  35144. a unique ID. This is used to identify the column later on, after the user may have
  35145. changed the order that they appear in
  35146. @param width the initial width of the column, in pixels
  35147. @param maximumWidth a maximum width that the column can take when the user is resizing it. This only applies
  35148. if the 'resizable' flag is specified for this column
  35149. @param minimumWidth a minimum width that the column can take when the user is resizing it. This only applies
  35150. if the 'resizable' flag is specified for this column
  35151. @param propertyFlags a combination of some of the values from the ColumnPropertyFlags enum, to define the
  35152. properties of this column
  35153. @param insertIndex the index at which the column should be added. A value of 0 puts it at the start (left-hand side)
  35154. and -1 puts it at the end (right-hand size) of the table. Note that the index the index within
  35155. all columns, not just the index amongst those that are currently visible
  35156. */
  35157. void addColumn (const String& columnName,
  35158. int columnId,
  35159. int width,
  35160. int minimumWidth = 30,
  35161. int maximumWidth = -1,
  35162. int propertyFlags = defaultFlags,
  35163. int insertIndex = -1);
  35164. /** Removes a column with the given ID.
  35165. If there is such a column, this will asynchronously call the tableColumnsChanged() method of any
  35166. registered listeners.
  35167. */
  35168. void removeColumn (int columnIdToRemove);
  35169. /** Deletes all columns from the table.
  35170. If there are any columns to remove, this will asynchronously call the tableColumnsChanged() method of any
  35171. registered listeners.
  35172. */
  35173. void removeAllColumns();
  35174. /** Returns the number of columns in the table.
  35175. If onlyCountVisibleColumns is true, this will return the number of visible columns; otherwise it'll
  35176. return the total number of columns, including hidden ones.
  35177. @see isColumnVisible
  35178. */
  35179. int getNumColumns (bool onlyCountVisibleColumns) const;
  35180. /** Returns the name for a column.
  35181. @see setColumnName
  35182. */
  35183. const String getColumnName (int columnId) const;
  35184. /** Changes the name of a column. */
  35185. void setColumnName (int columnId, const String& newName);
  35186. /** Moves a column to a different index in the table.
  35187. @param columnId the column to move
  35188. @param newVisibleIndex the target index for it, from 0 to the number of columns currently visible.
  35189. */
  35190. void moveColumn (int columnId, int newVisibleIndex);
  35191. /** Returns the width of one of the columns.
  35192. */
  35193. int getColumnWidth (int columnId) const;
  35194. /** Changes the width of a column.
  35195. This will cause an asynchronous callback to the tableColumnsResized() method of any registered listeners.
  35196. */
  35197. void setColumnWidth (int columnId, int newWidth);
  35198. /** Shows or hides a column.
  35199. This can cause an asynchronous callback to the tableColumnsChanged() method of any registered listeners.
  35200. @see isColumnVisible
  35201. */
  35202. void setColumnVisible (int columnId, bool shouldBeVisible);
  35203. /** Returns true if this column is currently visible.
  35204. @see setColumnVisible
  35205. */
  35206. bool isColumnVisible (int columnId) const;
  35207. /** Changes the column which is the sort column.
  35208. This can cause an asynchronous callback to the tableSortOrderChanged() method of any registered listeners.
  35209. If this method doesn't actually change the column ID, then no re-sort will take place (you can
  35210. call reSortTable() to force a re-sort to happen if you've modified the table's contents).
  35211. @see getSortColumnId, isSortedForwards, reSortTable
  35212. */
  35213. void setSortColumnId (int columnId, bool sortForwards);
  35214. /** Returns the column ID by which the table is currently sorted, or 0 if it is unsorted.
  35215. @see setSortColumnId, isSortedForwards
  35216. */
  35217. int getSortColumnId() const;
  35218. /** Returns true if the table is currently sorted forwards, or false if it's backwards.
  35219. @see setSortColumnId
  35220. */
  35221. bool isSortedForwards() const;
  35222. /** Triggers a re-sort of the table according to the current sort-column.
  35223. If you modifiy the table's contents, you can call this to signal that the table needs
  35224. to be re-sorted.
  35225. (This doesn't do any sorting synchronously - it just asynchronously sends a call to the
  35226. tableSortOrderChanged() method of any listeners).
  35227. */
  35228. void reSortTable();
  35229. /** Returns the total width of all the visible columns in the table.
  35230. */
  35231. int getTotalWidth() const;
  35232. /** Returns the index of a given column.
  35233. If there's no such column ID, this will return -1.
  35234. If onlyCountVisibleColumns is true, this will return the index amoungst the visible columns;
  35235. otherwise it'll return the index amongst all the columns, including any hidden ones.
  35236. */
  35237. int getIndexOfColumnId (int columnId, bool onlyCountVisibleColumns) const;
  35238. /** Returns the ID of the column at a given index.
  35239. If onlyCountVisibleColumns is true, this will count the index amoungst the visible columns;
  35240. otherwise it'll count it amongst all the columns, including any hidden ones.
  35241. If the index is out-of-range, it'll return 0.
  35242. */
  35243. int getColumnIdOfIndex (int index, bool onlyCountVisibleColumns) const;
  35244. /** Returns the rectangle containing of one of the columns.
  35245. The index is an index from 0 to the number of columns that are currently visible (hidden
  35246. ones are not counted). It returns a rectangle showing the position of the column relative
  35247. to this component's top-left. If the index is out-of-range, an empty rectangle is retrurned.
  35248. */
  35249. const Rectangle<int> getColumnPosition (int index) const;
  35250. /** Finds the column ID at a given x-position in the component.
  35251. If there is a column at this point this returns its ID, or if not, it will return 0.
  35252. */
  35253. int getColumnIdAtX (int xToFind) const;
  35254. /** If set to true, this indicates that the columns should be expanded or shrunk to fill the
  35255. entire width of the component.
  35256. By default this is disabled. Turning it on also means that when resizing a column, those
  35257. on the right will be squashed to fit.
  35258. */
  35259. void setStretchToFitActive (bool shouldStretchToFit);
  35260. /** Returns true if stretch-to-fit has been enabled.
  35261. @see setStretchToFitActive
  35262. */
  35263. bool isStretchToFitActive() const;
  35264. /** If stretch-to-fit is enabled, this will resize all the columns to make them fit into the
  35265. specified width, keeping their relative proportions the same.
  35266. If the minimum widths of the columns are too wide to fit into this space, it may
  35267. actually end up wider.
  35268. */
  35269. void resizeAllColumnsToFit (int targetTotalWidth);
  35270. /** Enables or disables the pop-up menu.
  35271. The default menu allows the user to show or hide columns. You can add custom
  35272. items to this menu by overloading the addMenuItems() and reactToMenuItem() methods.
  35273. By default the menu is enabled.
  35274. @see isPopupMenuActive, addMenuItems, reactToMenuItem
  35275. */
  35276. void setPopupMenuActive (bool hasMenu);
  35277. /** Returns true if the pop-up menu is enabled.
  35278. @see setPopupMenuActive
  35279. */
  35280. bool isPopupMenuActive() const;
  35281. /** Returns a string that encapsulates the table's current layout.
  35282. This can be restored later using restoreFromString(). It saves the order of
  35283. the columns, the currently-sorted column, and the widths.
  35284. @see restoreFromString
  35285. */
  35286. const String toString() const;
  35287. /** Restores the state of the table, based on a string previously created with
  35288. toString().
  35289. @see toString
  35290. */
  35291. void restoreFromString (const String& storedVersion);
  35292. /** Adds a listener to be informed about things that happen to the header. */
  35293. void addListener (TableHeaderListener* newListener);
  35294. /** Removes a previously-registered listener. */
  35295. void removeListener (TableHeaderListener* listenerToRemove);
  35296. /** This can be overridden to handle a mouse-click on one of the column headers.
  35297. The default implementation will use this click to call getSortColumnId() and
  35298. change the sort order.
  35299. */
  35300. virtual void columnClicked (int columnId, const ModifierKeys& mods);
  35301. /** This can be overridden to add custom items to the pop-up menu.
  35302. If you override this, you should call the superclass's method to add its
  35303. column show/hide items, if you want them on the menu as well.
  35304. Then to handle the result, override reactToMenuItem().
  35305. @see reactToMenuItem
  35306. */
  35307. virtual void addMenuItems (PopupMenu& menu, int columnIdClicked);
  35308. /** Override this to handle any custom items that you have added to the
  35309. pop-up menu with an addMenuItems() override.
  35310. If the menuReturnId isn't one of your own custom menu items, you'll need to
  35311. call TableHeaderComponent::reactToMenuItem() to allow the base class to
  35312. handle the items that it had added.
  35313. @see addMenuItems
  35314. */
  35315. virtual void reactToMenuItem (int menuReturnId, int columnIdClicked);
  35316. /** @internal */
  35317. void paint (Graphics& g);
  35318. /** @internal */
  35319. void resized();
  35320. /** @internal */
  35321. void mouseMove (const MouseEvent&);
  35322. /** @internal */
  35323. void mouseEnter (const MouseEvent&);
  35324. /** @internal */
  35325. void mouseExit (const MouseEvent&);
  35326. /** @internal */
  35327. void mouseDown (const MouseEvent&);
  35328. /** @internal */
  35329. void mouseDrag (const MouseEvent&);
  35330. /** @internal */
  35331. void mouseUp (const MouseEvent&);
  35332. /** @internal */
  35333. const MouseCursor getMouseCursor();
  35334. /** Can be overridden for more control over the pop-up menu behaviour. */
  35335. virtual void showColumnChooserMenu (int columnIdClicked);
  35336. juce_UseDebuggingNewOperator
  35337. private:
  35338. struct ColumnInfo
  35339. {
  35340. String name;
  35341. int id, propertyFlags, width, minimumWidth, maximumWidth;
  35342. double lastDeliberateWidth;
  35343. bool isVisible() const;
  35344. };
  35345. OwnedArray <ColumnInfo> columns;
  35346. Array <TableHeaderListener*> listeners;
  35347. ScopedPointer <Component> dragOverlayComp;
  35348. bool columnsChanged, columnsResized, sortChanged, menuActive, stretchToFit;
  35349. int columnIdBeingResized, columnIdBeingDragged, initialColumnWidth;
  35350. int columnIdUnderMouse, draggingColumnOffset, draggingColumnOriginalIndex, lastDeliberateWidth;
  35351. ColumnInfo* getInfoForId (int columnId) const;
  35352. int visibleIndexToTotalIndex (int visibleIndex) const;
  35353. void sendColumnsChanged();
  35354. void handleAsyncUpdate();
  35355. void beginDrag (const MouseEvent&);
  35356. void endDrag (int finalIndex);
  35357. int getResizeDraggerAt (int mouseX) const;
  35358. void updateColumnUnderMouse (int x, int y);
  35359. void resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth);
  35360. TableHeaderComponent (const TableHeaderComponent&);
  35361. TableHeaderComponent operator= (const TableHeaderComponent&);
  35362. };
  35363. #endif // __JUCE_TABLEHEADERCOMPONENT_JUCEHEADER__
  35364. /*** End of inlined file: juce_TableHeaderComponent.h ***/
  35365. #endif
  35366. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35367. /*** Start of inlined file: juce_TableListBox.h ***/
  35368. #ifndef __JUCE_TABLELISTBOX_JUCEHEADER__
  35369. #define __JUCE_TABLELISTBOX_JUCEHEADER__
  35370. /**
  35371. One of these is used by a TableListBox as the data model for the table's contents.
  35372. The virtual methods that you override in this class take care of drawing the
  35373. table cells, and reacting to events.
  35374. @see TableListBox
  35375. */
  35376. class JUCE_API TableListBoxModel
  35377. {
  35378. public:
  35379. TableListBoxModel() {}
  35380. /** Destructor. */
  35381. virtual ~TableListBoxModel() {}
  35382. /** This must return the number of rows currently in the table.
  35383. If the number of rows changes, you must call TableListBox::updateContent() to
  35384. cause it to refresh the list.
  35385. */
  35386. virtual int getNumRows() = 0;
  35387. /** This must draw the background behind one of the rows in the table.
  35388. The graphics context has its origin at the row's top-left, and your method
  35389. should fill the area specified by the width and height parameters.
  35390. */
  35391. virtual void paintRowBackground (Graphics& g,
  35392. int rowNumber,
  35393. int width, int height,
  35394. bool rowIsSelected) = 0;
  35395. /** This must draw one of the cells.
  35396. The graphics context's origin will already be set to the top-left of the cell,
  35397. whose size is specified by (width, height).
  35398. */
  35399. virtual void paintCell (Graphics& g,
  35400. int rowNumber,
  35401. int columnId,
  35402. int width, int height,
  35403. bool rowIsSelected) = 0;
  35404. /** This is used to create or update a custom component to go in a cell.
  35405. Any cell may contain a custom component, or can just be drawn with the paintCell() method
  35406. and handle mouse clicks with cellClicked().
  35407. This method will be called whenever a custom component might need to be updated - e.g.
  35408. when the table is changed, or TableListBox::updateContent() is called.
  35409. If you don't need a custom component for the specified cell, then return 0.
  35410. If you do want a custom component, and the existingComponentToUpdate is null, then
  35411. this method must create a new component suitable for the cell, and return it.
  35412. If the existingComponentToUpdate is non-null, it will be a pointer to a component previously created
  35413. by this method. In this case, the method must either update it to make sure it's correctly representing
  35414. the given cell (which may be different from the one that the component was created for), or it can
  35415. delete this component and return a new one.
  35416. */
  35417. virtual Component* refreshComponentForCell (int rowNumber, int columnId, bool isRowSelected,
  35418. Component* existingComponentToUpdate);
  35419. /** This callback is made when the user clicks on one of the cells in the table.
  35420. The mouse event's coordinates will be relative to the entire table row.
  35421. @see cellDoubleClicked, backgroundClicked
  35422. */
  35423. virtual void cellClicked (int rowNumber, int columnId, const MouseEvent& e);
  35424. /** This callback is made when the user clicks on one of the cells in the table.
  35425. The mouse event's coordinates will be relative to the entire table row.
  35426. @see cellClicked, backgroundClicked
  35427. */
  35428. virtual void cellDoubleClicked (int rowNumber, int columnId, const MouseEvent& e);
  35429. /** This can be overridden to react to the user double-clicking on a part of the list where
  35430. there are no rows.
  35431. @see cellClicked
  35432. */
  35433. virtual void backgroundClicked();
  35434. /** This callback is made when the table's sort order is changed.
  35435. This could be because the user has clicked a column header, or because the
  35436. TableHeaderComponent::setSortColumnId() method was called.
  35437. If you implement this, your method should re-sort the table using the given
  35438. column as the key.
  35439. */
  35440. virtual void sortOrderChanged (int newSortColumnId, bool isForwards);
  35441. /** Returns the best width for one of the columns.
  35442. If you implement this method, you should measure the width of all the items
  35443. in this column, and return the best size.
  35444. Returning 0 means that the column shouldn't be changed.
  35445. This is used by TableListBox::autoSizeColumn() and TableListBox::autoSizeAllColumns().
  35446. */
  35447. virtual int getColumnAutoSizeWidth (int columnId);
  35448. /** Returns a tooltip for a particular cell in the table.
  35449. */
  35450. virtual const String getCellTooltip (int rowNumber, int columnId);
  35451. /** Override this to be informed when rows are selected or deselected.
  35452. @see ListBox::selectedRowsChanged()
  35453. */
  35454. virtual void selectedRowsChanged (int lastRowSelected);
  35455. /** Override this to be informed when the delete key is pressed.
  35456. @see ListBox::deleteKeyPressed()
  35457. */
  35458. virtual void deleteKeyPressed (int lastRowSelected);
  35459. /** Override this to be informed when the return key is pressed.
  35460. @see ListBox::returnKeyPressed()
  35461. */
  35462. virtual void returnKeyPressed (int lastRowSelected);
  35463. /** Override this to be informed when the list is scrolled.
  35464. This might be caused by the user moving the scrollbar, or by programmatic changes
  35465. to the list position.
  35466. */
  35467. virtual void listWasScrolled();
  35468. /** To allow rows from your table to be dragged-and-dropped, implement this method.
  35469. If this returns a non-empty name then when the user drags a row, the table will try to
  35470. find a DragAndDropContainer in its parent hierarchy, and will use it to trigger a
  35471. drag-and-drop operation, using this string as the source description, and the listbox
  35472. itself as the source component.
  35473. @see DragAndDropContainer::startDragging
  35474. */
  35475. virtual const String getDragSourceDescription (const SparseSet<int>& currentlySelectedRows);
  35476. };
  35477. /**
  35478. A table of cells, using a TableHeaderComponent as its header.
  35479. This component makes it easy to create a table by providing a TableListBoxModel as
  35480. the data source.
  35481. @see TableListBoxModel, TableHeaderComponent
  35482. */
  35483. class JUCE_API TableListBox : public ListBox,
  35484. private ListBoxModel,
  35485. private TableHeaderListener
  35486. {
  35487. public:
  35488. /** Creates a TableListBox.
  35489. The model pointer passed-in can be null, in which case you can set it later
  35490. with setModel().
  35491. */
  35492. TableListBox (const String& componentName,
  35493. TableListBoxModel* model);
  35494. /** Destructor. */
  35495. ~TableListBox();
  35496. /** Changes the TableListBoxModel that is being used for this table.
  35497. */
  35498. void setModel (TableListBoxModel* newModel);
  35499. /** Returns the model currently in use. */
  35500. TableListBoxModel* getModel() const { return model; }
  35501. /** Returns the header component being used in this table. */
  35502. TableHeaderComponent* getHeader() const { return header; }
  35503. /** Changes the height of the table header component.
  35504. @see getHeaderHeight
  35505. */
  35506. void setHeaderHeight (int newHeight);
  35507. /** Returns the height of the table header.
  35508. @see setHeaderHeight
  35509. */
  35510. int getHeaderHeight() const;
  35511. /** Resizes a column to fit its contents.
  35512. This uses TableListBoxModel::getColumnAutoSizeWidth() to find the best width,
  35513. and applies that to the column.
  35514. @see autoSizeAllColumns, TableHeaderComponent::setColumnWidth
  35515. */
  35516. void autoSizeColumn (int columnId);
  35517. /** Calls autoSizeColumn() for all columns in the table. */
  35518. void autoSizeAllColumns();
  35519. /** Enables or disables the auto size options on the popup menu.
  35520. By default, these are enabled.
  35521. */
  35522. void setAutoSizeMenuOptionShown (bool shouldBeShown);
  35523. /** True if the auto-size options should be shown on the menu.
  35524. @see setAutoSizeMenuOptionsShown
  35525. */
  35526. bool isAutoSizeMenuOptionShown() const;
  35527. /** Returns the position of one of the cells in the table.
  35528. If relativeToComponentTopLeft is true, the co-ordinates are relative to
  35529. the table component's top-left. The row number isn't checked to see if it's
  35530. in-range, but the column ID must exist or this will return an empty rectangle.
  35531. If relativeToComponentTopLeft is false, the co-ords are relative to the
  35532. top-left of the table's top-left cell.
  35533. */
  35534. const Rectangle<int> getCellPosition (int columnId, int rowNumber,
  35535. bool relativeToComponentTopLeft) const;
  35536. /** Returns the component that currently represents a given cell.
  35537. If the component for this cell is off-screen or if the position is out-of-range,
  35538. this may return 0.
  35539. @see getCellPosition
  35540. */
  35541. Component* getCellComponent (int columnId, int rowNumber) const;
  35542. /** Scrolls horizontally if necessary to make sure that a particular column is visible.
  35543. @see ListBox::scrollToEnsureRowIsOnscreen
  35544. */
  35545. void scrollToEnsureColumnIsOnscreen (int columnId);
  35546. /** @internal */
  35547. int getNumRows();
  35548. /** @internal */
  35549. void paintListBoxItem (int, Graphics&, int, int, bool);
  35550. /** @internal */
  35551. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  35552. /** @internal */
  35553. void selectedRowsChanged (int lastRowSelected);
  35554. /** @internal */
  35555. void deleteKeyPressed (int currentSelectedRow);
  35556. /** @internal */
  35557. void returnKeyPressed (int currentSelectedRow);
  35558. /** @internal */
  35559. void backgroundClicked();
  35560. /** @internal */
  35561. void listWasScrolled();
  35562. /** @internal */
  35563. void tableColumnsChanged (TableHeaderComponent*);
  35564. /** @internal */
  35565. void tableColumnsResized (TableHeaderComponent*);
  35566. /** @internal */
  35567. void tableSortOrderChanged (TableHeaderComponent*);
  35568. /** @internal */
  35569. void tableColumnDraggingChanged (TableHeaderComponent*, int);
  35570. /** @internal */
  35571. void resized();
  35572. juce_UseDebuggingNewOperator
  35573. private:
  35574. TableHeaderComponent* header;
  35575. TableListBoxModel* model;
  35576. int columnIdNowBeingDragged;
  35577. bool autoSizeOptionsShown;
  35578. void updateColumnComponents() const;
  35579. TableListBox (const TableListBox&);
  35580. TableListBox& operator= (const TableListBox&);
  35581. };
  35582. #endif // __JUCE_TABLELISTBOX_JUCEHEADER__
  35583. /*** End of inlined file: juce_TableListBox.h ***/
  35584. #endif
  35585. #ifndef __JUCE_TEXTEDITOR_JUCEHEADER__
  35586. #endif
  35587. #ifndef __JUCE_TOOLBAR_JUCEHEADER__
  35588. #endif
  35589. #ifndef __JUCE_TOOLBARITEMCOMPONENT_JUCEHEADER__
  35590. #endif
  35591. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35592. /*** Start of inlined file: juce_ToolbarItemFactory.h ***/
  35593. #ifndef __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35594. #define __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35595. /**
  35596. A factory object which can create ToolbarItemComponent objects.
  35597. A subclass of ToolbarItemFactory publishes a set of types of toolbar item
  35598. that it can create.
  35599. Each type of item is identified by a unique ID, and multiple instances of an
  35600. item type can exist at once (even on the same toolbar, e.g. spacers or separator
  35601. bars).
  35602. @see Toolbar, ToolbarItemComponent, ToolbarButton
  35603. */
  35604. class JUCE_API ToolbarItemFactory
  35605. {
  35606. public:
  35607. ToolbarItemFactory();
  35608. /** Destructor. */
  35609. virtual ~ToolbarItemFactory();
  35610. /** A set of reserved item ID values, used for the built-in item types.
  35611. */
  35612. enum SpecialItemIds
  35613. {
  35614. separatorBarId = -1, /**< The item ID for a vertical (or horizontal) separator bar that
  35615. can be placed between sets of items to break them into groups. */
  35616. spacerId = -2, /**< The item ID for a fixed-width space that can be placed between
  35617. items.*/
  35618. flexibleSpacerId = -3 /**< The item ID for a gap that pushes outwards against the things on
  35619. either side of it, filling any available space. */
  35620. };
  35621. /** Must return a list of the IDs for all the item types that this factory can create.
  35622. The ids should be added to the array that is passed-in.
  35623. An item ID can be any integer you choose, except for 0, which is considered a null ID,
  35624. and the predefined IDs in the SpecialItemIds enum.
  35625. You should also add the built-in types (separatorBarId, spacerId and flexibleSpacerId)
  35626. to this list if you want your toolbar to be able to contain those items.
  35627. The list returned here is used by the ToolbarItemPalette class to obtain its list
  35628. of available items, and their order on the palette will reflect the order in which
  35629. they appear on this list.
  35630. @see ToolbarItemPalette
  35631. */
  35632. virtual void getAllToolbarItemIds (Array <int>& ids) = 0;
  35633. /** Must return the set of items that should be added to a toolbar as its default set.
  35634. This method is used by Toolbar::addDefaultItems() to determine which items to
  35635. create.
  35636. The items that your method adds to the array that is passed-in will be added to the
  35637. toolbar in the same order. Items can appear in the list more than once.
  35638. */
  35639. virtual void getDefaultItemSet (Array <int>& ids) = 0;
  35640. /** Must create an instance of one of the items that the factory lists in its
  35641. getAllToolbarItemIds() method.
  35642. The itemId parameter can be any of the values listed by your getAllToolbarItemIds()
  35643. method, except for the built-in item types from the SpecialItemIds enum, which
  35644. are created internally by the toolbar code.
  35645. Try not to keep a pointer to the object that is returned, as it will be deleted
  35646. automatically by the toolbar, and remember that multiple instances of the same
  35647. item type are likely to exist at the same time.
  35648. */
  35649. virtual ToolbarItemComponent* createItem (int itemId) = 0;
  35650. };
  35651. #endif // __JUCE_TOOLBARITEMFACTORY_JUCEHEADER__
  35652. /*** End of inlined file: juce_ToolbarItemFactory.h ***/
  35653. #endif
  35654. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35655. /*** Start of inlined file: juce_ToolbarItemPalette.h ***/
  35656. #ifndef __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35657. #define __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35658. /**
  35659. A component containing a list of toolbar items, which the user can drag onto
  35660. a toolbar to add them.
  35661. You can use this class directly, but it's a lot easier to call Toolbar::showCustomisationDialog(),
  35662. which automatically shows one of these in a dialog box with lots of extra controls.
  35663. @see Toolbar
  35664. */
  35665. class JUCE_API ToolbarItemPalette : public Component,
  35666. public DragAndDropContainer
  35667. {
  35668. public:
  35669. /** Creates a palette of items for a given factory, with the aim of adding them
  35670. to the specified toolbar.
  35671. The ToolbarItemFactory::getAllToolbarItemIds() method is used to create the
  35672. set of items that are shown in this palette.
  35673. The toolbar and factory must not be deleted while this object exists.
  35674. */
  35675. ToolbarItemPalette (ToolbarItemFactory& factory,
  35676. Toolbar* toolbar);
  35677. /** Destructor. */
  35678. ~ToolbarItemPalette();
  35679. /** @internal */
  35680. void resized();
  35681. juce_UseDebuggingNewOperator
  35682. private:
  35683. ToolbarItemFactory& factory;
  35684. Toolbar* toolbar;
  35685. Viewport* viewport;
  35686. friend class Toolbar;
  35687. void replaceComponent (ToolbarItemComponent* comp);
  35688. ToolbarItemPalette (const ToolbarItemPalette&);
  35689. ToolbarItemPalette& operator= (const ToolbarItemPalette&);
  35690. };
  35691. #endif // __JUCE_TOOLBARITEMPALETTE_JUCEHEADER__
  35692. /*** End of inlined file: juce_ToolbarItemPalette.h ***/
  35693. #endif
  35694. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35695. /*** Start of inlined file: juce_TreeView.h ***/
  35696. #ifndef __JUCE_TREEVIEW_JUCEHEADER__
  35697. #define __JUCE_TREEVIEW_JUCEHEADER__
  35698. /*** Start of inlined file: juce_FileDragAndDropTarget.h ***/
  35699. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35700. #define __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35701. /**
  35702. Components derived from this class can have files dropped onto them by an external application.
  35703. @see DragAndDropContainer
  35704. */
  35705. class JUCE_API FileDragAndDropTarget
  35706. {
  35707. public:
  35708. /** Destructor. */
  35709. virtual ~FileDragAndDropTarget() {}
  35710. /** Callback to check whether this target is interested in the set of files being offered.
  35711. Note that this will be called repeatedly when the user is dragging the mouse around over your
  35712. component, so don't do anything time-consuming in here, like opening the files to have a look
  35713. inside them!
  35714. @param files the set of (absolute) pathnames of the files that the user is dragging
  35715. @returns true if this component wants to receive the other callbacks regarging this
  35716. type of object; if it returns false, no other callbacks will be made.
  35717. */
  35718. virtual bool isInterestedInFileDrag (const StringArray& files) = 0;
  35719. /** Callback to indicate that some files are being dragged over this component.
  35720. This gets called when the user moves the mouse into this component while dragging.
  35721. Use this callback as a trigger to make your component repaint itself to give the
  35722. user feedback about whether the files can be dropped here or not.
  35723. @param files the set of (absolute) pathnames of the files that the user is dragging
  35724. @param x the mouse x position, relative to this component
  35725. @param y the mouse y position, relative to this component
  35726. */
  35727. virtual void fileDragEnter (const StringArray& files, int x, int y);
  35728. /** Callback to indicate that the user is dragging some files over this component.
  35729. This gets called when the user moves the mouse over this component while dragging.
  35730. Normally overriding itemDragEnter() and itemDragExit() are enough, but
  35731. this lets you know what happens in-between.
  35732. @param files the set of (absolute) pathnames of the files that the user is dragging
  35733. @param x the mouse x position, relative to this component
  35734. @param y the mouse y position, relative to this component
  35735. */
  35736. virtual void fileDragMove (const StringArray& files, int x, int y);
  35737. /** Callback to indicate that the mouse has moved away from this component.
  35738. This gets called when the user moves the mouse out of this component while dragging
  35739. the files.
  35740. If you've used fileDragEnter() to repaint your component and give feedback, use this
  35741. as a signal to repaint it in its normal state.
  35742. @param files the set of (absolute) pathnames of the files that the user is dragging
  35743. */
  35744. virtual void fileDragExit (const StringArray& files);
  35745. /** Callback to indicate that the user has dropped the files onto this component.
  35746. When the user drops the files, this get called, and you can use the files in whatever
  35747. way is appropriate.
  35748. Note that after this is called, the fileDragExit method may not be called, so you should
  35749. clean up in here if there's anything you need to do when the drag finishes.
  35750. @param files the set of (absolute) pathnames of the files that the user is dragging
  35751. @param x the mouse x position, relative to this component
  35752. @param y the mouse y position, relative to this component
  35753. */
  35754. virtual void filesDropped (const StringArray& files, int x, int y) = 0;
  35755. };
  35756. #endif // __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  35757. /*** End of inlined file: juce_FileDragAndDropTarget.h ***/
  35758. class TreeView;
  35759. /**
  35760. An item in a treeview.
  35761. A TreeViewItem can either be a leaf-node in the tree, or it can contain its
  35762. own sub-items.
  35763. To implement an item that contains sub-items, override the itemOpennessChanged()
  35764. method so that when it is opened, it adds the new sub-items to itself using the
  35765. addSubItem method. Depending on the nature of the item it might choose to only
  35766. do this the first time it's opened, or it might want to refresh itself each time.
  35767. It also has the option of deleting its sub-items when it is closed, or leaving them
  35768. in place.
  35769. */
  35770. class JUCE_API TreeViewItem
  35771. {
  35772. public:
  35773. /** Constructor. */
  35774. TreeViewItem();
  35775. /** Destructor. */
  35776. virtual ~TreeViewItem();
  35777. /** Returns the number of sub-items that have been added to this item.
  35778. Note that this doesn't mean much if the node isn't open.
  35779. @see getSubItem, mightContainSubItems, addSubItem
  35780. */
  35781. int getNumSubItems() const throw();
  35782. /** Returns one of the item's sub-items.
  35783. Remember that the object returned might get deleted at any time when its parent
  35784. item is closed or refreshed, depending on the nature of the items you're using.
  35785. @see getNumSubItems
  35786. */
  35787. TreeViewItem* getSubItem (int index) const throw();
  35788. /** Removes any sub-items. */
  35789. void clearSubItems();
  35790. /** Adds a sub-item.
  35791. @param newItem the object to add to the item's sub-item list. Once added, these can be
  35792. found using getSubItem(). When the items are later removed with
  35793. removeSubItem() (or when this item is deleted), they will be deleted.
  35794. @param insertPosition the index which the new item should have when it's added. If this
  35795. value is less than 0, the item will be added to the end of the list.
  35796. */
  35797. void addSubItem (TreeViewItem* newItem, int insertPosition = -1);
  35798. /** Removes one of the sub-items.
  35799. @param index the item to remove
  35800. @param deleteItem if true, the item that is removed will also be deleted.
  35801. */
  35802. void removeSubItem (int index, bool deleteItem = true);
  35803. /** Returns the TreeView to which this item belongs. */
  35804. TreeView* getOwnerView() const throw() { return ownerView; }
  35805. /** Returns the item within which this item is contained. */
  35806. TreeViewItem* getParentItem() const throw() { return parentItem; }
  35807. /** True if this item is currently open in the treeview. */
  35808. bool isOpen() const throw();
  35809. /** Opens or closes the item.
  35810. When opened or closed, the item's itemOpennessChanged() method will be called,
  35811. and a subclass should use this callback to create and add any sub-items that
  35812. it needs to.
  35813. @see itemOpennessChanged, mightContainSubItems
  35814. */
  35815. void setOpen (bool shouldBeOpen);
  35816. /** True if this item is currently selected.
  35817. Use this when painting the node, to decide whether to draw it as selected or not.
  35818. */
  35819. bool isSelected() const throw();
  35820. /** Selects or deselects the item.
  35821. This will cause a callback to itemSelectionChanged()
  35822. */
  35823. void setSelected (bool shouldBeSelected,
  35824. bool deselectOtherItemsFirst);
  35825. /** Returns the rectangle that this item occupies.
  35826. If relativeToTreeViewTopLeft is true, the co-ordinates are relative to the
  35827. top-left of the TreeView comp, so this will depend on the scroll-position of
  35828. the tree. If false, it is relative to the top-left of the topmost item in the
  35829. tree (so this would be unaffected by scrolling the view).
  35830. */
  35831. const Rectangle<int> getItemPosition (bool relativeToTreeViewTopLeft) const throw();
  35832. /** Sends a signal to the treeview to make it refresh itself.
  35833. Call this if your items have changed and you want the tree to update to reflect
  35834. this.
  35835. */
  35836. void treeHasChanged() const throw();
  35837. /** Sends a repaint message to redraw just this item.
  35838. Note that you should only call this if you want to repaint a superficial change. If
  35839. you're altering the tree's nodes, you should instead call treeHasChanged().
  35840. */
  35841. void repaintItem() const;
  35842. /** Returns the row number of this item in the tree.
  35843. The row number of an item will change according to which items are open.
  35844. @see TreeView::getNumRowsInTree(), TreeView::getItemOnRow()
  35845. */
  35846. int getRowNumberInTree() const throw();
  35847. /** Returns true if all the item's parent nodes are open.
  35848. This is useful to check whether the item might actually be visible or not.
  35849. */
  35850. bool areAllParentsOpen() const throw();
  35851. /** Changes whether lines are drawn to connect any sub-items to this item.
  35852. By default, line-drawing is turned on.
  35853. */
  35854. void setLinesDrawnForSubItems (bool shouldDrawLines) throw();
  35855. /** Tells the tree whether this item can potentially be opened.
  35856. If your item could contain sub-items, this should return true; if it returns
  35857. false then the tree will not try to open the item. This determines whether or
  35858. not the item will be drawn with a 'plus' button next to it.
  35859. */
  35860. virtual bool mightContainSubItems() = 0;
  35861. /** Returns a string to uniquely identify this item.
  35862. If you're planning on using the TreeView::getOpennessState() method, then
  35863. these strings will be used to identify which nodes are open. The string
  35864. should be unique amongst the item's sibling items, but it's ok for there
  35865. to be duplicates at other levels of the tree.
  35866. If you're not going to store the state, then it's ok not to bother implementing
  35867. this method.
  35868. */
  35869. virtual const String getUniqueName() const;
  35870. /** Called when an item is opened or closed.
  35871. When setOpen() is called and the item has specified that it might
  35872. have sub-items with the mightContainSubItems() method, this method
  35873. is called to let the item create or manage its sub-items.
  35874. So when this is called with isNowOpen set to true (i.e. when the item is being
  35875. opened), a subclass might choose to use clearSubItems() and addSubItem() to
  35876. refresh its sub-item list.
  35877. When this is called with isNowOpen set to false, the subclass might want
  35878. to use clearSubItems() to save on space, or it might choose to leave them,
  35879. depending on the nature of the tree.
  35880. You could also use this callback as a trigger to start a background process
  35881. which asynchronously creates sub-items and adds them, if that's more
  35882. appropriate for the task in hand.
  35883. @see mightContainSubItems
  35884. */
  35885. virtual void itemOpennessChanged (bool isNowOpen);
  35886. /** Must return the width required by this item.
  35887. If your item needs to have a particular width in pixels, return that value; if
  35888. you'd rather have it just fill whatever space is available in the treeview,
  35889. return -1.
  35890. If all your items return -1, no horizontal scrollbar will be shown, but if any
  35891. items have fixed widths and extend beyond the width of the treeview, a
  35892. scrollbar will appear.
  35893. Each item can be a different width, but if they change width, you should call
  35894. treeHasChanged() to update the tree.
  35895. */
  35896. virtual int getItemWidth() const { return -1; }
  35897. /** Must return the height required by this item.
  35898. This is the height in pixels that the item will take up. Items in the tree
  35899. can be different heights, but if they change height, you should call
  35900. treeHasChanged() to update the tree.
  35901. */
  35902. virtual int getItemHeight() const { return 20; }
  35903. /** You can override this method to return false if you don't want to allow the
  35904. user to select this item.
  35905. */
  35906. virtual bool canBeSelected() const { return true; }
  35907. /** Creates a component that will be used to represent this item.
  35908. You don't have to implement this method - if it returns 0 then no component
  35909. will be used for the item, and you can just draw it using the paintItem()
  35910. callback. But if you do return a component, it will be positioned in the
  35911. treeview so that it can be used to represent this item.
  35912. The component returned will be managed by the treeview, so always return
  35913. a new component, and don't keep a reference to it, as the treeview will
  35914. delete it later when it goes off the screen or is no longer needed. Also
  35915. bear in mind that if the component keeps a reference to the item that
  35916. created it, that item could be deleted before the component. Its position
  35917. and size will be completely managed by the tree, so don't attempt to move it
  35918. around.
  35919. Something you may want to do with your component is to give it a pointer to
  35920. the TreeView that created it. This is perfectly safe, and there's no danger
  35921. of it becoming a dangling pointer because the TreeView will always delete
  35922. the component before it is itself deleted.
  35923. As long as you stick to these rules you can return whatever kind of
  35924. component you like. It's most useful if you're doing things like drag-and-drop
  35925. of items, or want to use a Label component to edit item names, etc.
  35926. */
  35927. virtual Component* createItemComponent() { return 0; }
  35928. /** Draws the item's contents.
  35929. You can choose to either implement this method and draw each item, or you
  35930. can use createItemComponent() to create a component that will represent the
  35931. item.
  35932. If all you need in your tree is to be able to draw the items and detect when
  35933. the user selects or double-clicks one of them, it's probably enough to
  35934. use paintItem(), itemClicked() and itemDoubleClicked(). If you need more
  35935. complicated interactions, you may need to use createItemComponent() instead.
  35936. @param g the graphics context to draw into
  35937. @param width the width of the area available for drawing
  35938. @param height the height of the area available for drawing
  35939. */
  35940. virtual void paintItem (Graphics& g, int width, int height);
  35941. /** Draws the item's open/close button.
  35942. If you don't implement this method, the default behaviour is to
  35943. call LookAndFeel::drawTreeviewPlusMinusBox(), but you can override
  35944. it for custom effects.
  35945. */
  35946. virtual void paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver);
  35947. /** Called when the user clicks on this item.
  35948. If you're using createItemComponent() to create a custom component for the
  35949. item, the mouse-clicks might not make it through to the treeview, but this
  35950. is how you find out about clicks when just drawing each item individually.
  35951. The associated mouse-event details are passed in, so you can find out about
  35952. which button, where it was, etc.
  35953. @see itemDoubleClicked
  35954. */
  35955. virtual void itemClicked (const MouseEvent& e);
  35956. /** Called when the user double-clicks on this item.
  35957. If you're using createItemComponent() to create a custom component for the
  35958. item, the mouse-clicks might not make it through to the treeview, but this
  35959. is how you find out about clicks when just drawing each item individually.
  35960. The associated mouse-event details are passed in, so you can find out about
  35961. which button, where it was, etc.
  35962. If not overridden, the base class method here will open or close the item as
  35963. if the 'plus' button had been clicked.
  35964. @see itemClicked
  35965. */
  35966. virtual void itemDoubleClicked (const MouseEvent& e);
  35967. /** Called when the item is selected or deselected.
  35968. Use this if you want to do something special when the item's selectedness
  35969. changes. By default it'll get repainted when this happens.
  35970. */
  35971. virtual void itemSelectionChanged (bool isNowSelected);
  35972. /** The item can return a tool tip string here if it wants to.
  35973. @see TooltipClient
  35974. */
  35975. virtual const String getTooltip();
  35976. /** To allow items from your treeview to be dragged-and-dropped, implement this method.
  35977. If this returns a non-empty name then when the user drags an item, the treeview will
  35978. try to find a DragAndDropContainer in its parent hierarchy, and will use it to trigger
  35979. a drag-and-drop operation, using this string as the source description, with the treeview
  35980. itself as the source component.
  35981. If you need more complex drag-and-drop behaviour, you can use custom components for
  35982. the items, and use those to trigger the drag.
  35983. To accept drag-and-drop in your tree, see isInterestedInDragSource(),
  35984. isInterestedInFileDrag(), etc.
  35985. @see DragAndDropContainer::startDragging
  35986. */
  35987. virtual const String getDragSourceDescription();
  35988. /** If you want your item to be able to have files drag-and-dropped onto it, implement this
  35989. method and return true.
  35990. If you return true and allow some files to be dropped, you'll also need to implement the
  35991. filesDropped() method to do something with them.
  35992. Note that this will be called often, so make your implementation very quick! There's
  35993. certainly no time to try opening the files and having a think about what's inside them!
  35994. For responding to internal drag-and-drop of other types of object, see isInterestedInDragSource().
  35995. @see FileDragAndDropTarget::isInterestedInFileDrag, isInterestedInDragSource
  35996. */
  35997. virtual bool isInterestedInFileDrag (const StringArray& files);
  35998. /** When files are dropped into this item, this callback is invoked.
  35999. For this to work, you'll need to have also implemented isInterestedInFileDrag().
  36000. The insertIndex value indicates where in the list of sub-items the files were dropped.
  36001. @see FileDragAndDropTarget::filesDropped, isInterestedInFileDrag
  36002. */
  36003. virtual void filesDropped (const StringArray& files, int insertIndex);
  36004. /** If you want your item to act as a DragAndDropTarget, implement this method and return true.
  36005. If you implement this method, you'll also need to implement itemDropped() in order to handle
  36006. the items when they are dropped.
  36007. To respond to drag-and-drop of files from external applications, see isInterestedInFileDrag().
  36008. @see DragAndDropTarget::isInterestedInDragSource, itemDropped
  36009. */
  36010. virtual bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  36011. /** When a things are dropped into this item, this callback is invoked.
  36012. For this to work, you need to have also implemented isInterestedInDragSource().
  36013. The insertIndex value indicates where in the list of sub-items the new items should be placed.
  36014. @see isInterestedInDragSource, DragAndDropTarget::itemDropped
  36015. */
  36016. virtual void itemDropped (const String& sourceDescription, Component* sourceComponent, int insertIndex);
  36017. /** Sets a flag to indicate that the item wants to be allowed
  36018. to draw all the way across to the left edge of the treeview.
  36019. By default this is false, which means that when the paintItem()
  36020. method is called, its graphics context is clipped to only allow
  36021. drawing within the item's rectangle. If this flag is set to true,
  36022. then the graphics context isn't clipped on its left side, so it
  36023. can draw all the way across to the left margin. Note that the
  36024. context will still have its origin in the same place though, so
  36025. the coordinates of anything to its left will be negative. It's
  36026. mostly useful if you want to draw a wider bar behind the
  36027. highlighted item.
  36028. */
  36029. void setDrawsInLeftMargin (bool canDrawInLeftMargin) throw();
  36030. /** Saves the current state of open/closed nodes so it can be restored later.
  36031. This takes a snapshot of which sub-nodes have been explicitly opened or closed,
  36032. and records it as XML. To identify node objects it uses the
  36033. TreeViewItem::getUniqueName() method to create named paths. This
  36034. means that the same state of open/closed nodes can be restored to a
  36035. completely different instance of the tree, as long as it contains nodes
  36036. whose unique names are the same.
  36037. You'd normally want to use TreeView::getOpennessState() rather than call it
  36038. for a specific item, but this can be handy if you need to briefly save the state
  36039. for a section of the tree.
  36040. The caller is responsible for deleting the object that is returned.
  36041. @see TreeView::getOpennessState, restoreOpennessState
  36042. */
  36043. XmlElement* getOpennessState() const throw();
  36044. /** Restores the openness of this item and all its sub-items from a saved state.
  36045. See TreeView::restoreOpennessState for more details.
  36046. You'd normally want to use TreeView::restoreOpennessState() rather than call it
  36047. for a specific item, but this can be handy if you need to briefly save the state
  36048. for a section of the tree.
  36049. @see TreeView::restoreOpennessState, getOpennessState
  36050. */
  36051. void restoreOpennessState (const XmlElement& xml) throw();
  36052. /** Returns the index of this item in its parent's sub-items. */
  36053. int getIndexInParent() const throw();
  36054. /** Returns true if this item is the last of its parent's sub-itens. */
  36055. bool isLastOfSiblings() const throw();
  36056. /** Creates a string that can be used to uniquely retrieve this item in the tree.
  36057. The string that is returned can be passed to TreeView::findItemFromIdentifierString().
  36058. The string takes the form of a path, constructed from the getUniqueName() of this
  36059. item and all its parents, so these must all be correctly implemented for it to work.
  36060. @see TreeView::findItemFromIdentifierString, getUniqueName
  36061. */
  36062. const String getItemIdentifierString() const;
  36063. juce_UseDebuggingNewOperator
  36064. private:
  36065. TreeView* ownerView;
  36066. TreeViewItem* parentItem;
  36067. OwnedArray <TreeViewItem> subItems;
  36068. int y, itemHeight, totalHeight, itemWidth, totalWidth;
  36069. int uid;
  36070. bool selected : 1;
  36071. bool redrawNeeded : 1;
  36072. bool drawLinesInside : 1;
  36073. bool drawsInLeftMargin : 1;
  36074. unsigned int openness : 2;
  36075. friend class TreeView;
  36076. friend class TreeViewContentComponent;
  36077. void updatePositions (int newY);
  36078. int getIndentX() const throw();
  36079. void setOwnerView (TreeView* newOwner) throw();
  36080. void paintRecursively (Graphics& g, int width);
  36081. TreeViewItem* getTopLevelItem() throw();
  36082. TreeViewItem* findItemRecursively (int y) throw();
  36083. TreeViewItem* getDeepestOpenParentItem() throw();
  36084. int getNumRows() const throw();
  36085. TreeViewItem* getItemOnRow (int index) throw();
  36086. void deselectAllRecursively();
  36087. int countSelectedItemsRecursively() const throw();
  36088. TreeViewItem* getSelectedItemWithIndex (int index) throw();
  36089. TreeViewItem* getNextVisibleItem (bool recurse) const throw();
  36090. TreeViewItem* findItemFromIdentifierString (const String& identifierString);
  36091. TreeViewItem (const TreeViewItem&);
  36092. TreeViewItem& operator= (const TreeViewItem&);
  36093. };
  36094. /**
  36095. A tree-view component.
  36096. Use one of these to hold and display a structure of TreeViewItem objects.
  36097. */
  36098. class JUCE_API TreeView : public Component,
  36099. public SettableTooltipClient,
  36100. public FileDragAndDropTarget,
  36101. public DragAndDropTarget,
  36102. private AsyncUpdater
  36103. {
  36104. public:
  36105. /** Creates an empty treeview.
  36106. Once you've got a treeview component, you'll need to give it something to
  36107. display, using the setRootItem() method.
  36108. */
  36109. TreeView (const String& componentName = String::empty);
  36110. /** Destructor. */
  36111. ~TreeView();
  36112. /** Sets the item that is displayed in the treeview.
  36113. A tree has a single root item which contains as many sub-items as it needs. If
  36114. you want the tree to contain a number of root items, you should still use a single
  36115. root item above these, but hide it using setRootItemVisible().
  36116. You can pass in 0 to this method to clear the tree and remove its current root item.
  36117. The object passed in will not be deleted by the treeview, it's up to the caller
  36118. to delete it when no longer needed. BUT make absolutely sure that you don't delete
  36119. this item until you've removed it from the tree, either by calling setRootItem (0),
  36120. or by deleting the tree first. You can also use deleteRootItem() as a quick way
  36121. to delete it.
  36122. */
  36123. void setRootItem (TreeViewItem* newRootItem);
  36124. /** Returns the tree's root item.
  36125. This will be the last object passed to setRootItem(), or 0 if none has been set.
  36126. */
  36127. TreeViewItem* getRootItem() const throw() { return rootItem; }
  36128. /** This will remove and delete the current root item.
  36129. It's a convenient way of deleting the item and calling setRootItem (0).
  36130. */
  36131. void deleteRootItem();
  36132. /** Changes whether the tree's root item is shown or not.
  36133. If the root item is hidden, only its sub-items will be shown in the treeview - this
  36134. lets you make the tree look as if it's got many root items. If it's hidden, this call
  36135. will also make sure the root item is open (otherwise the treeview would look empty).
  36136. */
  36137. void setRootItemVisible (bool shouldBeVisible);
  36138. /** Returns true if the root item is visible.
  36139. @see setRootItemVisible
  36140. */
  36141. bool isRootItemVisible() const throw() { return rootItemVisible; }
  36142. /** Sets whether items are open or closed by default.
  36143. Normally, items are closed until the user opens them, but you can use this
  36144. to make them default to being open until explicitly closed.
  36145. @see areItemsOpenByDefault
  36146. */
  36147. void setDefaultOpenness (bool isOpenByDefault);
  36148. /** Returns true if the tree's items default to being open.
  36149. @see setDefaultOpenness
  36150. */
  36151. bool areItemsOpenByDefault() const throw() { return defaultOpenness; }
  36152. /** This sets a flag to indicate that the tree can be used for multi-selection.
  36153. You can always select multiple items internally by calling the
  36154. TreeViewItem::setSelected() method, but this flag indicates whether the user
  36155. is allowed to multi-select by clicking on the tree.
  36156. By default it is disabled.
  36157. @see isMultiSelectEnabled
  36158. */
  36159. void setMultiSelectEnabled (bool canMultiSelect);
  36160. /** Returns whether multi-select has been enabled for the tree.
  36161. @see setMultiSelectEnabled
  36162. */
  36163. bool isMultiSelectEnabled() const throw() { return multiSelectEnabled; }
  36164. /** Sets a flag to indicate whether to hide the open/close buttons.
  36165. @see areOpenCloseButtonsVisible
  36166. */
  36167. void setOpenCloseButtonsVisible (bool shouldBeVisible);
  36168. /** Returns whether open/close buttons are shown.
  36169. @see setOpenCloseButtonsVisible
  36170. */
  36171. bool areOpenCloseButtonsVisible() const throw() { return openCloseButtonsVisible; }
  36172. /** Deselects any items that are currently selected. */
  36173. void clearSelectedItems();
  36174. /** Returns the number of items that are currently selected.
  36175. @see getSelectedItem, clearSelectedItems
  36176. */
  36177. int getNumSelectedItems() const throw();
  36178. /** Returns one of the selected items in the tree.
  36179. @param index the index, 0 to (getNumSelectedItems() - 1)
  36180. */
  36181. TreeViewItem* getSelectedItem (int index) const throw();
  36182. /** Returns the number of rows the tree is using.
  36183. This will depend on which items are open.
  36184. @see TreeViewItem::getRowNumberInTree()
  36185. */
  36186. int getNumRowsInTree() const;
  36187. /** Returns the item on a particular row of the tree.
  36188. If the index is out of range, this will return 0.
  36189. @see getNumRowsInTree, TreeViewItem::getRowNumberInTree()
  36190. */
  36191. TreeViewItem* getItemOnRow (int index) const;
  36192. /** Returns the item that contains a given y position.
  36193. The y is relative to the top of the TreeView component.
  36194. */
  36195. TreeViewItem* getItemAt (int yPosition) const throw();
  36196. /** Tries to scroll the tree so that this item is on-screen somewhere. */
  36197. void scrollToKeepItemVisible (TreeViewItem* item);
  36198. /** Returns the treeview's Viewport object. */
  36199. Viewport* getViewport() const throw();
  36200. /** Returns the number of pixels by which each nested level of the tree is indented.
  36201. @see setIndentSize
  36202. */
  36203. int getIndentSize() const throw() { return indentSize; }
  36204. /** Changes the distance by which each nested level of the tree is indented.
  36205. @see getIndentSize
  36206. */
  36207. void setIndentSize (int newIndentSize);
  36208. /** Searches the tree for an item with the specified identifier.
  36209. The identifer string must have been created by calling TreeViewItem::getItemIdentifierString().
  36210. If no such item exists, this will return false. If the item is found, all of its items
  36211. will be automatically opened.
  36212. */
  36213. TreeViewItem* findItemFromIdentifierString (const String& identifierString) const;
  36214. /** Saves the current state of open/closed nodes so it can be restored later.
  36215. This takes a snapshot of which nodes have been explicitly opened or closed,
  36216. and records it as XML. To identify node objects it uses the
  36217. TreeViewItem::getUniqueName() method to create named paths. This
  36218. means that the same state of open/closed nodes can be restored to a
  36219. completely different instance of the tree, as long as it contains nodes
  36220. whose unique names are the same.
  36221. The caller is responsible for deleting the object that is returned.
  36222. @param alsoIncludeScrollPosition if this is true, the state will also
  36223. include information about where the
  36224. tree has been scrolled to vertically,
  36225. so this can also be restored
  36226. @see restoreOpennessState
  36227. */
  36228. XmlElement* getOpennessState (bool alsoIncludeScrollPosition) const;
  36229. /** Restores a previously saved arrangement of open/closed nodes.
  36230. This will try to restore a snapshot of the tree's state that was created by
  36231. the getOpennessState() method. If any of the nodes named in the original
  36232. XML aren't present in this tree, they will be ignored.
  36233. @see getOpennessState
  36234. */
  36235. void restoreOpennessState (const XmlElement& newState);
  36236. /** A set of colour IDs to use to change the colour of various aspects of the treeview.
  36237. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36238. methods.
  36239. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36240. */
  36241. enum ColourIds
  36242. {
  36243. backgroundColourId = 0x1000500, /**< A background colour to fill the component with. */
  36244. linesColourId = 0x1000501, /**< The colour to draw the lines with.*/
  36245. dragAndDropIndicatorColourId = 0x1000502 /**< The colour to use for the drag-and-drop target position indicator. */
  36246. };
  36247. /** @internal */
  36248. void paint (Graphics& g);
  36249. /** @internal */
  36250. void resized();
  36251. /** @internal */
  36252. bool keyPressed (const KeyPress& key);
  36253. /** @internal */
  36254. void colourChanged();
  36255. /** @internal */
  36256. void enablementChanged();
  36257. /** @internal */
  36258. bool isInterestedInFileDrag (const StringArray& files);
  36259. /** @internal */
  36260. void fileDragEnter (const StringArray& files, int x, int y);
  36261. /** @internal */
  36262. void fileDragMove (const StringArray& files, int x, int y);
  36263. /** @internal */
  36264. void fileDragExit (const StringArray& files);
  36265. /** @internal */
  36266. void filesDropped (const StringArray& files, int x, int y);
  36267. /** @internal */
  36268. bool isInterestedInDragSource (const String& sourceDescription, Component* sourceComponent);
  36269. /** @internal */
  36270. void itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36271. /** @internal */
  36272. void itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36273. /** @internal */
  36274. void itemDragExit (const String& sourceDescription, Component* sourceComponent);
  36275. /** @internal */
  36276. void itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y);
  36277. juce_UseDebuggingNewOperator
  36278. private:
  36279. friend class TreeViewItem;
  36280. friend class TreeViewContentComponent;
  36281. class TreeViewport;
  36282. class InsertPointHighlight;
  36283. class TargetGroupHighlight;
  36284. friend class ScopedPointer<TreeViewport>;
  36285. friend class ScopedPointer<InsertPointHighlight>;
  36286. friend class ScopedPointer<TargetGroupHighlight>;
  36287. ScopedPointer<TreeViewport> viewport;
  36288. CriticalSection nodeAlterationLock;
  36289. TreeViewItem* rootItem;
  36290. ScopedPointer<InsertPointHighlight> dragInsertPointHighlight;
  36291. ScopedPointer<TargetGroupHighlight> dragTargetGroupHighlight;
  36292. int indentSize;
  36293. bool defaultOpenness : 1;
  36294. bool needsRecalculating : 1;
  36295. bool rootItemVisible : 1;
  36296. bool multiSelectEnabled : 1;
  36297. bool openCloseButtonsVisible : 1;
  36298. void itemsChanged() throw();
  36299. void handleAsyncUpdate();
  36300. void moveSelectedRow (int delta);
  36301. void updateButtonUnderMouse (const MouseEvent& e);
  36302. void showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw();
  36303. void hideDragHighlight() throw();
  36304. void handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  36305. void handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y);
  36306. TreeViewItem* getInsertPosition (int& x, int& y, int& insertIndex,
  36307. const StringArray& files, const String& sourceDescription,
  36308. Component* sourceComponent) const throw();
  36309. TreeView (const TreeView&);
  36310. TreeView& operator= (const TreeView&);
  36311. };
  36312. #endif // __JUCE_TREEVIEW_JUCEHEADER__
  36313. /*** End of inlined file: juce_TreeView.h ***/
  36314. #endif
  36315. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36316. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  36317. #ifndef __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36318. #define __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36319. /*** Start of inlined file: juce_DirectoryContentsList.h ***/
  36320. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36321. #define __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36322. /*** Start of inlined file: juce_FileFilter.h ***/
  36323. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  36324. #define __JUCE_FILEFILTER_JUCEHEADER__
  36325. /**
  36326. Interface for deciding which files are suitable for something.
  36327. For example, this is used by DirectoryContentsList to select which files
  36328. go into the list.
  36329. @see WildcardFileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  36330. */
  36331. class JUCE_API FileFilter
  36332. {
  36333. public:
  36334. /** Creates a filter with the given description.
  36335. The description can be returned later with the getDescription() method.
  36336. */
  36337. FileFilter (const String& filterDescription);
  36338. /** Destructor. */
  36339. virtual ~FileFilter();
  36340. /** Returns the description that the filter was created with. */
  36341. const String& getDescription() const throw();
  36342. /** Should return true if this file is suitable for inclusion in whatever context
  36343. the object is being used.
  36344. */
  36345. virtual bool isFileSuitable (const File& file) const = 0;
  36346. /** Should return true if this directory is suitable for inclusion in whatever context
  36347. the object is being used.
  36348. */
  36349. virtual bool isDirectorySuitable (const File& file) const = 0;
  36350. protected:
  36351. String description;
  36352. };
  36353. #endif // __JUCE_FILEFILTER_JUCEHEADER__
  36354. /*** End of inlined file: juce_FileFilter.h ***/
  36355. /**
  36356. A class to asynchronously scan for details about the files in a directory.
  36357. This keeps a list of files and some information about them, using a background
  36358. thread to scan for more files. As files are found, it broadcasts change messages
  36359. to tell any listeners.
  36360. @see FileListComponent, FileBrowserComponent
  36361. */
  36362. class JUCE_API DirectoryContentsList : public ChangeBroadcaster,
  36363. public TimeSliceClient
  36364. {
  36365. public:
  36366. /** Creates a directory list.
  36367. To set the directory it should point to, use setDirectory(), which will
  36368. also start it scanning for files on the background thread.
  36369. When the background thread finds and adds new files to this list, the
  36370. ChangeBroadcaster class will send a change message, so you can register
  36371. listeners and update them when the list changes.
  36372. @param fileFilter an optional filter to select which files are
  36373. included in the list. If this is 0, then all files
  36374. and directories are included. Make sure that the
  36375. filter doesn't get deleted during the lifetime of this
  36376. object
  36377. @param threadToUse a thread object that this list can use
  36378. to scan for files as a background task. Make sure
  36379. that the thread you give it has been started, or you
  36380. won't get any files!
  36381. */
  36382. DirectoryContentsList (const FileFilter* fileFilter,
  36383. TimeSliceThread& threadToUse);
  36384. /** Destructor. */
  36385. ~DirectoryContentsList();
  36386. /** Sets the directory to look in for files.
  36387. If the directory that's passed in is different to the current one, this will
  36388. also start the background thread scanning it for files.
  36389. */
  36390. void setDirectory (const File& directory,
  36391. bool includeDirectories,
  36392. bool includeFiles);
  36393. /** Returns the directory that's currently being used. */
  36394. const File& getDirectory() const;
  36395. /** Clears the list, and stops the thread scanning for files. */
  36396. void clear();
  36397. /** Clears the list and restarts scanning the directory for files. */
  36398. void refresh();
  36399. /** True if the background thread hasn't yet finished scanning for files. */
  36400. bool isStillLoading() const;
  36401. /** Tells the list whether or not to ignore hidden files.
  36402. By default these are ignored.
  36403. */
  36404. void setIgnoresHiddenFiles (bool shouldIgnoreHiddenFiles);
  36405. /** Returns true if hidden files are ignored.
  36406. @see setIgnoresHiddenFiles
  36407. */
  36408. bool ignoresHiddenFiles() const;
  36409. /** Contains cached information about one of the files in a DirectoryContentsList.
  36410. */
  36411. struct FileInfo
  36412. {
  36413. /** The filename.
  36414. This isn't a full pathname, it's just the last part of the path, same as you'd
  36415. get from File::getFileName().
  36416. To get the full pathname, use DirectoryContentsList::getDirectory().getChildFile (filename).
  36417. */
  36418. String filename;
  36419. /** File size in bytes. */
  36420. int64 fileSize;
  36421. /** File modification time.
  36422. As supplied by File::getLastModificationTime().
  36423. */
  36424. Time modificationTime;
  36425. /** File creation time.
  36426. As supplied by File::getCreationTime().
  36427. */
  36428. Time creationTime;
  36429. /** True if the file is a directory. */
  36430. bool isDirectory;
  36431. /** True if the file is read-only. */
  36432. bool isReadOnly;
  36433. };
  36434. /** Returns the number of files currently available in the list.
  36435. The info about one of these files can be retrieved with getFileInfo() or
  36436. getFile().
  36437. Obviously as the background thread runs and scans the directory for files, this
  36438. number will change.
  36439. @see getFileInfo, getFile
  36440. */
  36441. int getNumFiles() const;
  36442. /** Returns the cached information about one of the files in the list.
  36443. If the index is in-range, this will return true and will copy the file's details
  36444. to the structure that is passed-in.
  36445. If it returns false, then the index wasn't in range, and the structure won't
  36446. be affected.
  36447. @see getNumFiles, getFile
  36448. */
  36449. bool getFileInfo (int index, FileInfo& resultInfo) const;
  36450. /** Returns one of the files in the list.
  36451. @param index should be less than getNumFiles(). If this is out-of-range, the
  36452. return value will be File::nonexistent
  36453. @see getNumFiles, getFileInfo
  36454. */
  36455. const File getFile (int index) const;
  36456. /** Returns the file filter being used.
  36457. The filter is specified in the constructor.
  36458. */
  36459. const FileFilter* getFilter() const { return fileFilter; }
  36460. /** @internal */
  36461. bool useTimeSlice();
  36462. /** @internal */
  36463. TimeSliceThread& getTimeSliceThread() { return thread; }
  36464. /** @internal */
  36465. static int compareElements (const DirectoryContentsList::FileInfo* first,
  36466. const DirectoryContentsList::FileInfo* second);
  36467. juce_UseDebuggingNewOperator
  36468. private:
  36469. File root;
  36470. const FileFilter* fileFilter;
  36471. TimeSliceThread& thread;
  36472. int fileTypeFlags;
  36473. CriticalSection fileListLock;
  36474. OwnedArray <FileInfo> files;
  36475. ScopedPointer <DirectoryIterator> fileFindHandle;
  36476. bool volatile shouldStop;
  36477. void changed();
  36478. bool checkNextFile (bool& hasChanged);
  36479. bool addFile (const File& file, bool isDir,
  36480. const int64 fileSize, const Time& modTime,
  36481. const Time& creationTime, bool isReadOnly);
  36482. void setTypeFlags (int newFlags);
  36483. DirectoryContentsList (const DirectoryContentsList&);
  36484. DirectoryContentsList& operator= (const DirectoryContentsList&);
  36485. };
  36486. #endif // __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36487. /*** End of inlined file: juce_DirectoryContentsList.h ***/
  36488. /*** Start of inlined file: juce_FileBrowserListener.h ***/
  36489. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36490. #define __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36491. /**
  36492. A listener for user selection events in a file browser.
  36493. This is used by a FileBrowserComponent or FileListComponent.
  36494. */
  36495. class JUCE_API FileBrowserListener
  36496. {
  36497. public:
  36498. /** Destructor. */
  36499. virtual ~FileBrowserListener();
  36500. /** Callback when the user selects a different file in the browser. */
  36501. virtual void selectionChanged() = 0;
  36502. /** Callback when the user clicks on a file in the browser. */
  36503. virtual void fileClicked (const File& file, const MouseEvent& e) = 0;
  36504. /** Callback when the user double-clicks on a file in the browser. */
  36505. virtual void fileDoubleClicked (const File& file) = 0;
  36506. };
  36507. #endif // __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36508. /*** End of inlined file: juce_FileBrowserListener.h ***/
  36509. /**
  36510. A base class for components that display a list of the files in a directory.
  36511. @see DirectoryContentsList
  36512. */
  36513. class JUCE_API DirectoryContentsDisplayComponent
  36514. {
  36515. public:
  36516. /** Creates a DirectoryContentsDisplayComponent for a given list of files. */
  36517. DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow);
  36518. /** Destructor. */
  36519. virtual ~DirectoryContentsDisplayComponent();
  36520. /** Returns the number of files the user has got selected.
  36521. @see getSelectedFile
  36522. */
  36523. virtual int getNumSelectedFiles() const = 0;
  36524. /** Returns one of the files that the user has currently selected.
  36525. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  36526. @see getNumSelectedFiles
  36527. */
  36528. virtual const File getSelectedFile (int index) const = 0;
  36529. /** Deselects any selected files. */
  36530. virtual void deselectAllFiles() = 0;
  36531. /** Scrolls this view to the top. */
  36532. virtual void scrollToTop() = 0;
  36533. /** Adds a listener to be told when files are selected or clicked.
  36534. @see removeListener
  36535. */
  36536. void addListener (FileBrowserListener* listener);
  36537. /** Removes a listener.
  36538. @see addListener
  36539. */
  36540. void removeListener (FileBrowserListener* listener);
  36541. /** A set of colour IDs to use to change the colour of various aspects of the list.
  36542. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  36543. methods.
  36544. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  36545. */
  36546. enum ColourIds
  36547. {
  36548. highlightColourId = 0x1000540, /**< The colour to use to fill a highlighted row of the list. */
  36549. textColourId = 0x1000541, /**< The colour for the text. */
  36550. };
  36551. /** @internal */
  36552. void sendSelectionChangeMessage();
  36553. /** @internal */
  36554. void sendDoubleClickMessage (const File& file);
  36555. /** @internal */
  36556. void sendMouseClickMessage (const File& file, const MouseEvent& e);
  36557. juce_UseDebuggingNewOperator
  36558. protected:
  36559. DirectoryContentsList& fileList;
  36560. ListenerList <FileBrowserListener> listeners;
  36561. DirectoryContentsDisplayComponent (const DirectoryContentsDisplayComponent&);
  36562. DirectoryContentsDisplayComponent& operator= (const DirectoryContentsDisplayComponent&);
  36563. };
  36564. #endif // __JUCE_DIRECTORYCONTENTSDISPLAYCOMPONENT_JUCEHEADER__
  36565. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.h ***/
  36566. #endif
  36567. #ifndef __JUCE_DIRECTORYCONTENTSLIST_JUCEHEADER__
  36568. #endif
  36569. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36570. /*** Start of inlined file: juce_FileBrowserComponent.h ***/
  36571. #ifndef __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36572. #define __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36573. /*** Start of inlined file: juce_FilePreviewComponent.h ***/
  36574. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36575. #define __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36576. /**
  36577. Base class for components that live inside a file chooser dialog box and
  36578. show previews of the files that get selected.
  36579. One of these allows special extra information to be displayed for files
  36580. in a dialog box as the user selects them. Each time the current file or
  36581. directory is changed, the selectedFileChanged() method will be called
  36582. to allow it to update itself appropriately.
  36583. @see FileChooser, ImagePreviewComponent
  36584. */
  36585. class JUCE_API FilePreviewComponent : public Component
  36586. {
  36587. public:
  36588. /** Creates a FilePreviewComponent. */
  36589. FilePreviewComponent();
  36590. /** Destructor. */
  36591. ~FilePreviewComponent();
  36592. /** Called to indicate that the user's currently selected file has changed.
  36593. @param newSelectedFile the newly selected file or directory, which may be
  36594. File::nonexistent if none is selected.
  36595. */
  36596. virtual void selectedFileChanged (const File& newSelectedFile) = 0;
  36597. juce_UseDebuggingNewOperator
  36598. private:
  36599. FilePreviewComponent (const FilePreviewComponent&);
  36600. FilePreviewComponent& operator= (const FilePreviewComponent&);
  36601. };
  36602. #endif // __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  36603. /*** End of inlined file: juce_FilePreviewComponent.h ***/
  36604. /**
  36605. A component for browsing and selecting a file or directory to open or save.
  36606. This contains a FileListComponent and adds various boxes and controls for
  36607. navigating and selecting a file. It can work in different modes so that it can
  36608. be used for loading or saving a file, or for choosing a directory.
  36609. @see FileChooserDialogBox, FileChooser, FileListComponent
  36610. */
  36611. class JUCE_API FileBrowserComponent : public Component,
  36612. public ChangeBroadcaster,
  36613. private FileBrowserListener,
  36614. private TextEditorListener,
  36615. private ButtonListener,
  36616. private ComboBoxListener,
  36617. private FileFilter
  36618. {
  36619. public:
  36620. /** Various options for the browser.
  36621. A combination of these is passed into the FileBrowserComponent constructor.
  36622. */
  36623. enum FileChooserFlags
  36624. {
  36625. openMode = 1, /**< specifies that the component should allow the user to
  36626. choose an existing file with the intention of opening it. */
  36627. saveMode = 2, /**< specifies that the component should allow the user to specify
  36628. the name of a file that will be used to save something. */
  36629. canSelectFiles = 4, /**< specifies that the user can select files (can be used in
  36630. conjunction with canSelectDirectories). */
  36631. canSelectDirectories = 8, /**< specifies that the user can select directories (can be used in
  36632. conjuction with canSelectFiles). */
  36633. canSelectMultipleItems = 16, /**< specifies that the user can select multiple items. */
  36634. useTreeView = 32, /**< specifies that a tree-view should be shown instead of a file list. */
  36635. filenameBoxIsReadOnly = 64 /**< specifies that the user can't type directly into the filename box. */
  36636. };
  36637. /** Creates a FileBrowserComponent.
  36638. @param flags A combination of flags from the FileChooserFlags enumeration,
  36639. used to specify the component's behaviour. The flags must contain
  36640. either openMode or saveMode, and canSelectFiles and/or
  36641. canSelectDirectories.
  36642. @param initialFileOrDirectory The file or directory that should be selected when
  36643. the component begins. If this is File::nonexistent,
  36644. a default directory will be chosen.
  36645. @param fileFilter an optional filter to use to determine which files
  36646. are shown. If this is 0 then all files are displayed. Note
  36647. that a pointer is kept internally to this object, so
  36648. make sure that it is not deleted before the browser object
  36649. is deleted.
  36650. @param previewComp an optional preview component that will be used to
  36651. show previews of files that the user selects
  36652. */
  36653. FileBrowserComponent (int flags,
  36654. const File& initialFileOrDirectory,
  36655. const FileFilter* fileFilter,
  36656. FilePreviewComponent* previewComp);
  36657. /** Destructor. */
  36658. ~FileBrowserComponent();
  36659. /** Returns the number of files that the user has got selected.
  36660. If multiple select isn't active, this will only be 0 or 1. To get the complete
  36661. list of files they've chosen, pass an index to getCurrentFile().
  36662. */
  36663. int getNumSelectedFiles() const throw();
  36664. /** Returns one of the files that the user has chosen.
  36665. If the box has multi-select enabled, the index lets you specify which of the files
  36666. to get - see getNumSelectedFiles() to find out how many files were chosen.
  36667. @see getHighlightedFile
  36668. */
  36669. const File getSelectedFile (int index) const throw();
  36670. /** Deselects any files that are currently selected.
  36671. */
  36672. void deselectAllFiles();
  36673. /** Returns true if the currently selected file(s) are usable.
  36674. This can be used to decide whether the user can press "ok" for the
  36675. current file. What it does depends on the mode, so for example in an "open"
  36676. mode, this only returns true if a file has been selected and if it exists.
  36677. In a "save" mode, a non-existent file would also be valid.
  36678. */
  36679. bool currentFileIsValid() const;
  36680. /** This returns the last item in the view that the user has highlighted.
  36681. This may be different from getCurrentFile(), which returns the value
  36682. that is shown in the filename box, and if there are multiple selections,
  36683. this will only return one of them.
  36684. @see getSelectedFile
  36685. */
  36686. const File getHighlightedFile() const throw();
  36687. /** Returns the directory whose contents are currently being shown in the listbox. */
  36688. const File getRoot() const;
  36689. /** Changes the directory that's being shown in the listbox. */
  36690. void setRoot (const File& newRootDirectory);
  36691. /** Equivalent to pressing the "up" button to browse the parent directory. */
  36692. void goUp();
  36693. /** Refreshes the directory that's currently being listed. */
  36694. void refresh();
  36695. /** Returns a verb to describe what should happen when the file is accepted.
  36696. E.g. if browsing in "load file" mode, this will be "Open", if in "save file"
  36697. mode, it'll be "Save", etc.
  36698. */
  36699. virtual const String getActionVerb() const;
  36700. /** Returns true if the saveMode flag was set when this component was created.
  36701. */
  36702. bool isSaveMode() const throw();
  36703. /** Adds a listener to be told when the user selects and clicks on files.
  36704. @see removeListener
  36705. */
  36706. void addListener (FileBrowserListener* listener);
  36707. /** Removes a listener.
  36708. @see addListener
  36709. */
  36710. void removeListener (FileBrowserListener* listener);
  36711. /** @internal */
  36712. void resized();
  36713. /** @internal */
  36714. void buttonClicked (Button* b);
  36715. /** @internal */
  36716. void comboBoxChanged (ComboBox*);
  36717. /** @internal */
  36718. void textEditorTextChanged (TextEditor& editor);
  36719. /** @internal */
  36720. void textEditorReturnKeyPressed (TextEditor& editor);
  36721. /** @internal */
  36722. void textEditorEscapeKeyPressed (TextEditor& editor);
  36723. /** @internal */
  36724. void textEditorFocusLost (TextEditor& editor);
  36725. /** @internal */
  36726. bool keyPressed (const KeyPress& key);
  36727. /** @internal */
  36728. void selectionChanged();
  36729. /** @internal */
  36730. void fileClicked (const File& f, const MouseEvent& e);
  36731. /** @internal */
  36732. void fileDoubleClicked (const File& f);
  36733. /** @internal */
  36734. bool isFileSuitable (const File& file) const;
  36735. /** @internal */
  36736. bool isDirectorySuitable (const File&) const;
  36737. /** @internal */
  36738. FilePreviewComponent* getPreviewComponent() const throw();
  36739. juce_UseDebuggingNewOperator
  36740. protected:
  36741. virtual const BigInteger getRoots (StringArray& rootNames, StringArray& rootPaths);
  36742. private:
  36743. ScopedPointer <DirectoryContentsList> fileList;
  36744. const FileFilter* fileFilter;
  36745. int flags;
  36746. File currentRoot;
  36747. Array<File> chosenFiles;
  36748. ListenerList <FileBrowserListener> listeners;
  36749. DirectoryContentsDisplayComponent* fileListComponent;
  36750. FilePreviewComponent* previewComp;
  36751. ComboBox* currentPathBox;
  36752. TextEditor* filenameBox;
  36753. Button* goUpButton;
  36754. TimeSliceThread thread;
  36755. void sendListenerChangeMessage();
  36756. bool isFileOrDirSuitable (const File& f) const;
  36757. FileBrowserComponent (const FileBrowserComponent&);
  36758. FileBrowserComponent& operator= (const FileBrowserComponent&);
  36759. };
  36760. #endif // __JUCE_FILEBROWSERCOMPONENT_JUCEHEADER__
  36761. /*** End of inlined file: juce_FileBrowserComponent.h ***/
  36762. #endif
  36763. #ifndef __JUCE_FILEBROWSERLISTENER_JUCEHEADER__
  36764. #endif
  36765. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36766. /*** Start of inlined file: juce_FileChooser.h ***/
  36767. #ifndef __JUCE_FILECHOOSER_JUCEHEADER__
  36768. #define __JUCE_FILECHOOSER_JUCEHEADER__
  36769. /**
  36770. Creates a dialog box to choose a file or directory to load or save.
  36771. To use a FileChooser:
  36772. - create one (as a local stack variable is the neatest way)
  36773. - call one of its browseFor.. methods
  36774. - if this returns true, the user has selected a file, so you can retrieve it
  36775. with the getResult() method.
  36776. e.g. @code
  36777. void loadMooseFile()
  36778. {
  36779. FileChooser myChooser ("Please select the moose you want to load...",
  36780. File::getSpecialLocation (File::userHomeDirectory),
  36781. "*.moose");
  36782. if (myChooser.browseForFileToOpen())
  36783. {
  36784. File mooseFile (myChooser.getResult());
  36785. loadMoose (mooseFile);
  36786. }
  36787. }
  36788. @endcode
  36789. */
  36790. class JUCE_API FileChooser
  36791. {
  36792. public:
  36793. /** Creates a FileChooser.
  36794. After creating one of these, use one of the browseFor... methods to display it.
  36795. @param dialogBoxTitle a text string to display in the dialog box to
  36796. tell the user what's going on
  36797. @param initialFileOrDirectory the file or directory that should be selected when
  36798. the dialog box opens. If this parameter is set to
  36799. File::nonexistent, a sensible default directory
  36800. will be used instead.
  36801. @param filePatternsAllowed a set of file patterns to specify which files can be
  36802. selected - each pattern should be separated by a
  36803. comma or semi-colon, e.g. "*" or "*.jpg;*.gif". An
  36804. empty string means that all files are allowed
  36805. @param useOSNativeDialogBox if true, then a native dialog box will be used if
  36806. possible; if false, then a Juce-based browser dialog
  36807. box will always be used
  36808. @see browseForFileToOpen, browseForFileToSave, browseForDirectory
  36809. */
  36810. FileChooser (const String& dialogBoxTitle,
  36811. const File& initialFileOrDirectory = File::nonexistent,
  36812. const String& filePatternsAllowed = String::empty,
  36813. bool useOSNativeDialogBox = true);
  36814. /** Destructor. */
  36815. ~FileChooser();
  36816. /** Shows a dialog box to choose a file to open.
  36817. This will display the dialog box modally, using an "open file" mode, so that
  36818. it won't allow non-existent files or directories to be chosen.
  36819. @param previewComponent an optional component to display inside the dialog
  36820. box to show special info about the files that the user
  36821. is browsing. The component will not be deleted by this
  36822. object, so the caller must take care of it.
  36823. @returns true if the user selected a file, in which case, use the getResult()
  36824. method to find out what it was. Returns false if they cancelled instead.
  36825. @see browseForFileToSave, browseForDirectory
  36826. */
  36827. bool browseForFileToOpen (FilePreviewComponent* previewComponent = 0);
  36828. /** Same as browseForFileToOpen, but allows the user to select multiple files.
  36829. The files that are returned can be obtained by calling getResults(). See
  36830. browseForFileToOpen() for more info about the behaviour of this method.
  36831. */
  36832. bool browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent = 0);
  36833. /** Shows a dialog box to choose a file to save.
  36834. This will display the dialog box modally, using an "save file" mode, so it
  36835. will allow non-existent files to be chosen, but not directories.
  36836. @param warnAboutOverwritingExistingFiles if true, the dialog box will ask
  36837. the user if they're sure they want to overwrite a file that already
  36838. exists
  36839. @returns true if the user chose a file and pressed 'ok', in which case, use
  36840. the getResult() method to find out what the file was. Returns false
  36841. if they cancelled instead.
  36842. @see browseForFileToOpen, browseForDirectory
  36843. */
  36844. bool browseForFileToSave (bool warnAboutOverwritingExistingFiles);
  36845. /** Shows a dialog box to choose a directory.
  36846. This will display the dialog box modally, using an "open directory" mode, so it
  36847. will only allow directories to be returned, not files.
  36848. @returns true if the user chose a directory and pressed 'ok', in which case, use
  36849. the getResult() method to find out what they chose. Returns false
  36850. if they cancelled instead.
  36851. @see browseForFileToOpen, browseForFileToSave
  36852. */
  36853. bool browseForDirectory();
  36854. /** Same as browseForFileToOpen, but allows the user to select multiple files and directories.
  36855. The files that are returned can be obtained by calling getResults(). See
  36856. browseForFileToOpen() for more info about the behaviour of this method.
  36857. */
  36858. bool browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent = 0);
  36859. /** Returns the last file that was chosen by one of the browseFor methods.
  36860. After calling the appropriate browseFor... method, this method lets you
  36861. find out what file or directory they chose.
  36862. Note that the file returned is only valid if the browse method returned true (i.e.
  36863. if the user pressed 'ok' rather than cancelling).
  36864. If you're using a multiple-file select, then use the getResults() method instead,
  36865. to obtain the list of all files chosen.
  36866. @see getResults
  36867. */
  36868. const File getResult() const;
  36869. /** Returns a list of all the files that were chosen during the last call to a
  36870. browse method.
  36871. This array may be empty if no files were chosen, or can contain multiple entries
  36872. if multiple files were chosen.
  36873. @see getResult
  36874. */
  36875. const Array<File>& getResults() const;
  36876. juce_UseDebuggingNewOperator
  36877. private:
  36878. String title, filters;
  36879. File startingFile;
  36880. Array<File> results;
  36881. bool useNativeDialogBox;
  36882. bool showDialog (bool selectsDirectories, bool selectsFiles, bool isSave,
  36883. bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36884. FilePreviewComponent* previewComponent);
  36885. static void showPlatformDialog (Array<File>& results, const String& title, const File& file,
  36886. const String& filters, bool selectsDirectories, bool selectsFiles,
  36887. bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles,
  36888. FilePreviewComponent* previewComponent);
  36889. };
  36890. #endif // __JUCE_FILECHOOSER_JUCEHEADER__
  36891. /*** End of inlined file: juce_FileChooser.h ***/
  36892. #endif
  36893. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36894. /*** Start of inlined file: juce_FileChooserDialogBox.h ***/
  36895. #ifndef __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36896. #define __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  36897. /*** Start of inlined file: juce_ResizableWindow.h ***/
  36898. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36899. #define __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  36900. /*** Start of inlined file: juce_TopLevelWindow.h ***/
  36901. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36902. #define __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  36903. /*** Start of inlined file: juce_DropShadower.h ***/
  36904. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  36905. #define __JUCE_DROPSHADOWER_JUCEHEADER__
  36906. /**
  36907. Adds a drop-shadow to a component.
  36908. This object creates and manages a set of components which sit around a
  36909. component, creating a gaussian shadow around it. The components will track
  36910. the position of the component and if it's brought to the front they'll also
  36911. follow this.
  36912. For desktop windows you don't need to use this class directly - just
  36913. set the Component::windowHasDropShadow flag when calling
  36914. Component::addToDesktop(), and the system will create one of these if it's
  36915. needed (which it obviously isn't on the Mac, for example).
  36916. */
  36917. class JUCE_API DropShadower : public ComponentListener
  36918. {
  36919. public:
  36920. /** Creates a DropShadower.
  36921. @param alpha the opacity of the shadows, from 0 to 1.0
  36922. @param xOffset the horizontal displacement of the shadow, in pixels
  36923. @param yOffset the vertical displacement of the shadow, in pixels
  36924. @param blurRadius the radius of the blur to use for creating the shadow
  36925. */
  36926. DropShadower (float alpha = 0.5f,
  36927. int xOffset = 1,
  36928. int yOffset = 5,
  36929. float blurRadius = 10.0f);
  36930. /** Destructor. */
  36931. virtual ~DropShadower();
  36932. /** Attaches the DropShadower to the component you want to shadow. */
  36933. void setOwner (Component* componentToFollow);
  36934. /** @internal */
  36935. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  36936. /** @internal */
  36937. void componentBroughtToFront (Component& component);
  36938. /** @internal */
  36939. void componentChildrenChanged (Component& component);
  36940. /** @internal */
  36941. void componentParentHierarchyChanged (Component& component);
  36942. /** @internal */
  36943. void componentVisibilityChanged (Component& component);
  36944. juce_UseDebuggingNewOperator
  36945. private:
  36946. Component* owner;
  36947. int numShadows;
  36948. Component* shadowWindows[4];
  36949. Image shadowImageSections[12];
  36950. const int shadowEdge, xOffset, yOffset;
  36951. const float alpha, blurRadius;
  36952. bool inDestructor, reentrant;
  36953. void updateShadows();
  36954. void setShadowImage (const Image& src,
  36955. const int num,
  36956. const int w, const int h,
  36957. const int sx, const int sy);
  36958. void bringShadowWindowsToFront();
  36959. void deleteShadowWindows();
  36960. DropShadower (const DropShadower&);
  36961. DropShadower& operator= (const DropShadower&);
  36962. };
  36963. #endif // __JUCE_DROPSHADOWER_JUCEHEADER__
  36964. /*** End of inlined file: juce_DropShadower.h ***/
  36965. /**
  36966. A base class for top-level windows.
  36967. This class is used for components that are considered a major part of your
  36968. application - e.g. ResizableWindow, DocumentWindow, DialogWindow, AlertWindow,
  36969. etc. Things like menus that pop up briefly aren't derived from it.
  36970. A TopLevelWindow is probably on the desktop, but this isn't mandatory - it
  36971. could itself be the child of another component.
  36972. The class manages a list of all instances of top-level windows that are in use,
  36973. and each one is also given the concept of being "active". The active window is
  36974. one that is actively being used by the user. This isn't quite the same as the
  36975. component with the keyboard focus, because there may be a popup menu or other
  36976. temporary window which gets keyboard focus while the active top level window is
  36977. unchanged.
  36978. A top-level window also has an optional drop-shadow.
  36979. @see ResizableWindow, DocumentWindow, DialogWindow
  36980. */
  36981. class JUCE_API TopLevelWindow : public Component
  36982. {
  36983. public:
  36984. /** Creates a TopLevelWindow.
  36985. @param name the name to give the component
  36986. @param addToDesktop if true, the window will be automatically added to the
  36987. desktop; if false, you can use it as a child component
  36988. */
  36989. TopLevelWindow (const String& name, bool addToDesktop);
  36990. /** Destructor. */
  36991. ~TopLevelWindow();
  36992. /** True if this is currently the TopLevelWindow that is actively being used.
  36993. This isn't quite the same as having keyboard focus, because the focus may be
  36994. on a child component or a temporary pop-up menu, etc, while this window is
  36995. still considered to be active.
  36996. @see activeWindowStatusChanged
  36997. */
  36998. bool isActiveWindow() const throw() { return windowIsActive_; }
  36999. /** This will set the bounds of the window so that it's centred in front of another
  37000. window.
  37001. If your app has a few windows open and want to pop up a dialog box for one of
  37002. them, you can use this to show it in front of the relevent parent window, which
  37003. is a bit neater than just having it appear in the middle of the screen.
  37004. If componentToCentreAround is 0, then the currently active TopLevelWindow will
  37005. be used instead. If no window is focused, it'll just default to the middle of the
  37006. screen.
  37007. */
  37008. void centreAroundComponent (Component* componentToCentreAround,
  37009. int width, int height);
  37010. /** Turns the drop-shadow on and off. */
  37011. void setDropShadowEnabled (bool useShadow);
  37012. /** Sets whether an OS-native title bar will be used, or a Juce one.
  37013. @see isUsingNativeTitleBar
  37014. */
  37015. void setUsingNativeTitleBar (bool useNativeTitleBar);
  37016. /** Returns true if the window is currently using an OS-native title bar.
  37017. @see setUsingNativeTitleBar
  37018. */
  37019. bool isUsingNativeTitleBar() const throw() { return useNativeTitleBar && isOnDesktop(); }
  37020. /** Returns the number of TopLevelWindow objects currently in use.
  37021. @see getTopLevelWindow
  37022. */
  37023. static int getNumTopLevelWindows() throw();
  37024. /** Returns one of the TopLevelWindow objects currently in use.
  37025. The index is 0 to (getNumTopLevelWindows() - 1).
  37026. */
  37027. static TopLevelWindow* getTopLevelWindow (int index) throw();
  37028. /** Returns the currently-active top level window.
  37029. There might not be one, of course, so this can return 0.
  37030. */
  37031. static TopLevelWindow* getActiveTopLevelWindow() throw();
  37032. juce_UseDebuggingNewOperator
  37033. /** @internal */
  37034. virtual void addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo = 0);
  37035. protected:
  37036. /** This callback happens when this window becomes active or inactive.
  37037. @see isActiveWindow
  37038. */
  37039. virtual void activeWindowStatusChanged();
  37040. /** @internal */
  37041. void focusOfChildComponentChanged (FocusChangeType cause);
  37042. /** @internal */
  37043. void parentHierarchyChanged();
  37044. /** @internal */
  37045. void visibilityChanged();
  37046. /** @internal */
  37047. virtual int getDesktopWindowStyleFlags() const;
  37048. /** @internal */
  37049. void recreateDesktopWindow();
  37050. private:
  37051. friend class TopLevelWindowManager;
  37052. bool useDropShadow, useNativeTitleBar, windowIsActive_;
  37053. ScopedPointer <DropShadower> shadower;
  37054. void setWindowActive (bool isNowActive);
  37055. TopLevelWindow (const TopLevelWindow&);
  37056. TopLevelWindow& operator= (const TopLevelWindow&);
  37057. };
  37058. #endif // __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  37059. /*** End of inlined file: juce_TopLevelWindow.h ***/
  37060. /*** Start of inlined file: juce_ComponentDragger.h ***/
  37061. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37062. #define __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37063. /*** Start of inlined file: juce_ComponentBoundsConstrainer.h ***/
  37064. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37065. #define __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37066. /**
  37067. A class that imposes restrictions on a Component's size or position.
  37068. This is used by classes such as ResizableCornerComponent,
  37069. ResizableBorderComponent and ResizableWindow.
  37070. The base class can impose some basic size and position limits, but you can
  37071. also subclass this for custom uses.
  37072. @see ResizableCornerComponent, ResizableBorderComponent, ResizableWindow
  37073. */
  37074. class JUCE_API ComponentBoundsConstrainer
  37075. {
  37076. public:
  37077. /** When first created, the object will not impose any restrictions on the components. */
  37078. ComponentBoundsConstrainer() throw();
  37079. /** Destructor. */
  37080. virtual ~ComponentBoundsConstrainer();
  37081. /** Imposes a minimum width limit. */
  37082. void setMinimumWidth (int minimumWidth) throw();
  37083. /** Returns the current minimum width. */
  37084. int getMinimumWidth() const throw() { return minW; }
  37085. /** Imposes a maximum width limit. */
  37086. void setMaximumWidth (int maximumWidth) throw();
  37087. /** Returns the current maximum width. */
  37088. int getMaximumWidth() const throw() { return maxW; }
  37089. /** Imposes a minimum height limit. */
  37090. void setMinimumHeight (int minimumHeight) throw();
  37091. /** Returns the current minimum height. */
  37092. int getMinimumHeight() const throw() { return minH; }
  37093. /** Imposes a maximum height limit. */
  37094. void setMaximumHeight (int maximumHeight) throw();
  37095. /** Returns the current maximum height. */
  37096. int getMaximumHeight() const throw() { return maxH; }
  37097. /** Imposes a minimum width and height limit. */
  37098. void setMinimumSize (int minimumWidth,
  37099. int minimumHeight) throw();
  37100. /** Imposes a maximum width and height limit. */
  37101. void setMaximumSize (int maximumWidth,
  37102. int maximumHeight) throw();
  37103. /** Set all the maximum and minimum dimensions. */
  37104. void setSizeLimits (int minimumWidth,
  37105. int minimumHeight,
  37106. int maximumWidth,
  37107. int maximumHeight) throw();
  37108. /** Sets the amount by which the component is allowed to go off-screen.
  37109. The values indicate how many pixels must remain on-screen when dragged off
  37110. one of its parent's edges, so e.g. if minimumWhenOffTheTop is set to 10, then
  37111. when the component goes off the top of the screen, its y-position will be
  37112. clipped so that there are always at least 10 pixels on-screen. In other words,
  37113. the lowest y-position it can take would be (10 - the component's height).
  37114. If you pass 0 or less for one of these amounts, the component is allowed
  37115. to move beyond that edge completely, with no restrictions at all.
  37116. If you pass a very large number (i.e. larger that the dimensions of the
  37117. component itself), then the component won't be allowed to overlap that
  37118. edge at all. So e.g. setting minimumWhenOffTheLeft to 0xffffff will mean that
  37119. the component will bump into the left side of the screen and go no further.
  37120. */
  37121. void setMinimumOnscreenAmounts (int minimumWhenOffTheTop,
  37122. int minimumWhenOffTheLeft,
  37123. int minimumWhenOffTheBottom,
  37124. int minimumWhenOffTheRight) throw();
  37125. /** Specifies a width-to-height ratio that the resizer should always maintain.
  37126. If the value is 0, no aspect ratio is enforced. If it's non-zero, the width
  37127. will always be maintained as this multiple of the height.
  37128. @see setResizeLimits
  37129. */
  37130. void setFixedAspectRatio (double widthOverHeight) throw();
  37131. /** Returns the aspect ratio that was set with setFixedAspectRatio().
  37132. If no aspect ratio is being enforced, this will return 0.
  37133. */
  37134. double getFixedAspectRatio() const throw();
  37135. /** This callback changes the given co-ordinates to impose whatever the current
  37136. constraints are set to be.
  37137. @param bounds the target position that should be examined and adjusted
  37138. @param previousBounds the component's current size
  37139. @param limits the region in which the component can be positioned
  37140. @param isStretchingTop whether the top edge of the component is being resized
  37141. @param isStretchingLeft whether the left edge of the component is being resized
  37142. @param isStretchingBottom whether the bottom edge of the component is being resized
  37143. @param isStretchingRight whether the right edge of the component is being resized
  37144. */
  37145. virtual void checkBounds (Rectangle<int>& bounds,
  37146. const Rectangle<int>& previousBounds,
  37147. const Rectangle<int>& limits,
  37148. bool isStretchingTop,
  37149. bool isStretchingLeft,
  37150. bool isStretchingBottom,
  37151. bool isStretchingRight);
  37152. /** This callback happens when the resizer is about to start dragging. */
  37153. virtual void resizeStart();
  37154. /** This callback happens when the resizer has finished dragging. */
  37155. virtual void resizeEnd();
  37156. /** Checks the given bounds, and then sets the component to the corrected size. */
  37157. void setBoundsForComponent (Component* const component,
  37158. const Rectangle<int>& bounds,
  37159. bool isStretchingTop,
  37160. bool isStretchingLeft,
  37161. bool isStretchingBottom,
  37162. bool isStretchingRight);
  37163. /** Performs a check on the current size of a component, and moves or resizes
  37164. it if it fails the constraints.
  37165. */
  37166. void checkComponentBounds (Component* component);
  37167. /** Called by setBoundsForComponent() to apply a new constrained size to a
  37168. component.
  37169. By default this just calls setBounds(), but it virtual in case it's needed for
  37170. extremely cunning purposes.
  37171. */
  37172. virtual void applyBoundsToComponent (Component* component,
  37173. const Rectangle<int>& bounds);
  37174. juce_UseDebuggingNewOperator
  37175. private:
  37176. int minW, maxW, minH, maxH;
  37177. int minOffTop, minOffLeft, minOffBottom, minOffRight;
  37178. double aspectRatio;
  37179. ComponentBoundsConstrainer (const ComponentBoundsConstrainer&);
  37180. ComponentBoundsConstrainer& operator= (const ComponentBoundsConstrainer&);
  37181. };
  37182. #endif // __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  37183. /*** End of inlined file: juce_ComponentBoundsConstrainer.h ***/
  37184. /**
  37185. An object to take care of the logic for dragging components around with the mouse.
  37186. Very easy to use - in your mouseDown() callback, call startDraggingComponent(),
  37187. then in your mouseDrag() callback, call dragComponent().
  37188. When starting a drag, you can give it a ComponentBoundsConstrainer to use
  37189. to limit the component's position and keep it on-screen.
  37190. e.g. @code
  37191. class MyDraggableComp
  37192. {
  37193. ComponentDragger myDragger;
  37194. void mouseDown (const MouseEvent& e)
  37195. {
  37196. myDragger.startDraggingComponent (this, 0);
  37197. }
  37198. void mouseDrag (const MouseEvent& e)
  37199. {
  37200. myDragger.dragComponent (this, e);
  37201. }
  37202. };
  37203. @endcode
  37204. */
  37205. class JUCE_API ComponentDragger
  37206. {
  37207. public:
  37208. /** Creates a ComponentDragger. */
  37209. ComponentDragger();
  37210. /** Destructor. */
  37211. virtual ~ComponentDragger();
  37212. /** Call this from your component's mouseDown() method, to prepare for dragging.
  37213. @param componentToDrag the component that you want to drag
  37214. @param constrainer a constrainer object to use to keep the component
  37215. from going offscreen
  37216. @see dragComponent
  37217. */
  37218. void startDraggingComponent (Component* const componentToDrag,
  37219. ComponentBoundsConstrainer* constrainer);
  37220. /** Call this from your mouseDrag() callback to move the component.
  37221. This will move the component, but will first check the validity of the
  37222. component's new position using the checkPosition() method, which you
  37223. can override if you need to enforce special positioning limits on the
  37224. component.
  37225. @param componentToDrag the component that you want to drag
  37226. @param e the current mouse-drag event
  37227. @see dragComponent
  37228. */
  37229. void dragComponent (Component* const componentToDrag,
  37230. const MouseEvent& e);
  37231. juce_UseDebuggingNewOperator
  37232. private:
  37233. ComponentBoundsConstrainer* constrainer;
  37234. Point<int> originalPos;
  37235. ComponentDragger (const ComponentDragger&);
  37236. ComponentDragger& operator= (const ComponentDragger&);
  37237. };
  37238. #endif // __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  37239. /*** End of inlined file: juce_ComponentDragger.h ***/
  37240. /*** Start of inlined file: juce_ResizableBorderComponent.h ***/
  37241. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37242. #define __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37243. /**
  37244. A component that resizes its parent window when dragged.
  37245. This component forms a frame around the edge of a component, allowing it to
  37246. be dragged by the edges or corners to resize it - like the way windows are
  37247. resized in MSWindows or Linux.
  37248. To use it, just add it to your component, making it fill the entire parent component
  37249. (there's a mouse hit-test that only traps mouse-events which land around the
  37250. edge of the component, so it's even ok to put it on top of any other components
  37251. you're using). Make sure you rescale the resizer component to fill the parent
  37252. each time the parent's size changes.
  37253. @see ResizableCornerComponent
  37254. */
  37255. class JUCE_API ResizableBorderComponent : public Component
  37256. {
  37257. public:
  37258. /** Creates a resizer.
  37259. Pass in the target component which you want to be resized when this one is
  37260. dragged.
  37261. The target component will usually be a parent of the resizer component, but this
  37262. isn't mandatory.
  37263. Remember that when the target component is resized, it'll need to move and
  37264. resize this component to keep it in place, as this won't happen automatically.
  37265. If the constrainer parameter is non-zero, then this object will be used to enforce
  37266. limits on the size and position that the component can be stretched to. Make sure
  37267. that the constrainer isn't deleted while still in use by this object.
  37268. @see ComponentBoundsConstrainer
  37269. */
  37270. ResizableBorderComponent (Component* componentToResize,
  37271. ComponentBoundsConstrainer* constrainer);
  37272. /** Destructor. */
  37273. ~ResizableBorderComponent();
  37274. /** Specifies how many pixels wide the draggable edges of this component are.
  37275. @see getBorderThickness
  37276. */
  37277. void setBorderThickness (const BorderSize& newBorderSize);
  37278. /** Returns the number of pixels wide that the draggable edges of this component are.
  37279. @see setBorderThickness
  37280. */
  37281. const BorderSize getBorderThickness() const;
  37282. /** Represents the different sections of a resizable border, which allow it to
  37283. resized in different ways.
  37284. */
  37285. class Zone
  37286. {
  37287. public:
  37288. enum Zones
  37289. {
  37290. centre = 0,
  37291. left = 1,
  37292. top = 2,
  37293. right = 4,
  37294. bottom = 8
  37295. };
  37296. /** Creates a Zone from a combination of the flags in \enum Zones. */
  37297. explicit Zone (int zoneFlags = 0) throw();
  37298. Zone (const Zone& other) throw();
  37299. Zone& operator= (const Zone& other) throw();
  37300. bool operator== (const Zone& other) const throw();
  37301. bool operator!= (const Zone& other) const throw();
  37302. /** Given a point within a rectangle with a resizable border, this returns the
  37303. zone that the point lies within.
  37304. */
  37305. static const Zone fromPositionOnBorder (const Rectangle<int>& totalSize,
  37306. const BorderSize& border,
  37307. const Point<int>& position);
  37308. /** Returns an appropriate mouse-cursor for this resize zone. */
  37309. const MouseCursor getMouseCursor() const throw();
  37310. /** Returns true if dragging this zone will move the enire object without resizing it. */
  37311. bool isDraggingWholeObject() const throw() { return zone == centre; }
  37312. /** Returns true if dragging this zone will move the object's left edge. */
  37313. bool isDraggingLeftEdge() const throw() { return (zone & left) != 0; }
  37314. /** Returns true if dragging this zone will move the object's right edge. */
  37315. bool isDraggingRightEdge() const throw() { return (zone & right) != 0; }
  37316. /** Returns true if dragging this zone will move the object's top edge. */
  37317. bool isDraggingTopEdge() const throw() { return (zone & top) != 0; }
  37318. /** Returns true if dragging this zone will move the object's bottom edge. */
  37319. bool isDraggingBottomEdge() const throw() { return (zone & bottom) != 0; }
  37320. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  37321. applies to.
  37322. */
  37323. const Rectangle<int> resizeRectangleBy (Rectangle<int> original,
  37324. const Point<int>& distance) const throw();
  37325. /** Resizes this rectangle by the given amount, moving just the edges that this zone
  37326. applies to.
  37327. */
  37328. const Rectangle<float> resizeRectangleBy (Rectangle<float> original,
  37329. const Point<float>& distance) const throw();
  37330. /** Returns the raw flags for this zone. */
  37331. int getZoneFlags() const throw() { return zone; }
  37332. private:
  37333. int zone;
  37334. };
  37335. juce_UseDebuggingNewOperator
  37336. protected:
  37337. /** @internal */
  37338. void paint (Graphics& g);
  37339. /** @internal */
  37340. void mouseEnter (const MouseEvent& e);
  37341. /** @internal */
  37342. void mouseMove (const MouseEvent& e);
  37343. /** @internal */
  37344. void mouseDown (const MouseEvent& e);
  37345. /** @internal */
  37346. void mouseDrag (const MouseEvent& e);
  37347. /** @internal */
  37348. void mouseUp (const MouseEvent& e);
  37349. /** @internal */
  37350. bool hitTest (int x, int y);
  37351. private:
  37352. Component::SafePointer<Component> component;
  37353. ComponentBoundsConstrainer* constrainer;
  37354. BorderSize borderSize;
  37355. Rectangle<int> originalBounds;
  37356. Zone mouseZone;
  37357. void updateMouseZone (const MouseEvent& e);
  37358. ResizableBorderComponent (const ResizableBorderComponent&);
  37359. ResizableBorderComponent& operator= (const ResizableBorderComponent&);
  37360. };
  37361. #endif // __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  37362. /*** End of inlined file: juce_ResizableBorderComponent.h ***/
  37363. /*** Start of inlined file: juce_ResizableCornerComponent.h ***/
  37364. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37365. #define __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37366. /** A component that resizes a parent window when dragged.
  37367. This is the small triangular stripey resizer component you get in the bottom-right
  37368. of windows (more commonly on the Mac than Windows). Put one in the corner of
  37369. a larger component and it will automatically resize its parent when it gets dragged
  37370. around.
  37371. @see ResizableFrameComponent
  37372. */
  37373. class JUCE_API ResizableCornerComponent : public Component
  37374. {
  37375. public:
  37376. /** Creates a resizer.
  37377. Pass in the target component which you want to be resized when this one is
  37378. dragged.
  37379. The target component will usually be a parent of the resizer component, but this
  37380. isn't mandatory.
  37381. Remember that when the target component is resized, it'll need to move and
  37382. resize this component to keep it in place, as this won't happen automatically.
  37383. If the constrainer parameter is non-zero, then this object will be used to enforce
  37384. limits on the size and position that the component can be stretched to. Make sure
  37385. that the constrainer isn't deleted while still in use by this object. If you
  37386. pass a zero in here, no limits will be put on the sizes it can be stretched to.
  37387. @see ComponentBoundsConstrainer
  37388. */
  37389. ResizableCornerComponent (Component* componentToResize,
  37390. ComponentBoundsConstrainer* constrainer);
  37391. /** Destructor. */
  37392. ~ResizableCornerComponent();
  37393. juce_UseDebuggingNewOperator
  37394. protected:
  37395. /** @internal */
  37396. void paint (Graphics& g);
  37397. /** @internal */
  37398. void mouseDown (const MouseEvent& e);
  37399. /** @internal */
  37400. void mouseDrag (const MouseEvent& e);
  37401. /** @internal */
  37402. void mouseUp (const MouseEvent& e);
  37403. /** @internal */
  37404. bool hitTest (int x, int y);
  37405. private:
  37406. Component::SafePointer<Component> component;
  37407. ComponentBoundsConstrainer* constrainer;
  37408. Rectangle<int> originalBounds;
  37409. ResizableCornerComponent (const ResizableCornerComponent&);
  37410. ResizableCornerComponent& operator= (const ResizableCornerComponent&);
  37411. };
  37412. #endif // __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  37413. /*** End of inlined file: juce_ResizableCornerComponent.h ***/
  37414. /**
  37415. A base class for top-level windows that can be dragged around and resized.
  37416. To add content to the window, use its setContentComponent() method to
  37417. give it a component that will remain positioned inside it (leaving a gap around
  37418. the edges for a border).
  37419. It's not advisable to add child components directly to a ResizableWindow: put them
  37420. inside your content component instead. And overriding methods like resized(), moved(), etc
  37421. is also not recommended - instead override these methods for your content component.
  37422. (If for some obscure reason you do need to override these methods, always remember to
  37423. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  37424. decorations correctly).
  37425. By default resizing isn't enabled - use the setResizable() method to enable it and
  37426. to choose the style of resizing to use.
  37427. @see TopLevelWindow
  37428. */
  37429. class JUCE_API ResizableWindow : public TopLevelWindow
  37430. {
  37431. public:
  37432. /** Creates a ResizableWindow.
  37433. This constructor doesn't specify a background colour, so the LookAndFeel's default
  37434. background colour will be used.
  37435. @param name the name to give the component
  37436. @param addToDesktop if true, the window will be automatically added to the
  37437. desktop; if false, you can use it as a child component
  37438. */
  37439. ResizableWindow (const String& name,
  37440. bool addToDesktop);
  37441. /** Creates a ResizableWindow.
  37442. @param name the name to give the component
  37443. @param backgroundColour the colour to use for filling the window's background.
  37444. @param addToDesktop if true, the window will be automatically added to the
  37445. desktop; if false, you can use it as a child component
  37446. */
  37447. ResizableWindow (const String& name,
  37448. const Colour& backgroundColour,
  37449. bool addToDesktop);
  37450. /** Destructor.
  37451. If a content component has been set with setContentComponent(), it
  37452. will be deleted.
  37453. */
  37454. ~ResizableWindow();
  37455. /** Returns the colour currently being used for the window's background.
  37456. As a convenience the window will fill itself with this colour, but you
  37457. can override the paint() method if you need more customised behaviour.
  37458. This method is the same as retrieving the colour for ResizableWindow::backgroundColourId.
  37459. @see setBackgroundColour
  37460. */
  37461. const Colour getBackgroundColour() const throw();
  37462. /** Changes the colour currently being used for the window's background.
  37463. As a convenience the window will fill itself with this colour, but you
  37464. can override the paint() method if you need more customised behaviour.
  37465. Note that the opaque state of this window is altered by this call to reflect
  37466. the opacity of the colour passed-in. On window systems which can't support
  37467. semi-transparent windows this might cause problems, (though it's unlikely you'll
  37468. be using this class as a base for a semi-transparent component anyway).
  37469. You can also use the ResizableWindow::backgroundColourId colour id to set
  37470. this colour.
  37471. @see getBackgroundColour
  37472. */
  37473. void setBackgroundColour (const Colour& newColour);
  37474. /** Make the window resizable or fixed.
  37475. @param shouldBeResizable whether it's resizable at all
  37476. @param useBottomRightCornerResizer if true, it'll add a ResizableCornerComponent at the
  37477. bottom-right; if false, it'll use a ResizableBorderComponent
  37478. around the edge
  37479. @see setResizeLimits, isResizable
  37480. */
  37481. void setResizable (bool shouldBeResizable,
  37482. bool useBottomRightCornerResizer);
  37483. /** True if resizing is enabled.
  37484. @see setResizable
  37485. */
  37486. bool isResizable() const throw();
  37487. /** This sets the maximum and minimum sizes for the window.
  37488. If the window's current size is outside these limits, it will be resized to
  37489. make sure it's within them.
  37490. Calling setBounds() on the component will bypass any size checking - it's only when
  37491. the window is being resized by the user that these values are enforced.
  37492. @see setResizable, setFixedAspectRatio
  37493. */
  37494. void setResizeLimits (int newMinimumWidth,
  37495. int newMinimumHeight,
  37496. int newMaximumWidth,
  37497. int newMaximumHeight) throw();
  37498. /** Returns the bounds constrainer object that this window is using.
  37499. You can access this to change its properties.
  37500. */
  37501. ComponentBoundsConstrainer* getConstrainer() throw() { return constrainer; }
  37502. /** Sets the bounds-constrainer object to use for resizing and dragging this window.
  37503. A pointer to the object you pass in will be kept, but it won't be deleted
  37504. by this object, so it's the caller's responsiblity to manage it.
  37505. If you pass 0, then no contraints will be placed on the positioning of the window.
  37506. */
  37507. void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
  37508. /** Calls the window's setBounds method, after first checking these bounds
  37509. with the current constrainer.
  37510. @see setConstrainer
  37511. */
  37512. void setBoundsConstrained (const Rectangle<int>& bounds);
  37513. /** Returns true if the window is currently in full-screen mode.
  37514. @see setFullScreen
  37515. */
  37516. bool isFullScreen() const;
  37517. /** Puts the window into full-screen mode, or restores it to its normal size.
  37518. If true, the window will become full-screen; if false, it will return to the
  37519. last size it was before being made full-screen.
  37520. @see isFullScreen
  37521. */
  37522. void setFullScreen (bool shouldBeFullScreen);
  37523. /** Returns true if the window is currently minimised.
  37524. @see setMinimised
  37525. */
  37526. bool isMinimised() const;
  37527. /** Minimises the window, or restores it to its previous position and size.
  37528. When being un-minimised, it'll return to the last position and size it
  37529. was in before being minimised.
  37530. @see isMinimised
  37531. */
  37532. void setMinimised (bool shouldMinimise);
  37533. /** Returns a string which encodes the window's current size and position.
  37534. This string will encapsulate the window's size, position, and whether it's
  37535. in full-screen mode. It's intended for letting your application save and
  37536. restore a window's position.
  37537. Use the restoreWindowStateFromString() to restore from a saved state.
  37538. @see restoreWindowStateFromString
  37539. */
  37540. const String getWindowStateAsString();
  37541. /** Restores the window to a previously-saved size and position.
  37542. This restores the window's size, positon and full-screen status from an
  37543. string that was previously created with the getWindowStateAsString()
  37544. method.
  37545. @returns false if the string wasn't a valid window state
  37546. @see getWindowStateAsString
  37547. */
  37548. bool restoreWindowStateFromString (const String& previousState);
  37549. /** Returns the current content component.
  37550. This will be the component set by setContentComponent(), or 0 if none
  37551. has yet been specified.
  37552. @see setContentComponent
  37553. */
  37554. Component* getContentComponent() const throw() { return contentComponent; }
  37555. /** Changes the current content component.
  37556. This sets a component that will be placed in the centre of the ResizableWindow,
  37557. (leaving a space around the edge for the border).
  37558. You should never add components directly to a ResizableWindow (or any of its subclasses)
  37559. with addChildComponent(). Instead, add them to the content component.
  37560. @param newContentComponent the new component to use (or null to not use one) - this
  37561. component will be deleted either when replaced by another call
  37562. to this method, or when the ResizableWindow is deleted.
  37563. To remove a content component without deleting it, use
  37564. setContentComponent (0, false).
  37565. @param deleteOldOne if true, the previous content component will be deleted; if
  37566. false, the previous component will just be removed without
  37567. deleting it.
  37568. @param resizeToFit if true, the ResizableWindow will maintain its size such that
  37569. it always fits around the size of the content component. If false, the
  37570. new content will be resized to fit the current space available.
  37571. */
  37572. void setContentComponent (Component* newContentComponent,
  37573. bool deleteOldOne = true,
  37574. bool resizeToFit = false);
  37575. /** Changes the window so that the content component ends up with the specified size.
  37576. This is basically a setSize call on the window, but which adds on the borders,
  37577. so you can specify the content component's target size.
  37578. */
  37579. void setContentComponentSize (int width, int height);
  37580. /** A set of colour IDs to use to change the colour of various aspects of the window.
  37581. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37582. methods.
  37583. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37584. */
  37585. enum ColourIds
  37586. {
  37587. backgroundColourId = 0x1005700, /**< A colour to use to fill the window's background. */
  37588. };
  37589. juce_UseDebuggingNewOperator
  37590. protected:
  37591. /** @internal */
  37592. void paint (Graphics& g);
  37593. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37594. void moved();
  37595. /** (if overriding this, make sure you call ResizableWindow::resized() in your subclass) */
  37596. void resized();
  37597. /** @internal */
  37598. void mouseDown (const MouseEvent& e);
  37599. /** @internal */
  37600. void mouseDrag (const MouseEvent& e);
  37601. /** @internal */
  37602. void lookAndFeelChanged();
  37603. /** @internal */
  37604. void childBoundsChanged (Component* child);
  37605. /** @internal */
  37606. void parentSizeChanged();
  37607. /** @internal */
  37608. void visibilityChanged();
  37609. /** @internal */
  37610. void activeWindowStatusChanged();
  37611. /** @internal */
  37612. int getDesktopWindowStyleFlags() const;
  37613. /** Returns the width of the border to use around the window.
  37614. @see getContentComponentBorder
  37615. */
  37616. virtual const BorderSize getBorderThickness();
  37617. /** Returns the insets to use when positioning the content component.
  37618. @see getBorderThickness
  37619. */
  37620. virtual const BorderSize getContentComponentBorder();
  37621. #if JUCE_DEBUG
  37622. /** Overridden to warn people about adding components directly to this component
  37623. instead of using setContentComponent().
  37624. If you know what you're doing and are sure you really want to add a component, specify
  37625. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37626. */
  37627. void addChildComponent (Component* child, int zOrder = -1);
  37628. /** Overridden to warn people about adding components directly to this component
  37629. instead of using setContentComponent().
  37630. If you know what you're doing and are sure you really want to add a component, specify
  37631. a base-class method call to Component::addAndMakeVisible(), to side-step this warning.
  37632. */
  37633. void addAndMakeVisible (Component* child, int zOrder = -1);
  37634. #endif
  37635. ScopedPointer <ResizableCornerComponent> resizableCorner;
  37636. ScopedPointer <ResizableBorderComponent> resizableBorder;
  37637. private:
  37638. Component::SafePointer <Component> contentComponent;
  37639. bool resizeToFitContent, fullscreen;
  37640. ComponentDragger dragger;
  37641. Rectangle<int> lastNonFullScreenPos;
  37642. ComponentBoundsConstrainer defaultConstrainer;
  37643. ComponentBoundsConstrainer* constrainer;
  37644. #if JUCE_DEBUG
  37645. bool hasBeenResized;
  37646. #endif
  37647. void updateLastPos();
  37648. ResizableWindow (const ResizableWindow&);
  37649. ResizableWindow& operator= (const ResizableWindow&);
  37650. // (xxx remove these eventually)
  37651. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37652. void getBorderThickness (int& left, int& top, int& right, int& bottom);
  37653. // temporarily here to stop old code compiling, as the parameters for these methods have changed..
  37654. void getContentComponentBorder (int& left, int& top, int& right, int& bottom);
  37655. };
  37656. #endif // __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  37657. /*** End of inlined file: juce_ResizableWindow.h ***/
  37658. /*** Start of inlined file: juce_GlyphArrangement.h ***/
  37659. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37660. #define __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37661. /**
  37662. A glyph from a particular font, with a particular size, style,
  37663. typeface and position.
  37664. @see GlyphArrangement, Font
  37665. */
  37666. class JUCE_API PositionedGlyph
  37667. {
  37668. public:
  37669. PositionedGlyph (const PositionedGlyph& other);
  37670. /** Returns the character the glyph represents. */
  37671. juce_wchar getCharacter() const { return character; }
  37672. /** Checks whether the glyph is actually empty. */
  37673. bool isWhitespace() const { return CharacterFunctions::isWhitespace (character); }
  37674. /** Returns the position of the glyph's left-hand edge. */
  37675. float getLeft() const { return x; }
  37676. /** Returns the position of the glyph's right-hand edge. */
  37677. float getRight() const { return x + w; }
  37678. /** Returns the y position of the glyph's baseline. */
  37679. float getBaselineY() const { return y; }
  37680. /** Returns the y position of the top of the glyph. */
  37681. float getTop() const { return y - font.getAscent(); }
  37682. /** Returns the y position of the bottom of the glyph. */
  37683. float getBottom() const { return y + font.getDescent(); }
  37684. /** Returns the bounds of the glyph. */
  37685. const Rectangle<float> getBounds() const { return Rectangle<float> (x, getTop(), w, font.getHeight()); }
  37686. /** Shifts the glyph's position by a relative amount. */
  37687. void moveBy (float deltaX, float deltaY);
  37688. /** Draws the glyph into a graphics context. */
  37689. void draw (const Graphics& g) const;
  37690. /** Draws the glyph into a graphics context, with an extra transform applied to it. */
  37691. void draw (const Graphics& g, const AffineTransform& transform) const;
  37692. /** Returns the path for this glyph.
  37693. @param path the glyph's outline will be appended to this path
  37694. */
  37695. void createPath (Path& path) const;
  37696. /** Checks to see if a point lies within this glyph. */
  37697. bool hitTest (float x, float y) const;
  37698. juce_UseDebuggingNewOperator
  37699. private:
  37700. friend class GlyphArrangement;
  37701. float x, y, w;
  37702. Font font;
  37703. juce_wchar character;
  37704. int glyph;
  37705. PositionedGlyph (float x, float y, float w, const Font& font, juce_wchar character, int glyph);
  37706. };
  37707. /**
  37708. A set of glyphs, each with a position.
  37709. You can create a GlyphArrangement, text to it and then draw it onto a
  37710. graphics context. It's used internally by the text methods in the
  37711. Graphics class, but can be used directly if more control is needed.
  37712. @see Font, PositionedGlyph
  37713. */
  37714. class JUCE_API GlyphArrangement
  37715. {
  37716. public:
  37717. /** Creates an empty arrangement. */
  37718. GlyphArrangement();
  37719. /** Takes a copy of another arrangement. */
  37720. GlyphArrangement (const GlyphArrangement& other);
  37721. /** Copies another arrangement onto this one.
  37722. To add another arrangement without clearing this one, use addGlyphArrangement().
  37723. */
  37724. GlyphArrangement& operator= (const GlyphArrangement& other);
  37725. /** Destructor. */
  37726. ~GlyphArrangement();
  37727. /** Returns the total number of glyphs in the arrangement. */
  37728. int getNumGlyphs() const throw() { return glyphs.size(); }
  37729. /** Returns one of the glyphs from the arrangement.
  37730. @param index the glyph's index, from 0 to (getNumGlyphs() - 1). Be
  37731. careful not to pass an out-of-range index here, as it
  37732. doesn't do any bounds-checking.
  37733. */
  37734. PositionedGlyph& getGlyph (int index) const;
  37735. /** Clears all text from the arrangement and resets it.
  37736. */
  37737. void clear();
  37738. /** Appends a line of text to the arrangement.
  37739. This will add the text as a single line, where x is the left-hand edge of the
  37740. first character, and y is the position for the text's baseline.
  37741. If the text contains new-lines or carriage-returns, this will ignore them - use
  37742. addJustifiedText() to add multi-line arrangements.
  37743. */
  37744. void addLineOfText (const Font& font,
  37745. const String& text,
  37746. float x, float y);
  37747. /** Adds a line of text, truncating it if it's wider than a specified size.
  37748. This is the same as addLineOfText(), but if the line's width exceeds the value
  37749. specified in maxWidthPixels, it will be truncated using either ellipsis (i.e. dots: "..."),
  37750. if useEllipsis is true, or if this is false, it will just drop any subsequent characters.
  37751. */
  37752. void addCurtailedLineOfText (const Font& font,
  37753. const String& text,
  37754. float x, float y,
  37755. float maxWidthPixels,
  37756. bool useEllipsis);
  37757. /** Adds some multi-line text, breaking lines at word-boundaries if they are too wide.
  37758. This will add text to the arrangement, breaking it into new lines either where there
  37759. is a new-line or carriage-return character in the text, or where a line's width
  37760. exceeds the value set in maxLineWidth.
  37761. Each line that is added will be laid out using the flags set in horizontalLayout, so
  37762. the lines can be left- or right-justified, or centred horizontally in the space
  37763. between x and (x + maxLineWidth).
  37764. The y co-ordinate is the position of the baseline of the first line of text - subsequent
  37765. lines will be placed below it, separated by a distance of font.getHeight().
  37766. */
  37767. void addJustifiedText (const Font& font,
  37768. const String& text,
  37769. float x, float y,
  37770. float maxLineWidth,
  37771. const Justification& horizontalLayout);
  37772. /** Tries to fit some text withing a given space.
  37773. This does its best to make the given text readable within the specified rectangle,
  37774. so it useful for labelling things.
  37775. If the text is too big, it'll be squashed horizontally or broken over multiple lines
  37776. if the maximumLinesToUse value allows this. If the text just won't fit into the space,
  37777. it'll cram as much as possible in there, and put some ellipsis at the end to show that
  37778. it's been truncated.
  37779. A Justification parameter lets you specify how the text is laid out within the rectangle,
  37780. both horizontally and vertically.
  37781. @see Graphics::drawFittedText
  37782. */
  37783. void addFittedText (const Font& font,
  37784. const String& text,
  37785. float x, float y, float width, float height,
  37786. const Justification& layout,
  37787. int maximumLinesToUse,
  37788. float minimumHorizontalScale = 0.7f);
  37789. /** Appends another glyph arrangement to this one. */
  37790. void addGlyphArrangement (const GlyphArrangement& other);
  37791. /** Draws this glyph arrangement to a graphics context.
  37792. This uses cached bitmaps so is much faster than the draw (Graphics&, const AffineTransform&)
  37793. method, which renders the glyphs as filled vectors.
  37794. */
  37795. void draw (const Graphics& g) const;
  37796. /** Draws this glyph arrangement to a graphics context.
  37797. This renders the paths as filled vectors, so is far slower than the draw (Graphics&)
  37798. method for non-transformed arrangements.
  37799. */
  37800. void draw (const Graphics& g, const AffineTransform& transform) const;
  37801. /** Converts the set of glyphs into a path.
  37802. @param path the glyphs' outlines will be appended to this path
  37803. */
  37804. void createPath (Path& path) const;
  37805. /** Looks for a glyph that contains the given co-ordinate.
  37806. @returns the index of the glyph, or -1 if none were found.
  37807. */
  37808. int findGlyphIndexAt (float x, float y) const;
  37809. /** Finds the smallest rectangle that will enclose a subset of the glyphs.
  37810. @param startIndex the first glyph to test
  37811. @param numGlyphs the number of glyphs to include; if this is < 0, all glyphs after
  37812. startIndex will be included
  37813. @param includeWhitespace if true, the extent of any whitespace characters will also
  37814. be taken into account
  37815. */
  37816. const Rectangle<float> getBoundingBox (int startIndex, int numGlyphs, bool includeWhitespace) const;
  37817. /** Shifts a set of glyphs by a given amount.
  37818. @param startIndex the first glyph to transform
  37819. @param numGlyphs the number of glyphs to move; if this is < 0, all glyphs after
  37820. startIndex will be used
  37821. @param deltaX the amount to add to their x-positions
  37822. @param deltaY the amount to add to their y-positions
  37823. */
  37824. void moveRangeOfGlyphs (int startIndex, int numGlyphs,
  37825. float deltaX, float deltaY);
  37826. /** Removes a set of glyphs from the arrangement.
  37827. @param startIndex the first glyph to remove
  37828. @param numGlyphs the number of glyphs to remove; if this is < 0, all glyphs after
  37829. startIndex will be deleted
  37830. */
  37831. void removeRangeOfGlyphs (int startIndex, int numGlyphs);
  37832. /** Expands or compresses a set of glyphs horizontally.
  37833. @param startIndex the first glyph to transform
  37834. @param numGlyphs the number of glyphs to stretch; if this is < 0, all glyphs after
  37835. startIndex will be used
  37836. @param horizontalScaleFactor how much to scale their horizontal width by
  37837. */
  37838. void stretchRangeOfGlyphs (int startIndex, int numGlyphs,
  37839. float horizontalScaleFactor);
  37840. /** Justifies a set of glyphs within a given space.
  37841. This moves the glyphs as a block so that the whole thing is located within the
  37842. given rectangle with the specified layout.
  37843. If the Justification::horizontallyJustified flag is specified, each line will
  37844. be stretched out to fill the specified width.
  37845. */
  37846. void justifyGlyphs (int startIndex, int numGlyphs,
  37847. float x, float y, float width, float height,
  37848. const Justification& justification);
  37849. juce_UseDebuggingNewOperator
  37850. private:
  37851. OwnedArray <PositionedGlyph> glyphs;
  37852. int insertEllipsis (const Font& font, float maxXPos, int startIndex, int endIndex);
  37853. int fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  37854. const Justification& justification, float minimumHorizontalScale);
  37855. void spreadOutLine (int start, int numGlyphs, float targetWidth);
  37856. };
  37857. #endif // __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  37858. /*** End of inlined file: juce_GlyphArrangement.h ***/
  37859. /**
  37860. A file open/save dialog box.
  37861. This is a Juce-based file dialog box; to use a native file chooser, see the
  37862. FileChooser class.
  37863. To use one of these, create it and call its show() method. e.g.
  37864. @code
  37865. {
  37866. WildcardFileFilter wildcardFilter ("*.foo", "Foo files");
  37867. FileBrowserComponent browser (FileBrowserComponent::loadFileMode,
  37868. File::nonexistent,
  37869. &wildcardFilter,
  37870. 0);
  37871. FileChooserDialogBox dialogBox ("Open some kind of file",
  37872. "Please choose some kind of file that you want to open...",
  37873. browser,
  37874. getLookAndFeel().alertWindowBackground);
  37875. if (dialogBox.show())
  37876. {
  37877. File selectedFile = browser.getCurrentFile();
  37878. ...
  37879. }
  37880. }
  37881. @endcode
  37882. @see FileChooser
  37883. */
  37884. class JUCE_API FileChooserDialogBox : public ResizableWindow,
  37885. public ButtonListener,
  37886. public FileBrowserListener
  37887. {
  37888. public:
  37889. /** Creates a file chooser box.
  37890. @param title the main title to show at the top of the box
  37891. @param instructions an optional longer piece of text to show below the title in
  37892. a smaller font, describing in more detail what's required.
  37893. @param browserComponent a FileBrowserComponent that will be shown inside this dialog
  37894. box. Make sure you delete this after (but not before!) the
  37895. dialog box has been deleted.
  37896. @param warnAboutOverwritingExistingFiles if true, then the user will be asked to confirm
  37897. if they try to select a file that already exists. (This
  37898. flag is only used when saving files)
  37899. @param backgroundColour the background colour for the top level window
  37900. @see FileBrowserComponent, FilePreviewComponent
  37901. */
  37902. FileChooserDialogBox (const String& title,
  37903. const String& instructions,
  37904. FileBrowserComponent& browserComponent,
  37905. bool warnAboutOverwritingExistingFiles,
  37906. const Colour& backgroundColour);
  37907. /** Destructor. */
  37908. ~FileChooserDialogBox();
  37909. /** Displays and runs the dialog box modally.
  37910. This will show the box with the specified size, returning true if the user
  37911. pressed 'ok', or false if they cancelled.
  37912. Leave the width or height as 0 to use the default size
  37913. */
  37914. bool show (int width = 0, int height = 0);
  37915. /** Displays and runs the dialog box modally.
  37916. This will show the box with the specified size at the specified location,
  37917. returning true if the user pressed 'ok', or false if they cancelled.
  37918. Leave the width or height as 0 to use the default size.
  37919. */
  37920. bool showAt (int x, int y, int width, int height);
  37921. /** A set of colour IDs to use to change the colour of various aspects of the box.
  37922. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  37923. methods.
  37924. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  37925. */
  37926. enum ColourIds
  37927. {
  37928. titleTextColourId = 0x1000850, /**< The colour to use to draw the box's title. */
  37929. };
  37930. /** @internal */
  37931. void buttonClicked (Button* button);
  37932. /** @internal */
  37933. void closeButtonPressed();
  37934. /** @internal */
  37935. void selectionChanged();
  37936. /** @internal */
  37937. void fileClicked (const File& file, const MouseEvent& e);
  37938. /** @internal */
  37939. void fileDoubleClicked (const File& file);
  37940. juce_UseDebuggingNewOperator
  37941. private:
  37942. class ContentComponent : public Component
  37943. {
  37944. public:
  37945. ContentComponent();
  37946. ~ContentComponent();
  37947. void paint (Graphics& g);
  37948. void resized();
  37949. String instructions;
  37950. GlyphArrangement text;
  37951. FileBrowserComponent* chooserComponent;
  37952. FilePreviewComponent* previewComponent;
  37953. TextButton* okButton;
  37954. TextButton* cancelButton;
  37955. };
  37956. ContentComponent* content;
  37957. const bool warnAboutOverwritingExistingFiles;
  37958. FileChooserDialogBox (const FileChooserDialogBox&);
  37959. FileChooserDialogBox& operator= (const FileChooserDialogBox&);
  37960. };
  37961. #endif // __JUCE_FILECHOOSERDIALOGBOX_JUCEHEADER__
  37962. /*** End of inlined file: juce_FileChooserDialogBox.h ***/
  37963. #endif
  37964. #ifndef __JUCE_FILEFILTER_JUCEHEADER__
  37965. #endif
  37966. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37967. /*** Start of inlined file: juce_FileListComponent.h ***/
  37968. #ifndef __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37969. #define __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  37970. /**
  37971. A component that displays the files in a directory as a listbox.
  37972. This implements the DirectoryContentsDisplayComponent base class so that
  37973. it can be used in a FileBrowserComponent.
  37974. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  37975. class and the FileBrowserListener class.
  37976. @see DirectoryContentsList, FileTreeComponent
  37977. */
  37978. class JUCE_API FileListComponent : public ListBox,
  37979. public DirectoryContentsDisplayComponent,
  37980. private ListBoxModel,
  37981. private ChangeListener
  37982. {
  37983. public:
  37984. /** Creates a listbox to show the contents of a specified directory.
  37985. */
  37986. FileListComponent (DirectoryContentsList& listToShow);
  37987. /** Destructor. */
  37988. ~FileListComponent();
  37989. /** Returns the number of files the user has got selected.
  37990. @see getSelectedFile
  37991. */
  37992. int getNumSelectedFiles() const;
  37993. /** Returns one of the files that the user has currently selected.
  37994. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  37995. @see getNumSelectedFiles
  37996. */
  37997. const File getSelectedFile (int index = 0) const;
  37998. /** Deselects any files that are currently selected. */
  37999. void deselectAllFiles();
  38000. /** Scrolls to the top of the list. */
  38001. void scrollToTop();
  38002. /** @internal */
  38003. void changeListenerCallback (void*);
  38004. /** @internal */
  38005. int getNumRows();
  38006. /** @internal */
  38007. void paintListBoxItem (int, Graphics&, int, int, bool);
  38008. /** @internal */
  38009. Component* refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate);
  38010. /** @internal */
  38011. void selectedRowsChanged (int lastRowSelected);
  38012. /** @internal */
  38013. void deleteKeyPressed (int currentSelectedRow);
  38014. /** @internal */
  38015. void returnKeyPressed (int currentSelectedRow);
  38016. juce_UseDebuggingNewOperator
  38017. private:
  38018. FileListComponent (const FileListComponent&);
  38019. FileListComponent& operator= (const FileListComponent&);
  38020. File lastDirectory;
  38021. };
  38022. #endif // __JUCE_FILELISTCOMPONENT_JUCEHEADER__
  38023. /*** End of inlined file: juce_FileListComponent.h ***/
  38024. #endif
  38025. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38026. /*** Start of inlined file: juce_FilenameComponent.h ***/
  38027. #ifndef __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38028. #define __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38029. class FilenameComponent;
  38030. /**
  38031. Listens for events happening to a FilenameComponent.
  38032. Use FilenameComponent::addListener() and FilenameComponent::removeListener() to
  38033. register one of these objects for event callbacks when the filename is changed.
  38034. @see FilenameComponent
  38035. */
  38036. class JUCE_API FilenameComponentListener
  38037. {
  38038. public:
  38039. /** Destructor. */
  38040. virtual ~FilenameComponentListener() {}
  38041. /** This method is called after the FilenameComponent's file has been changed. */
  38042. virtual void filenameComponentChanged (FilenameComponent* fileComponentThatHasChanged) = 0;
  38043. };
  38044. /**
  38045. Shows a filename as an editable text box, with a 'browse' button and a
  38046. drop-down list for recently selected files.
  38047. A handy component for dialogue boxes where you want the user to be able to
  38048. select a file or directory.
  38049. Attach an FilenameComponentListener using the addListener() method, and it will
  38050. get called each time the user changes the filename, either by browsing for a file
  38051. and clicking 'ok', or by typing a new filename into the box and pressing return.
  38052. @see FileChooser, ComboBox
  38053. */
  38054. class JUCE_API FilenameComponent : public Component,
  38055. public SettableTooltipClient,
  38056. public FileDragAndDropTarget,
  38057. private AsyncUpdater,
  38058. private ButtonListener,
  38059. private ComboBoxListener
  38060. {
  38061. public:
  38062. /** Creates a FilenameComponent.
  38063. @param name the name for this component.
  38064. @param currentFile the file to initially show in the box
  38065. @param canEditFilename if true, the user can manually edit the filename; if false,
  38066. they can only change it by browsing for a new file
  38067. @param isDirectory if true, the file will be treated as a directory, and
  38068. an appropriate directory browser used
  38069. @param isForSaving if true, the file browser will allow non-existent files to
  38070. be picked, as the file is assumed to be used for saving rather
  38071. than loading
  38072. @param fileBrowserWildcard a wildcard pattern to use in the file browser - e.g. "*.txt;*.foo".
  38073. If an empty string is passed in, then the pattern is assumed to be "*"
  38074. @param enforcedSuffix if this is non-empty, it is treated as a suffix that will be added
  38075. to any filenames that are entered or chosen
  38076. @param textWhenNothingSelected the message to display in the box before any filename is entered. (This
  38077. will only appear if the initial file isn't valid)
  38078. */
  38079. FilenameComponent (const String& name,
  38080. const File& currentFile,
  38081. bool canEditFilename,
  38082. bool isDirectory,
  38083. bool isForSaving,
  38084. const String& fileBrowserWildcard,
  38085. const String& enforcedSuffix,
  38086. const String& textWhenNothingSelected);
  38087. /** Destructor. */
  38088. ~FilenameComponent();
  38089. /** Returns the currently displayed filename. */
  38090. const File getCurrentFile() const;
  38091. /** Changes the current filename.
  38092. If addToRecentlyUsedList is true, the filename will also be added to the
  38093. drop-down list of recent files.
  38094. If sendChangeNotification is false, then the listeners won't be told of the
  38095. change.
  38096. */
  38097. void setCurrentFile (File newFile,
  38098. bool addToRecentlyUsedList,
  38099. bool sendChangeNotification = true);
  38100. /** Changes whether the use can type into the filename box.
  38101. */
  38102. void setFilenameIsEditable (bool shouldBeEditable);
  38103. /** Sets a file or directory to be the default starting point for the browser to show.
  38104. This is only used if the current file hasn't been set.
  38105. */
  38106. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  38107. /** Returns all the entries on the recent files list.
  38108. This can be used in conjunction with setRecentlyUsedFilenames() for saving the
  38109. state of this list.
  38110. @see setRecentlyUsedFilenames
  38111. */
  38112. const StringArray getRecentlyUsedFilenames() const;
  38113. /** Sets all the entries on the recent files list.
  38114. This can be used in conjunction with getRecentlyUsedFilenames() for saving the
  38115. state of this list.
  38116. @see getRecentlyUsedFilenames, addRecentlyUsedFile
  38117. */
  38118. void setRecentlyUsedFilenames (const StringArray& filenames);
  38119. /** Adds an entry to the recently-used files dropdown list.
  38120. If the file is already in the list, it will be moved to the top. A limit
  38121. is also placed on the number of items that are kept in the list.
  38122. @see getRecentlyUsedFilenames, setRecentlyUsedFilenames, setMaxNumberOfRecentFiles
  38123. */
  38124. void addRecentlyUsedFile (const File& file);
  38125. /** Changes the limit for the number of files that will be stored in the recent-file list.
  38126. */
  38127. void setMaxNumberOfRecentFiles (int newMaximum);
  38128. /** Changes the text shown on the 'browse' button.
  38129. By default this button just says "..." but you can change it. The button itself
  38130. can be changed using the look-and-feel classes, so it might not actually have any
  38131. text on it.
  38132. */
  38133. void setBrowseButtonText (const String& browseButtonText);
  38134. /** Adds a listener that will be called when the selected file is changed. */
  38135. void addListener (FilenameComponentListener* listener);
  38136. /** Removes a previously-registered listener. */
  38137. void removeListener (FilenameComponentListener* listener);
  38138. /** Gives the component a tooltip. */
  38139. void setTooltip (const String& newTooltip);
  38140. /** @internal */
  38141. void paintOverChildren (Graphics& g);
  38142. /** @internal */
  38143. void resized();
  38144. /** @internal */
  38145. void lookAndFeelChanged();
  38146. /** @internal */
  38147. bool isInterestedInFileDrag (const StringArray& files);
  38148. /** @internal */
  38149. void filesDropped (const StringArray& files, int, int);
  38150. /** @internal */
  38151. void fileDragEnter (const StringArray& files, int, int);
  38152. /** @internal */
  38153. void fileDragExit (const StringArray& files);
  38154. juce_UseDebuggingNewOperator
  38155. private:
  38156. ComboBox filenameBox;
  38157. String lastFilename;
  38158. ScopedPointer<Button> browseButton;
  38159. int maxRecentFiles;
  38160. bool isDir, isSaving, isFileDragOver;
  38161. String wildcard, enforcedSuffix, browseButtonText;
  38162. ListenerList <FilenameComponentListener> listeners;
  38163. File defaultBrowseFile;
  38164. void comboBoxChanged (ComboBox*);
  38165. void buttonClicked (Button* button);
  38166. void handleAsyncUpdate();
  38167. FilenameComponent (const FilenameComponent&);
  38168. FilenameComponent& operator= (const FilenameComponent&);
  38169. };
  38170. #endif // __JUCE_FILENAMECOMPONENT_JUCEHEADER__
  38171. /*** End of inlined file: juce_FilenameComponent.h ***/
  38172. #endif
  38173. #ifndef __JUCE_FILEPREVIEWCOMPONENT_JUCEHEADER__
  38174. #endif
  38175. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38176. /*** Start of inlined file: juce_FileSearchPathListComponent.h ***/
  38177. #ifndef __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38178. #define __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38179. /**
  38180. Shows a set of file paths in a list, allowing them to be added, removed or
  38181. re-ordered.
  38182. @see FileSearchPath
  38183. */
  38184. class JUCE_API FileSearchPathListComponent : public Component,
  38185. public SettableTooltipClient,
  38186. public FileDragAndDropTarget,
  38187. private ButtonListener,
  38188. private ListBoxModel
  38189. {
  38190. public:
  38191. /** Creates an empty FileSearchPathListComponent.
  38192. */
  38193. FileSearchPathListComponent();
  38194. /** Destructor. */
  38195. ~FileSearchPathListComponent();
  38196. /** Returns the path as it is currently shown. */
  38197. const FileSearchPath& getPath() const throw() { return path; }
  38198. /** Changes the current path. */
  38199. void setPath (const FileSearchPath& newPath);
  38200. /** Sets a file or directory to be the default starting point for the browser to show.
  38201. This is only used if the current file hasn't been set.
  38202. */
  38203. void setDefaultBrowseTarget (const File& newDefaultDirectory);
  38204. /** A set of colour IDs to use to change the colour of various aspects of the label.
  38205. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38206. methods.
  38207. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38208. */
  38209. enum ColourIds
  38210. {
  38211. backgroundColourId = 0x1004100, /**< The background colour to fill the component with.
  38212. Make this transparent if you don't want the background to be filled. */
  38213. };
  38214. /** @internal */
  38215. int getNumRows();
  38216. /** @internal */
  38217. void paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected);
  38218. /** @internal */
  38219. void deleteKeyPressed (int lastRowSelected);
  38220. /** @internal */
  38221. void returnKeyPressed (int lastRowSelected);
  38222. /** @internal */
  38223. void listBoxItemDoubleClicked (int row, const MouseEvent&);
  38224. /** @internal */
  38225. void selectedRowsChanged (int lastRowSelected);
  38226. /** @internal */
  38227. void resized();
  38228. /** @internal */
  38229. void paint (Graphics& g);
  38230. /** @internal */
  38231. bool isInterestedInFileDrag (const StringArray& files);
  38232. /** @internal */
  38233. void filesDropped (const StringArray& files, int, int);
  38234. /** @internal */
  38235. void buttonClicked (Button* button);
  38236. juce_UseDebuggingNewOperator
  38237. private:
  38238. FileSearchPath path;
  38239. File defaultBrowseTarget;
  38240. ListBox* listBox;
  38241. Button* addButton;
  38242. Button* removeButton;
  38243. TextButton* changeButton;
  38244. DrawableButton* upButton;
  38245. DrawableButton* downButton;
  38246. void changed();
  38247. void updateButtons();
  38248. FileSearchPathListComponent (const FileSearchPathListComponent&);
  38249. FileSearchPathListComponent& operator= (const FileSearchPathListComponent&);
  38250. };
  38251. #endif // __JUCE_FILESEARCHPATHLISTCOMPONENT_JUCEHEADER__
  38252. /*** End of inlined file: juce_FileSearchPathListComponent.h ***/
  38253. #endif
  38254. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38255. /*** Start of inlined file: juce_FileTreeComponent.h ***/
  38256. #ifndef __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38257. #define __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38258. /**
  38259. A component that displays the files in a directory as a treeview.
  38260. This implements the DirectoryContentsDisplayComponent base class so that
  38261. it can be used in a FileBrowserComponent.
  38262. To attach a listener to it, use its DirectoryContentsDisplayComponent base
  38263. class and the FileBrowserListener class.
  38264. @see DirectoryContentsList, FileListComponent
  38265. */
  38266. class JUCE_API FileTreeComponent : public TreeView,
  38267. public DirectoryContentsDisplayComponent
  38268. {
  38269. public:
  38270. /** Creates a listbox to show the contents of a specified directory.
  38271. */
  38272. FileTreeComponent (DirectoryContentsList& listToShow);
  38273. /** Destructor. */
  38274. ~FileTreeComponent();
  38275. /** Returns the number of files the user has got selected.
  38276. @see getSelectedFile
  38277. */
  38278. int getNumSelectedFiles() const { return TreeView::getNumSelectedItems(); }
  38279. /** Returns one of the files that the user has currently selected.
  38280. The index should be in the range 0 to (getNumSelectedFiles() - 1).
  38281. @see getNumSelectedFiles
  38282. */
  38283. const File getSelectedFile (int index = 0) const;
  38284. /** Deselects any files that are currently selected. */
  38285. void deselectAllFiles();
  38286. /** Scrolls the list to the top. */
  38287. void scrollToTop();
  38288. /** Setting a name for this allows tree items to be dragged.
  38289. The string that you pass in here will be returned by the getDragSourceDescription()
  38290. of the items in the tree. For more info, see TreeViewItem::getDragSourceDescription().
  38291. */
  38292. void setDragAndDropDescription (const String& description);
  38293. /** Returns the last value that was set by setDragAndDropDescription().
  38294. */
  38295. const String& getDragAndDropDescription() const throw() { return dragAndDropDescription; }
  38296. juce_UseDebuggingNewOperator
  38297. private:
  38298. String dragAndDropDescription;
  38299. FileTreeComponent (const FileTreeComponent&);
  38300. FileTreeComponent& operator= (const FileTreeComponent&);
  38301. };
  38302. #endif // __JUCE_FILETREECOMPONENT_JUCEHEADER__
  38303. /*** End of inlined file: juce_FileTreeComponent.h ***/
  38304. #endif
  38305. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38306. /*** Start of inlined file: juce_ImagePreviewComponent.h ***/
  38307. #ifndef __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38308. #define __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38309. /**
  38310. A simple preview component that shows thumbnails of image files.
  38311. @see FileChooserDialogBox, FilePreviewComponent
  38312. */
  38313. class JUCE_API ImagePreviewComponent : public FilePreviewComponent,
  38314. private Timer
  38315. {
  38316. public:
  38317. /** Creates an ImagePreviewComponent. */
  38318. ImagePreviewComponent();
  38319. /** Destructor. */
  38320. ~ImagePreviewComponent();
  38321. /** @internal */
  38322. void selectedFileChanged (const File& newSelectedFile);
  38323. /** @internal */
  38324. void paint (Graphics& g);
  38325. /** @internal */
  38326. void timerCallback();
  38327. juce_UseDebuggingNewOperator
  38328. private:
  38329. File fileToLoad;
  38330. Image currentThumbnail;
  38331. String currentDetails;
  38332. void getThumbSize (int& w, int& h) const;
  38333. ImagePreviewComponent (const ImagePreviewComponent&);
  38334. ImagePreviewComponent& operator= (const ImagePreviewComponent&);
  38335. };
  38336. #endif // __JUCE_IMAGEPREVIEWCOMPONENT_JUCEHEADER__
  38337. /*** End of inlined file: juce_ImagePreviewComponent.h ***/
  38338. #endif
  38339. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38340. /*** Start of inlined file: juce_WildcardFileFilter.h ***/
  38341. #ifndef __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38342. #define __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38343. /**
  38344. A type of FileFilter that works by wildcard pattern matching.
  38345. This filter only allows files that match one of the specified patterns, but
  38346. allows all directories through.
  38347. @see FileFilter, DirectoryContentsList, FileListComponent, FileBrowserComponent
  38348. */
  38349. class JUCE_API WildcardFileFilter : public FileFilter
  38350. {
  38351. public:
  38352. /**
  38353. Creates a wildcard filter for one or more patterns.
  38354. The wildcardPatterns parameter is a comma or semicolon-delimited set of
  38355. patterns, e.g. "*.wav;*.aiff" would look for files ending in either .wav
  38356. or .aiff.
  38357. The description is a name to show the user in a list of possible patterns, so
  38358. for the wav/aiff example, your description might be "audio files".
  38359. */
  38360. WildcardFileFilter (const String& fileWildcardPatterns,
  38361. const String& directoryWildcardPatterns,
  38362. const String& description);
  38363. /** Destructor. */
  38364. ~WildcardFileFilter();
  38365. /** Returns true if the filename matches one of the patterns specified. */
  38366. bool isFileSuitable (const File& file) const;
  38367. /** This always returns true. */
  38368. bool isDirectorySuitable (const File& file) const;
  38369. juce_UseDebuggingNewOperator
  38370. private:
  38371. StringArray fileWildcards, directoryWildcards;
  38372. static void parse (const String& pattern, StringArray& result);
  38373. static bool match (const File& file, const StringArray& wildcards);
  38374. };
  38375. #endif // __JUCE_WILDCARDFILEFILTER_JUCEHEADER__
  38376. /*** End of inlined file: juce_WildcardFileFilter.h ***/
  38377. #endif
  38378. #ifndef __JUCE_COMPONENT_JUCEHEADER__
  38379. #endif
  38380. #ifndef __JUCE_COMPONENTLISTENER_JUCEHEADER__
  38381. #endif
  38382. #ifndef __JUCE_DESKTOP_JUCEHEADER__
  38383. #endif
  38384. #ifndef __JUCE_MODALCOMPONENTMANAGER_JUCEHEADER__
  38385. #endif
  38386. #ifndef __JUCE_KEYBOARDFOCUSTRAVERSER_JUCEHEADER__
  38387. #endif
  38388. #ifndef __JUCE_KEYLISTENER_JUCEHEADER__
  38389. #endif
  38390. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38391. /*** Start of inlined file: juce_KeyMappingEditorComponent.h ***/
  38392. #ifndef __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38393. #define __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38394. /*** Start of inlined file: juce_KeyPressMappingSet.h ***/
  38395. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38396. #define __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38397. /**
  38398. Manages and edits a list of keypresses, which it uses to invoke the appropriate
  38399. command in a ApplicationCommandManager.
  38400. Normally, you won't actually create a KeyPressMappingSet directly, because
  38401. each ApplicationCommandManager contains its own KeyPressMappingSet, so typically
  38402. you'd create yourself an ApplicationCommandManager, and call its
  38403. ApplicationCommandManager::getKeyMappings() method to get a pointer to its
  38404. KeyPressMappingSet.
  38405. For one of these to actually use keypresses, you'll need to add it as a KeyListener
  38406. to the top-level component for which you want to handle keystrokes. So for example:
  38407. @code
  38408. class MyMainWindow : public Component
  38409. {
  38410. ApplicationCommandManager* myCommandManager;
  38411. public:
  38412. MyMainWindow()
  38413. {
  38414. myCommandManager = new ApplicationCommandManager();
  38415. // first, make sure the command manager has registered all the commands that its
  38416. // targets can perform..
  38417. myCommandManager->registerAllCommandsForTarget (myCommandTarget1);
  38418. myCommandManager->registerAllCommandsForTarget (myCommandTarget2);
  38419. // this will use the command manager to initialise the KeyPressMappingSet with
  38420. // the default keypresses that were specified when the targets added their commands
  38421. // to the manager.
  38422. myCommandManager->getKeyMappings()->resetToDefaultMappings();
  38423. // having set up the default key-mappings, you might now want to load the last set
  38424. // of mappings that the user configured.
  38425. myCommandManager->getKeyMappings()->restoreFromXml (lastSavedKeyMappingsXML);
  38426. // Now tell our top-level window to send any keypresses that arrive to the
  38427. // KeyPressMappingSet, which will use them to invoke the appropriate commands.
  38428. addKeyListener (myCommandManager->getKeyMappings());
  38429. }
  38430. ...
  38431. }
  38432. @endcode
  38433. KeyPressMappingSet derives from ChangeBroadcaster so that interested parties can
  38434. register to be told when a command or mapping is added, removed, etc.
  38435. There's also a UI component called KeyMappingEditorComponent that can be used
  38436. to easily edit the key mappings.
  38437. @see Component::addKeyListener(), KeyMappingEditorComponent, ApplicationCommandManager
  38438. */
  38439. class JUCE_API KeyPressMappingSet : public KeyListener,
  38440. public ChangeBroadcaster,
  38441. public FocusChangeListener
  38442. {
  38443. public:
  38444. /** Creates a KeyPressMappingSet for a given command manager.
  38445. Normally, you won't actually create a KeyPressMappingSet directly, because
  38446. each ApplicationCommandManager contains its own KeyPressMappingSet, so the
  38447. best thing to do is to create your ApplicationCommandManager, and use the
  38448. ApplicationCommandManager::getKeyMappings() method to access its mappings.
  38449. When a suitable keypress happens, the manager's invoke() method will be
  38450. used to invoke the appropriate command.
  38451. @see ApplicationCommandManager
  38452. */
  38453. explicit KeyPressMappingSet (ApplicationCommandManager* commandManager);
  38454. /** Creates an copy of a KeyPressMappingSet. */
  38455. KeyPressMappingSet (const KeyPressMappingSet& other);
  38456. /** Destructor. */
  38457. ~KeyPressMappingSet();
  38458. ApplicationCommandManager* getCommandManager() const throw() { return commandManager; }
  38459. /** Returns a list of keypresses that are assigned to a particular command.
  38460. @param commandID the command's ID
  38461. */
  38462. const Array <KeyPress> getKeyPressesAssignedToCommand (CommandID commandID) const;
  38463. /** Assigns a keypress to a command.
  38464. If the keypress is already assigned to a different command, it will first be
  38465. removed from that command, to avoid it triggering multiple functions.
  38466. @param commandID the ID of the command that you want to add a keypress to. If
  38467. this is 0, the keypress will be removed from anything that it
  38468. was previously assigned to, but not re-assigned
  38469. @param newKeyPress the new key-press
  38470. @param insertIndex if this is less than zero, the key will be appended to the
  38471. end of the list of keypresses; otherwise the new keypress will
  38472. be inserted into the existing list at this index
  38473. */
  38474. void addKeyPress (CommandID commandID,
  38475. const KeyPress& newKeyPress,
  38476. int insertIndex = -1);
  38477. /** Reset all mappings to the defaults, as dictated by the ApplicationCommandManager.
  38478. @see resetToDefaultMapping
  38479. */
  38480. void resetToDefaultMappings();
  38481. /** Resets all key-mappings to the defaults for a particular command.
  38482. @see resetToDefaultMappings
  38483. */
  38484. void resetToDefaultMapping (CommandID commandID);
  38485. /** Removes all keypresses that are assigned to any commands. */
  38486. void clearAllKeyPresses();
  38487. /** Removes all keypresses that are assigned to a particular command. */
  38488. void clearAllKeyPresses (CommandID commandID);
  38489. /** Removes one of the keypresses that are assigned to a command.
  38490. See the getKeyPressesAssignedToCommand() for the list of keypresses to
  38491. which the keyPressIndex refers.
  38492. */
  38493. void removeKeyPress (CommandID commandID, int keyPressIndex);
  38494. /** Removes a keypress from any command that it may be assigned to.
  38495. */
  38496. void removeKeyPress (const KeyPress& keypress);
  38497. /** Returns true if the given command is linked to this key. */
  38498. bool containsMapping (CommandID commandID, const KeyPress& keyPress) const throw();
  38499. /** Looks for a command that corresponds to a keypress.
  38500. @returns the UID of the command or 0 if none was found
  38501. */
  38502. CommandID findCommandForKeyPress (const KeyPress& keyPress) const throw();
  38503. /** Tries to recreate the mappings from a previously stored state.
  38504. The XML passed in must have been created by the createXml() method.
  38505. If the stored state makes any reference to commands that aren't
  38506. currently available, these will be ignored.
  38507. If the set of mappings being loaded was a set of differences (using createXml (true)),
  38508. then this will call resetToDefaultMappings() and then merge the saved mappings
  38509. on top. If the saved set was created with createXml (false), then this method
  38510. will first clear all existing mappings and load the saved ones as a complete set.
  38511. @returns true if it manages to load the XML correctly
  38512. @see createXml
  38513. */
  38514. bool restoreFromXml (const XmlElement& xmlVersion);
  38515. /** Creates an XML representation of the current mappings.
  38516. This will produce a lump of XML that can be later reloaded using
  38517. restoreFromXml() to recreate the current mapping state.
  38518. The object that is returned must be deleted by the caller.
  38519. @param saveDifferencesFromDefaultSet if this is false, then all keypresses
  38520. will be saved into the XML. If it's true, then the XML will
  38521. only store the differences between the current mappings and
  38522. the default mappings you'd get from calling resetToDefaultMappings().
  38523. The advantage of saving a set of differences from the default is that
  38524. if you change the default mappings (in a new version of your app, for
  38525. example), then these will be merged into a user's saved preferences.
  38526. @see restoreFromXml
  38527. */
  38528. XmlElement* createXml (bool saveDifferencesFromDefaultSet) const;
  38529. /** @internal */
  38530. bool keyPressed (const KeyPress& key, Component* originatingComponent);
  38531. /** @internal */
  38532. bool keyStateChanged (bool isKeyDown, Component* originatingComponent);
  38533. /** @internal */
  38534. void globalFocusChanged (Component* focusedComponent);
  38535. juce_UseDebuggingNewOperator
  38536. private:
  38537. ApplicationCommandManager* commandManager;
  38538. struct CommandMapping
  38539. {
  38540. CommandID commandID;
  38541. Array <KeyPress> keypresses;
  38542. bool wantsKeyUpDownCallbacks;
  38543. };
  38544. OwnedArray <CommandMapping> mappings;
  38545. struct KeyPressTime
  38546. {
  38547. KeyPress key;
  38548. uint32 timeWhenPressed;
  38549. };
  38550. OwnedArray <KeyPressTime> keysDown;
  38551. void handleMessage (const Message& message);
  38552. void invokeCommand (const CommandID commandID,
  38553. const KeyPress& keyPress,
  38554. const bool isKeyDown,
  38555. const int millisecsSinceKeyPressed,
  38556. Component* const originatingComponent) const;
  38557. KeyPressMappingSet& operator= (const KeyPressMappingSet&);
  38558. };
  38559. #endif // __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38560. /*** End of inlined file: juce_KeyPressMappingSet.h ***/
  38561. /**
  38562. A component to allow editing of the keymaps stored by a KeyPressMappingSet
  38563. object.
  38564. @see KeyPressMappingSet
  38565. */
  38566. class JUCE_API KeyMappingEditorComponent : public Component,
  38567. public TreeViewItem,
  38568. public ChangeListener,
  38569. private ButtonListener
  38570. {
  38571. public:
  38572. /** Creates a KeyMappingEditorComponent.
  38573. @param mappingSet this is the set of mappings to display and
  38574. edit. Make sure the mappings object is not
  38575. deleted before this component!
  38576. @param showResetToDefaultButton if true, then at the bottom of the
  38577. list, the component will include a 'reset to
  38578. defaults' button.
  38579. */
  38580. KeyMappingEditorComponent (KeyPressMappingSet* mappingSet,
  38581. bool showResetToDefaultButton);
  38582. /** Destructor. */
  38583. virtual ~KeyMappingEditorComponent();
  38584. /** Sets up the colours to use for parts of the component.
  38585. @param mainBackground colour to use for most of the background
  38586. @param textColour colour to use for the text
  38587. */
  38588. void setColours (const Colour& mainBackground,
  38589. const Colour& textColour);
  38590. /** Returns the KeyPressMappingSet that this component is acting upon.
  38591. */
  38592. KeyPressMappingSet* getMappings() const throw() { return mappings; }
  38593. /** Can be overridden if some commands need to be excluded from the list.
  38594. By default this will use the KeyPressMappingSet's shouldCommandBeVisibleInEditor()
  38595. method to decide what to return, but you can override it to handle special cases.
  38596. */
  38597. virtual bool shouldCommandBeIncluded (CommandID commandID);
  38598. /** Can be overridden to indicate that some commands are shown as read-only.
  38599. By default this will use the KeyPressMappingSet's shouldCommandBeReadOnlyInEditor()
  38600. method to decide what to return, but you can override it to handle special cases.
  38601. */
  38602. virtual bool isCommandReadOnly (CommandID commandID);
  38603. /** This can be overridden to let you change the format of the string used
  38604. to describe a keypress.
  38605. This is handy if you're using non-standard KeyPress objects, e.g. for custom
  38606. keys that are triggered by something else externally. If you override the
  38607. method, be sure to let the base class's method handle keys you're not
  38608. interested in.
  38609. */
  38610. virtual const String getDescriptionForKeyPress (const KeyPress& key);
  38611. /** A set of colour IDs to use to change the colour of various aspects of the editor.
  38612. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38613. methods.
  38614. To change the colours of the menu that pops up
  38615. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38616. */
  38617. enum ColourIds
  38618. {
  38619. backgroundColourId = 0x100ad00, /**< The background colour to fill the editor background. */
  38620. textColourId = 0x100ad01, /**< The colour for the text. */
  38621. };
  38622. /** @internal */
  38623. void parentHierarchyChanged();
  38624. /** @internal */
  38625. void resized();
  38626. /** @internal */
  38627. void changeListenerCallback (void*);
  38628. /** @internal */
  38629. bool mightContainSubItems();
  38630. /** @internal */
  38631. const String getUniqueName() const;
  38632. /** @internal */
  38633. void buttonClicked (Button* button);
  38634. juce_UseDebuggingNewOperator
  38635. private:
  38636. KeyPressMappingSet* mappings;
  38637. TreeView* tree;
  38638. friend class KeyMappingTreeViewItem;
  38639. friend class KeyCategoryTreeViewItem;
  38640. friend class KeyMappingItemComponent;
  38641. friend class KeyMappingChangeButton;
  38642. TextButton* resetButton;
  38643. void assignNewKey (CommandID commandID, int index);
  38644. KeyMappingEditorComponent (const KeyMappingEditorComponent&);
  38645. KeyMappingEditorComponent& operator= (const KeyMappingEditorComponent&);
  38646. };
  38647. #endif // __JUCE_KEYMAPPINGEDITORCOMPONENT_JUCEHEADER__
  38648. /*** End of inlined file: juce_KeyMappingEditorComponent.h ***/
  38649. #endif
  38650. #ifndef __JUCE_KEYPRESS_JUCEHEADER__
  38651. #endif
  38652. #ifndef __JUCE_KEYPRESSMAPPINGSET_JUCEHEADER__
  38653. #endif
  38654. #ifndef __JUCE_MODIFIERKEYS_JUCEHEADER__
  38655. #endif
  38656. #ifndef __JUCE_TEXTINPUTTARGET_JUCEHEADER__
  38657. #endif
  38658. #ifndef __JUCE_COMPONENTANIMATOR_JUCEHEADER__
  38659. #endif
  38660. #ifndef __JUCE_COMPONENTBOUNDSCONSTRAINER_JUCEHEADER__
  38661. #endif
  38662. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38663. /*** Start of inlined file: juce_ComponentMovementWatcher.h ***/
  38664. #ifndef __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38665. #define __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38666. /** An object that watches for any movement of a component or any of its parent components.
  38667. This makes it easy to check when a component is moved relative to its top-level
  38668. peer window. The normal Component::moved() method is only called when a component
  38669. moves relative to its immediate parent, and sometimes you want to know if any of
  38670. components higher up the tree have moved (which of course will affect the overall
  38671. position of all their sub-components).
  38672. It also includes a callback that lets you know when the top-level peer is changed.
  38673. This class is used by specialised components like OpenGLComponent or QuickTimeComponent
  38674. because they need to keep their custom windows in the right place and respond to
  38675. changes in the peer.
  38676. */
  38677. class JUCE_API ComponentMovementWatcher : public ComponentListener
  38678. {
  38679. public:
  38680. /** Creates a ComponentMovementWatcher to watch a given target component. */
  38681. ComponentMovementWatcher (Component* component);
  38682. /** Destructor. */
  38683. ~ComponentMovementWatcher();
  38684. /** This callback happens when the component that is being watched is moved
  38685. relative to its top-level peer window, or when it is resized.
  38686. */
  38687. virtual void componentMovedOrResized (bool wasMoved, bool wasResized) = 0;
  38688. /** This callback happens when the component's top-level peer is changed.
  38689. */
  38690. virtual void componentPeerChanged() = 0;
  38691. juce_UseDebuggingNewOperator
  38692. /** @internal */
  38693. void componentParentHierarchyChanged (Component& component);
  38694. /** @internal */
  38695. void componentMovedOrResized (Component& component, bool wasMoved, bool wasResized);
  38696. private:
  38697. Component::SafePointer<Component> component;
  38698. ComponentPeer* lastPeer;
  38699. Array <Component*> registeredParentComps;
  38700. bool reentrant;
  38701. Rectangle<int> lastBounds;
  38702. void unregister();
  38703. void registerWithParentComps();
  38704. ComponentMovementWatcher (const ComponentMovementWatcher&);
  38705. ComponentMovementWatcher& operator= (const ComponentMovementWatcher&);
  38706. };
  38707. #endif // __JUCE_COMPONENTMOVEMENTWATCHER_JUCEHEADER__
  38708. /*** End of inlined file: juce_ComponentMovementWatcher.h ***/
  38709. #endif
  38710. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38711. /*** Start of inlined file: juce_GroupComponent.h ***/
  38712. #ifndef __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38713. #define __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38714. /**
  38715. A component that draws an outline around itself and has an optional title at
  38716. the top, for drawing an outline around a group of controls.
  38717. */
  38718. class JUCE_API GroupComponent : public Component
  38719. {
  38720. public:
  38721. /** Creates a GroupComponent.
  38722. @param componentName the name to give the component
  38723. @param labelText the text to show at the top of the outline
  38724. */
  38725. GroupComponent (const String& componentName = String::empty,
  38726. const String& labelText = String::empty);
  38727. /** Destructor. */
  38728. ~GroupComponent();
  38729. /** Changes the text that's shown at the top of the component. */
  38730. void setText (const String& newText);
  38731. /** Returns the currently displayed text label. */
  38732. const String getText() const;
  38733. /** Sets the positioning of the text label.
  38734. (The default is Justification::left)
  38735. @see getTextLabelPosition
  38736. */
  38737. void setTextLabelPosition (const Justification& justification);
  38738. /** Returns the current text label position.
  38739. @see setTextLabelPosition
  38740. */
  38741. const Justification getTextLabelPosition() const throw() { return justification; }
  38742. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38743. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38744. methods.
  38745. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38746. */
  38747. enum ColourIds
  38748. {
  38749. outlineColourId = 0x1005400, /**< The colour to use for drawing the line around the edge. */
  38750. textColourId = 0x1005410 /**< The colour to use to draw the text label. */
  38751. };
  38752. /** @internal */
  38753. void paint (Graphics& g);
  38754. /** @internal */
  38755. void enablementChanged();
  38756. /** @internal */
  38757. void colourChanged();
  38758. private:
  38759. String text;
  38760. Justification justification;
  38761. GroupComponent (const GroupComponent&);
  38762. GroupComponent& operator= (const GroupComponent&);
  38763. };
  38764. #endif // __JUCE_GROUPCOMPONENT_JUCEHEADER__
  38765. /*** End of inlined file: juce_GroupComponent.h ***/
  38766. #endif
  38767. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38768. /*** Start of inlined file: juce_MultiDocumentPanel.h ***/
  38769. #ifndef __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38770. #define __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  38771. /*** Start of inlined file: juce_TabbedComponent.h ***/
  38772. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38773. #define __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  38774. /*** Start of inlined file: juce_TabbedButtonBar.h ***/
  38775. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38776. #define __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38777. class TabbedButtonBar;
  38778. /** In a TabbedButtonBar, this component is used for each of the buttons.
  38779. If you want to create a TabbedButtonBar with custom tab components, derive
  38780. your component from this class, and override the TabbedButtonBar::createTabButton()
  38781. method to create it instead of the default one.
  38782. @see TabbedButtonBar
  38783. */
  38784. class JUCE_API TabBarButton : public Button
  38785. {
  38786. public:
  38787. /** Creates the tab button. */
  38788. TabBarButton (const String& name,
  38789. TabbedButtonBar* ownerBar,
  38790. int tabIndex);
  38791. /** Destructor. */
  38792. ~TabBarButton();
  38793. /** Chooses the best length for the tab, given the specified depth.
  38794. If the tab is horizontal, this should return its width, and the depth
  38795. specifies its height. If it's vertical, it should return the height, and
  38796. the depth is actually its width.
  38797. */
  38798. virtual int getBestTabLength (int depth);
  38799. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown);
  38800. void clicked (const ModifierKeys& mods);
  38801. bool hitTest (int x, int y);
  38802. juce_UseDebuggingNewOperator
  38803. protected:
  38804. friend class TabbedButtonBar;
  38805. TabbedButtonBar* const owner;
  38806. int tabIndex, overlapPixels;
  38807. DropShadowEffect shadow;
  38808. /** Returns an area of the component that's safe to draw in.
  38809. This deals with the orientation of the tabs, which affects which side is
  38810. touching the tabbed box's content component.
  38811. */
  38812. void getActiveArea (int& x, int& y, int& w, int& h);
  38813. private:
  38814. TabBarButton (const TabBarButton&);
  38815. TabBarButton& operator= (const TabBarButton&);
  38816. };
  38817. /**
  38818. A vertical or horizontal bar containing tabs that you can select.
  38819. You can use one of these to generate things like a dialog box that has
  38820. tabbed pages you can flip between. Attach a ChangeListener to the
  38821. button bar to be told when the user changes the page.
  38822. An easier method than doing this is to use a TabbedComponent, which
  38823. contains its own TabbedButtonBar and which takes care of the layout
  38824. and other housekeeping.
  38825. @see TabbedComponent
  38826. */
  38827. class JUCE_API TabbedButtonBar : public Component,
  38828. public ChangeBroadcaster,
  38829. public ButtonListener
  38830. {
  38831. public:
  38832. /** The placement of the tab-bar
  38833. @see setOrientation, getOrientation
  38834. */
  38835. enum Orientation
  38836. {
  38837. TabsAtTop,
  38838. TabsAtBottom,
  38839. TabsAtLeft,
  38840. TabsAtRight
  38841. };
  38842. /** Creates a TabbedButtonBar with a given placement.
  38843. You can change the orientation later if you need to.
  38844. */
  38845. TabbedButtonBar (Orientation orientation);
  38846. /** Destructor. */
  38847. ~TabbedButtonBar();
  38848. /** Changes the bar's orientation.
  38849. This won't change the bar's actual size - you'll need to do that yourself,
  38850. but this determines which direction the tabs go in, and which side they're
  38851. stuck to.
  38852. */
  38853. void setOrientation (Orientation orientation);
  38854. /** Returns the current orientation.
  38855. @see setOrientation
  38856. */
  38857. Orientation getOrientation() const throw() { return orientation; }
  38858. /** Deletes all the tabs from the bar.
  38859. @see addTab
  38860. */
  38861. void clearTabs();
  38862. /** Adds a tab to the bar.
  38863. Tabs are added in left-to-right reading order.
  38864. If this is the first tab added, it'll also be automatically selected.
  38865. */
  38866. void addTab (const String& tabName,
  38867. const Colour& tabBackgroundColour,
  38868. int insertIndex = -1);
  38869. /** Changes the name of one of the tabs. */
  38870. void setTabName (int tabIndex,
  38871. const String& newName);
  38872. /** Gets rid of one of the tabs. */
  38873. void removeTab (int tabIndex);
  38874. /** Moves a tab to a new index in the list.
  38875. Pass -1 as the index to move it to the end of the list.
  38876. */
  38877. void moveTab (int currentIndex, int newIndex);
  38878. /** Returns the number of tabs in the bar. */
  38879. int getNumTabs() const;
  38880. /** Returns a list of all the tab names in the bar. */
  38881. const StringArray getTabNames() const;
  38882. /** Changes the currently selected tab.
  38883. This will send a change message and cause a synchronous callback to
  38884. the currentTabChanged() method. (But if the given tab is already selected,
  38885. nothing will be done).
  38886. To deselect all the tabs, use an index of -1.
  38887. */
  38888. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  38889. /** Returns the name of the currently selected tab.
  38890. This could be an empty string if none are selected.
  38891. */
  38892. const String& getCurrentTabName() const throw() { return tabs [currentTabIndex]; }
  38893. /** Returns the index of the currently selected tab.
  38894. This could return -1 if none are selected.
  38895. */
  38896. int getCurrentTabIndex() const throw() { return currentTabIndex; }
  38897. /** Returns the button for a specific tab.
  38898. The button that is returned may be deleted later by this component, so don't hang
  38899. on to the pointer that is returned. A null pointer may be returned if the index is
  38900. out of range.
  38901. */
  38902. TabBarButton* getTabButton (int index) const;
  38903. /** Callback method to indicate the selected tab has been changed.
  38904. @see setCurrentTabIndex
  38905. */
  38906. virtual void currentTabChanged (int newCurrentTabIndex,
  38907. const String& newCurrentTabName);
  38908. /** Callback method to indicate that the user has right-clicked on a tab.
  38909. (Or ctrl-clicked on the Mac)
  38910. */
  38911. virtual void popupMenuClickOnTab (int tabIndex, const String& tabName);
  38912. /** Returns the colour of a tab.
  38913. This is the colour that was specified in addTab().
  38914. */
  38915. const Colour getTabBackgroundColour (int tabIndex);
  38916. /** Changes the background colour of a tab.
  38917. @see addTab, getTabBackgroundColour
  38918. */
  38919. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  38920. /** A set of colour IDs to use to change the colour of various aspects of the component.
  38921. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  38922. methods.
  38923. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  38924. */
  38925. enum ColourIds
  38926. {
  38927. tabOutlineColourId = 0x1005812, /**< The colour to use to draw an outline around the tabs. */
  38928. tabTextColourId = 0x1005813, /**< The colour to use to draw the tab names. If this isn't specified,
  38929. the look and feel will choose an appropriate colour. */
  38930. frontOutlineColourId = 0x1005814, /**< The colour to use to draw an outline around the currently-selected tab. */
  38931. frontTextColourId = 0x1005815, /**< The colour to use to draw the currently-selected tab name. If
  38932. this isn't specified, the look and feel will choose an appropriate
  38933. colour. */
  38934. };
  38935. /** @internal */
  38936. void resized();
  38937. /** @internal */
  38938. void buttonClicked (Button* button);
  38939. /** @internal */
  38940. void lookAndFeelChanged();
  38941. juce_UseDebuggingNewOperator
  38942. protected:
  38943. /** This creates one of the tabs.
  38944. If you need to use custom tab components, you can override this method and
  38945. return your own class instead of the default.
  38946. */
  38947. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  38948. private:
  38949. Orientation orientation;
  38950. StringArray tabs;
  38951. Array <Colour> tabColours;
  38952. int currentTabIndex;
  38953. Component* behindFrontTab;
  38954. ScopedPointer<Button> extraTabsButton;
  38955. TabbedButtonBar (const TabbedButtonBar&);
  38956. TabbedButtonBar& operator= (const TabbedButtonBar&);
  38957. };
  38958. #endif // __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  38959. /*** End of inlined file: juce_TabbedButtonBar.h ***/
  38960. /**
  38961. A component with a TabbedButtonBar along one of its sides.
  38962. This makes it easy to create a set of tabbed pages, just add a bunch of tabs
  38963. with addTab(), and this will take care of showing the pages for you when the
  38964. user clicks on a different tab.
  38965. @see TabbedButtonBar
  38966. */
  38967. class JUCE_API TabbedComponent : public Component
  38968. {
  38969. public:
  38970. /** Creates a TabbedComponent, specifying where the tabs should be placed.
  38971. Once created, add some tabs with the addTab() method.
  38972. */
  38973. explicit TabbedComponent (TabbedButtonBar::Orientation orientation);
  38974. /** Destructor. */
  38975. ~TabbedComponent();
  38976. /** Changes the placement of the tabs.
  38977. This will rearrange the layout to place the tabs along the appropriate
  38978. side of this component, and will shift the content component accordingly.
  38979. @see TabbedButtonBar::setOrientation
  38980. */
  38981. void setOrientation (TabbedButtonBar::Orientation orientation);
  38982. /** Returns the current tab placement.
  38983. @see setOrientation, TabbedButtonBar::getOrientation
  38984. */
  38985. TabbedButtonBar::Orientation getOrientation() const throw();
  38986. /** Specifies how many pixels wide or high the tab-bar should be.
  38987. If the tabs are placed along the top or bottom, this specified the height
  38988. of the bar; if they're along the left or right edges, it'll be the width
  38989. of the bar.
  38990. */
  38991. void setTabBarDepth (int newDepth);
  38992. /** Returns the current thickness of the tab bar.
  38993. @see setTabBarDepth
  38994. */
  38995. int getTabBarDepth() const throw() { return tabDepth; }
  38996. /** Specifies the thickness of an outline that should be drawn around the content component.
  38997. If this thickness is > 0, a line will be drawn around the three sides of the content
  38998. component which don't touch the tab-bar, and the content component will be inset by this amount.
  38999. To set the colour of the line, use setColour (outlineColourId, ...).
  39000. */
  39001. void setOutline (int newThickness);
  39002. /** Specifies a gap to leave around the edge of the content component.
  39003. Each edge of the content component will be indented by the given number of pixels.
  39004. */
  39005. void setIndent (int indentThickness);
  39006. /** Removes all the tabs from the bar.
  39007. @see TabbedButtonBar::clearTabs
  39008. */
  39009. void clearTabs();
  39010. /** Adds a tab to the tab-bar.
  39011. The component passed in will be shown for the tab, and if deleteComponentWhenNotNeeded
  39012. is true, it will be deleted when the tab is removed or when this object is
  39013. deleted.
  39014. @see TabbedButtonBar::addTab
  39015. */
  39016. void addTab (const String& tabName,
  39017. const Colour& tabBackgroundColour,
  39018. Component* contentComponent,
  39019. bool deleteComponentWhenNotNeeded,
  39020. int insertIndex = -1);
  39021. /** Changes the name of one of the tabs. */
  39022. void setTabName (int tabIndex, const String& newName);
  39023. /** Gets rid of one of the tabs. */
  39024. void removeTab (int tabIndex);
  39025. /** Returns the number of tabs in the bar. */
  39026. int getNumTabs() const;
  39027. /** Returns a list of all the tab names in the bar. */
  39028. const StringArray getTabNames() const;
  39029. /** Returns the content component that was added for the given index.
  39030. Be sure not to use or delete the components that are returned, as this may interfere
  39031. with the TabbedComponent's use of them.
  39032. */
  39033. Component* getTabContentComponent (int tabIndex) const throw();
  39034. /** Returns the colour of one of the tabs. */
  39035. const Colour getTabBackgroundColour (int tabIndex) const throw();
  39036. /** Changes the background colour of one of the tabs. */
  39037. void setTabBackgroundColour (int tabIndex, const Colour& newColour);
  39038. /** Changes the currently-selected tab.
  39039. To deselect all the tabs, pass -1 as the index.
  39040. @see TabbedButtonBar::setCurrentTabIndex
  39041. */
  39042. void setCurrentTabIndex (int newTabIndex, bool sendChangeMessage = true);
  39043. /** Returns the index of the currently selected tab.
  39044. @see addTab, TabbedButtonBar::getCurrentTabIndex()
  39045. */
  39046. int getCurrentTabIndex() const;
  39047. /** Returns the name of the currently selected tab.
  39048. @see addTab, TabbedButtonBar::getCurrentTabName()
  39049. */
  39050. const String& getCurrentTabName() const;
  39051. /** Returns the current component that's filling the panel.
  39052. This will return 0 if there isn't one.
  39053. */
  39054. Component* getCurrentContentComponent() const throw() { return panelComponent; }
  39055. /** Callback method to indicate the selected tab has been changed.
  39056. @see setCurrentTabIndex
  39057. */
  39058. virtual void currentTabChanged (int newCurrentTabIndex,
  39059. const String& newCurrentTabName);
  39060. /** Callback method to indicate that the user has right-clicked on a tab.
  39061. (Or ctrl-clicked on the Mac)
  39062. */
  39063. virtual void popupMenuClickOnTab (int tabIndex,
  39064. const String& tabName);
  39065. /** Returns the tab button bar component that is being used.
  39066. */
  39067. TabbedButtonBar& getTabbedButtonBar() const throw() { return *tabs; }
  39068. /** A set of colour IDs to use to change the colour of various aspects of the component.
  39069. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39070. methods.
  39071. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39072. */
  39073. enum ColourIds
  39074. {
  39075. backgroundColourId = 0x1005800, /**< The colour to fill the background behind the tabs. */
  39076. outlineColourId = 0x1005801, /**< The colour to use to draw an outline around the content.
  39077. (See setOutline) */
  39078. };
  39079. /** @internal */
  39080. void paint (Graphics& g);
  39081. /** @internal */
  39082. void resized();
  39083. /** @internal */
  39084. void lookAndFeelChanged();
  39085. juce_UseDebuggingNewOperator
  39086. protected:
  39087. TabbedButtonBar* tabs;
  39088. /** This creates one of the tab buttons.
  39089. If you need to use custom tab components, you can override this method and
  39090. return your own class instead of the default.
  39091. */
  39092. virtual TabBarButton* createTabButton (const String& tabName, int tabIndex);
  39093. private:
  39094. Array <Component*> contentComponents;
  39095. Component* panelComponent;
  39096. int tabDepth;
  39097. int outlineThickness, edgeIndent;
  39098. static const Identifier deleteComponentId;
  39099. friend class TabCompButtonBar;
  39100. void changeCallback (int newCurrentTabIndex, const String& newTabName);
  39101. TabbedComponent (const TabbedComponent&);
  39102. TabbedComponent& operator= (const TabbedComponent&);
  39103. };
  39104. #endif // __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  39105. /*** End of inlined file: juce_TabbedComponent.h ***/
  39106. /*** Start of inlined file: juce_DocumentWindow.h ***/
  39107. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39108. #define __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39109. /*** Start of inlined file: juce_MenuBarComponent.h ***/
  39110. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39111. #define __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39112. /*** Start of inlined file: juce_MenuBarModel.h ***/
  39113. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  39114. #define __JUCE_MENUBARMODEL_JUCEHEADER__
  39115. class MenuBarModel;
  39116. /**
  39117. A class to receive callbacks when a MenuBarModel changes.
  39118. @see MenuBarModel::addListener, MenuBarModel::removeListener, MenuBarModel::menuItemsChanged
  39119. */
  39120. class JUCE_API MenuBarModelListener
  39121. {
  39122. public:
  39123. /** Destructor. */
  39124. virtual ~MenuBarModelListener() {}
  39125. /** This callback is made when items are changed in the menu bar model.
  39126. */
  39127. virtual void menuBarItemsChanged (MenuBarModel* menuBarModel) = 0;
  39128. /** This callback is made when an application command is invoked that
  39129. is represented by one of the items in the menu bar model.
  39130. */
  39131. virtual void menuCommandInvoked (MenuBarModel* menuBarModel,
  39132. const ApplicationCommandTarget::InvocationInfo& info) = 0;
  39133. };
  39134. /**
  39135. A class for controlling MenuBar components.
  39136. This class is used to tell a MenuBar what menus to show, and to respond
  39137. to a menu being selected.
  39138. @see MenuBarModelListener, MenuBarComponent, PopupMenu
  39139. */
  39140. class JUCE_API MenuBarModel : private AsyncUpdater,
  39141. private ApplicationCommandManagerListener
  39142. {
  39143. public:
  39144. MenuBarModel() throw();
  39145. /** Destructor. */
  39146. virtual ~MenuBarModel();
  39147. /** Call this when some of your menu items have changed.
  39148. This method will cause a callback to any MenuBarListener objects that
  39149. are registered with this model.
  39150. If this model is displaying items from an ApplicationCommandManager, you
  39151. can use the setApplicationCommandManagerToWatch() method to cause
  39152. change messages to be sent automatically when the ApplicationCommandManager
  39153. is changed.
  39154. @see addListener, removeListener, MenuBarListener
  39155. */
  39156. void menuItemsChanged();
  39157. /** Tells the menu bar to listen to the specified command manager, and to update
  39158. itself when the commands change.
  39159. This will also allow it to flash a menu name when a command from that menu
  39160. is invoked using a keystroke.
  39161. */
  39162. void setApplicationCommandManagerToWatch (ApplicationCommandManager* manager) throw();
  39163. /** Registers a listener for callbacks when the menu items in this model change.
  39164. The listener object will get callbacks when this object's menuItemsChanged()
  39165. method is called.
  39166. @see removeListener
  39167. */
  39168. void addListener (MenuBarModelListener* listenerToAdd) throw();
  39169. /** Removes a listener.
  39170. @see addListener
  39171. */
  39172. void removeListener (MenuBarModelListener* listenerToRemove) throw();
  39173. /** This method must return a list of the names of the menus. */
  39174. virtual const StringArray getMenuBarNames() = 0;
  39175. /** This should return the popup menu to display for a given top-level menu.
  39176. @param topLevelMenuIndex the index of the top-level menu to show
  39177. @param menuName the name of the top-level menu item to show
  39178. */
  39179. virtual const PopupMenu getMenuForIndex (int topLevelMenuIndex,
  39180. const String& menuName) = 0;
  39181. /** This is called when a menu item has been clicked on.
  39182. @param menuItemID the item ID of the PopupMenu item that was selected
  39183. @param topLevelMenuIndex the index of the top-level menu from which the item was
  39184. chosen (just in case you've used duplicate ID numbers
  39185. on more than one of the popup menus)
  39186. */
  39187. virtual void menuItemSelected (int menuItemID,
  39188. int topLevelMenuIndex) = 0;
  39189. #if JUCE_MAC || DOXYGEN
  39190. /** MAC ONLY - Sets the model that is currently being shown as the main
  39191. menu bar at the top of the screen on the Mac.
  39192. You can pass 0 to stop the current model being displayed. Be careful
  39193. not to delete a model while it is being used.
  39194. An optional extra menu can be specified, containing items to add to the top of
  39195. the apple menu. (Confusingly, the 'apple' menu isn't the one with a picture of
  39196. an apple, it's the one next to it, with your application's name at the top
  39197. and the services menu etc on it). When one of these items is selected, the
  39198. menu bar model will be used to invoke it, and in the menuItemSelected() callback
  39199. the topLevelMenuIndex parameter will be -1. If you pass in an extraAppleMenuItems
  39200. object then newMenuBarModel must be non-null.
  39201. */
  39202. static void setMacMainMenu (MenuBarModel* newMenuBarModel,
  39203. const PopupMenu* extraAppleMenuItems = 0);
  39204. /** MAC ONLY - Returns the menu model that is currently being shown as
  39205. the main menu bar.
  39206. */
  39207. static MenuBarModel* getMacMainMenu();
  39208. #endif
  39209. /** @internal */
  39210. void applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info);
  39211. /** @internal */
  39212. void applicationCommandListChanged();
  39213. /** @internal */
  39214. void handleAsyncUpdate();
  39215. juce_UseDebuggingNewOperator
  39216. private:
  39217. ApplicationCommandManager* manager;
  39218. ListenerList <MenuBarModelListener> listeners;
  39219. MenuBarModel (const MenuBarModel&);
  39220. MenuBarModel& operator= (const MenuBarModel&);
  39221. };
  39222. #endif // __JUCE_MENUBARMODEL_JUCEHEADER__
  39223. /*** End of inlined file: juce_MenuBarModel.h ***/
  39224. /**
  39225. A menu bar component.
  39226. @see MenuBarModel
  39227. */
  39228. class JUCE_API MenuBarComponent : public Component,
  39229. private MenuBarModelListener,
  39230. private Timer
  39231. {
  39232. public:
  39233. /** Creates a menu bar.
  39234. @param model the model object to use to control this bar. You can
  39235. pass 0 into this if you like, and set the model later
  39236. using the setModel() method
  39237. */
  39238. MenuBarComponent (MenuBarModel* model);
  39239. /** Destructor. */
  39240. ~MenuBarComponent();
  39241. /** Changes the model object to use to control the bar.
  39242. This can be 0, in which case the bar will be empty. Don't delete the object
  39243. that is passed-in while it's still being used by this MenuBar.
  39244. */
  39245. void setModel (MenuBarModel* newModel);
  39246. /** Returns the current menu bar model being used.
  39247. */
  39248. MenuBarModel* getModel() const throw();
  39249. /** Pops up one of the menu items.
  39250. This lets you manually open one of the menus - it could be triggered by a
  39251. key shortcut, for example.
  39252. */
  39253. void showMenu (int menuIndex);
  39254. /** @internal */
  39255. void paint (Graphics& g);
  39256. /** @internal */
  39257. void resized();
  39258. /** @internal */
  39259. void mouseEnter (const MouseEvent& e);
  39260. /** @internal */
  39261. void mouseExit (const MouseEvent& e);
  39262. /** @internal */
  39263. void mouseDown (const MouseEvent& e);
  39264. /** @internal */
  39265. void mouseDrag (const MouseEvent& e);
  39266. /** @internal */
  39267. void mouseUp (const MouseEvent& e);
  39268. /** @internal */
  39269. void mouseMove (const MouseEvent& e);
  39270. /** @internal */
  39271. void handleCommandMessage (int commandId);
  39272. /** @internal */
  39273. bool keyPressed (const KeyPress& key);
  39274. /** @internal */
  39275. void menuBarItemsChanged (MenuBarModel* menuBarModel);
  39276. /** @internal */
  39277. void menuCommandInvoked (MenuBarModel* menuBarModel,
  39278. const ApplicationCommandTarget::InvocationInfo& info);
  39279. juce_UseDebuggingNewOperator
  39280. private:
  39281. class AsyncCallback;
  39282. friend class AsyncCallback;
  39283. MenuBarModel* model;
  39284. StringArray menuNames;
  39285. Array <int> xPositions;
  39286. int itemUnderMouse, currentPopupIndex, topLevelIndexClicked;
  39287. int lastMouseX, lastMouseY;
  39288. int getItemAt (int x, int y);
  39289. void setItemUnderMouse (int index);
  39290. void setOpenItem (int index);
  39291. void updateItemUnderMouse (int x, int y);
  39292. void timerCallback();
  39293. void repaintMenuItem (int index);
  39294. void menuDismissed (int topLevelIndex, int itemId);
  39295. MenuBarComponent (const MenuBarComponent&);
  39296. MenuBarComponent& operator= (const MenuBarComponent&);
  39297. };
  39298. #endif // __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  39299. /*** End of inlined file: juce_MenuBarComponent.h ***/
  39300. /**
  39301. A resizable window with a title bar and maximise, minimise and close buttons.
  39302. This subclass of ResizableWindow creates a fairly standard type of window with
  39303. a title bar and various buttons. The name of the component is shown in the
  39304. title bar, and an icon can optionally be specified with setIcon().
  39305. All the methods available to a ResizableWindow are also available to this,
  39306. so it can easily be made resizable, minimised, maximised, etc.
  39307. It's not advisable to add child components directly to a DocumentWindow: put them
  39308. inside your content component instead. And overriding methods like resized(), moved(), etc
  39309. is also not recommended - instead override these methods for your content component.
  39310. (If for some obscure reason you do need to override these methods, always remember to
  39311. call the super-class's resized() method too, otherwise it'll fail to lay out the window
  39312. decorations correctly).
  39313. You can also automatically add a menu bar to the window, using the setMenuBar()
  39314. method.
  39315. @see ResizableWindow, DialogWindow
  39316. */
  39317. class JUCE_API DocumentWindow : public ResizableWindow
  39318. {
  39319. public:
  39320. /** The set of available button-types that can be put on the title bar.
  39321. @see setTitleBarButtonsRequired
  39322. */
  39323. enum TitleBarButtons
  39324. {
  39325. minimiseButton = 1,
  39326. maximiseButton = 2,
  39327. closeButton = 4,
  39328. /** A combination of all the buttons above. */
  39329. allButtons = 7
  39330. };
  39331. /** Creates a DocumentWindow.
  39332. @param name the name to give the component - this is also
  39333. the title shown at the top of the window. To change
  39334. this later, use setName()
  39335. @param backgroundColour the colour to use for filling the window's background.
  39336. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  39337. should be shown on the title bar. This value is a bitwise
  39338. combination of values from the TitleBarButtons enum. Note
  39339. that it can be "allButtons" to get them all. You
  39340. can change this later with the setTitleBarButtonsRequired()
  39341. method, which can also specify where they are positioned.
  39342. @param addToDesktop if true, the window will be automatically added to the
  39343. desktop; if false, you can use it as a child component
  39344. @see TitleBarButtons
  39345. */
  39346. DocumentWindow (const String& name,
  39347. const Colour& backgroundColour,
  39348. int requiredButtons,
  39349. bool addToDesktop = true);
  39350. /** Destructor.
  39351. If a content component has been set with setContentComponent(), it
  39352. will be deleted.
  39353. */
  39354. ~DocumentWindow();
  39355. /** Changes the component's name.
  39356. (This is overridden from Component::setName() to cause a repaint, as
  39357. the name is what gets drawn across the window's title bar).
  39358. */
  39359. void setName (const String& newName);
  39360. /** Sets an icon to show in the title bar, next to the title.
  39361. A copy is made internally of the image, so the caller can delete the
  39362. image after calling this. If 0 is passed-in, any existing icon will be
  39363. removed.
  39364. */
  39365. void setIcon (const Image& imageToUse);
  39366. /** Changes the height of the title-bar. */
  39367. void setTitleBarHeight (int newHeight);
  39368. /** Returns the current title bar height. */
  39369. int getTitleBarHeight() const;
  39370. /** Changes the set of title-bar buttons being shown.
  39371. @param requiredButtons specifies which of the buttons (close, minimise, maximise)
  39372. should be shown on the title bar. This value is a bitwise
  39373. combination of values from the TitleBarButtons enum. Note
  39374. that it can be "allButtons" to get them all.
  39375. @param positionTitleBarButtonsOnLeft if true, the buttons should go at the
  39376. left side of the bar; if false, they'll be placed at the right
  39377. */
  39378. void setTitleBarButtonsRequired (int requiredButtons,
  39379. bool positionTitleBarButtonsOnLeft);
  39380. /** Sets whether the title should be centred within the window.
  39381. If true, the title text is shown in the middle of the title-bar; if false,
  39382. it'll be shown at the left of the bar.
  39383. */
  39384. void setTitleBarTextCentred (bool textShouldBeCentred);
  39385. /** Creates a menu inside this window.
  39386. @param menuBarModel this specifies a MenuBarModel that should be used to
  39387. generate the contents of a menu bar that will be placed
  39388. just below the title bar, and just above any content
  39389. component. If this value is zero, any existing menu bar
  39390. will be removed from the component; if non-zero, one will
  39391. be added if it's required.
  39392. @param menuBarHeight the height of the menu bar component, if one is needed. Pass a value of zero
  39393. or less to use the look-and-feel's default size.
  39394. */
  39395. void setMenuBar (MenuBarModel* menuBarModel,
  39396. int menuBarHeight = 0);
  39397. /** This method is called when the user tries to close the window.
  39398. This is triggered by the user clicking the close button, or using some other
  39399. OS-specific key shortcut or OS menu for getting rid of a window.
  39400. If the window is just a pop-up, you should override this closeButtonPressed()
  39401. method and make it delete the window in whatever way is appropriate for your
  39402. app. E.g. you might just want to call "delete this".
  39403. If your app is centred around this window such that the whole app should quit when
  39404. the window is closed, then you will probably want to use this method as an opportunity
  39405. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  39406. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  39407. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  39408. or closing it via the taskbar icon on Windows).
  39409. (Note that the DocumentWindow class overrides Component::userTriedToCloseWindow() and
  39410. redirects it to call this method, so any methods of closing the window that are
  39411. caught by userTriedToCloseWindow() will also end up here).
  39412. */
  39413. virtual void closeButtonPressed();
  39414. /** Callback that is triggered when the minimise button is pressed.
  39415. The default implementation of this calls ResizableWindow::setMinimised(), but
  39416. you can override it to do more customised behaviour.
  39417. */
  39418. virtual void minimiseButtonPressed();
  39419. /** Callback that is triggered when the maximise button is pressed, or when the
  39420. title-bar is double-clicked.
  39421. The default implementation of this calls ResizableWindow::setFullScreen(), but
  39422. you can override it to do more customised behaviour.
  39423. */
  39424. virtual void maximiseButtonPressed();
  39425. /** Returns the close button, (or 0 if there isn't one). */
  39426. Button* getCloseButton() const throw();
  39427. /** Returns the minimise button, (or 0 if there isn't one). */
  39428. Button* getMinimiseButton() const throw();
  39429. /** Returns the maximise button, (or 0 if there isn't one). */
  39430. Button* getMaximiseButton() const throw();
  39431. /** A set of colour IDs to use to change the colour of various aspects of the window.
  39432. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  39433. methods.
  39434. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  39435. */
  39436. enum ColourIds
  39437. {
  39438. textColourId = 0x1005701, /**< The colour to draw any text with. It's up to the look
  39439. and feel class how this is used. */
  39440. };
  39441. /** @internal */
  39442. void paint (Graphics& g);
  39443. /** @internal */
  39444. void resized();
  39445. /** @internal */
  39446. void lookAndFeelChanged();
  39447. /** @internal */
  39448. const BorderSize getBorderThickness();
  39449. /** @internal */
  39450. const BorderSize getContentComponentBorder();
  39451. /** @internal */
  39452. void mouseDoubleClick (const MouseEvent& e);
  39453. /** @internal */
  39454. void userTriedToCloseWindow();
  39455. /** @internal */
  39456. void activeWindowStatusChanged();
  39457. /** @internal */
  39458. int getDesktopWindowStyleFlags() const;
  39459. /** @internal */
  39460. void parentHierarchyChanged();
  39461. /** @internal */
  39462. const Rectangle<int> getTitleBarArea();
  39463. juce_UseDebuggingNewOperator
  39464. private:
  39465. int titleBarHeight, menuBarHeight, requiredButtons;
  39466. bool positionTitleBarButtonsOnLeft, drawTitleTextCentred;
  39467. ScopedPointer <Button> titleBarButtons [3];
  39468. Image titleBarIcon;
  39469. ScopedPointer <MenuBarComponent> menuBar;
  39470. MenuBarModel* menuBarModel;
  39471. class ButtonListenerProxy;
  39472. friend class ScopedPointer <ButtonListenerProxy>;
  39473. ScopedPointer <ButtonListenerProxy> buttonListener;
  39474. void repaintTitleBar();
  39475. DocumentWindow (const DocumentWindow&);
  39476. DocumentWindow& operator= (const DocumentWindow&);
  39477. };
  39478. #endif // __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  39479. /*** End of inlined file: juce_DocumentWindow.h ***/
  39480. class MultiDocumentPanel;
  39481. class MDITabbedComponentInternal;
  39482. /**
  39483. This is a derivative of DocumentWindow that is used inside a MultiDocumentPanel
  39484. component.
  39485. It's like a normal DocumentWindow but has some extra functionality to make sure
  39486. everything works nicely inside a MultiDocumentPanel.
  39487. @see MultiDocumentPanel
  39488. */
  39489. class JUCE_API MultiDocumentPanelWindow : public DocumentWindow
  39490. {
  39491. public:
  39492. /**
  39493. */
  39494. MultiDocumentPanelWindow (const Colour& backgroundColour);
  39495. /** Destructor. */
  39496. ~MultiDocumentPanelWindow();
  39497. /** @internal */
  39498. void maximiseButtonPressed();
  39499. /** @internal */
  39500. void closeButtonPressed();
  39501. /** @internal */
  39502. void activeWindowStatusChanged();
  39503. /** @internal */
  39504. void broughtToFront();
  39505. juce_UseDebuggingNewOperator
  39506. private:
  39507. void updateOrder();
  39508. MultiDocumentPanel* getOwner() const throw();
  39509. };
  39510. /**
  39511. A component that contains a set of other components either in floating windows
  39512. or tabs.
  39513. This acts as a panel that can be used to hold a set of open document windows, with
  39514. different layout modes.
  39515. Use addDocument() and closeDocument() to add or remove components from the
  39516. panel - never use any of the Component methods to access the panel's child
  39517. components directly, as these are managed internally.
  39518. */
  39519. class JUCE_API MultiDocumentPanel : public Component,
  39520. private ComponentListener
  39521. {
  39522. public:
  39523. /** Creates an empty panel.
  39524. Use addDocument() and closeDocument() to add or remove components from the
  39525. panel - never use any of the Component methods to access the panel's child
  39526. components directly, as these are managed internally.
  39527. */
  39528. MultiDocumentPanel();
  39529. /** Destructor.
  39530. When deleted, this will call closeAllDocuments (false) to make sure all its
  39531. components are deleted. If you need to make sure all documents are saved
  39532. before closing, then you should call closeAllDocuments (true) and check that
  39533. it returns true before deleting the panel.
  39534. */
  39535. ~MultiDocumentPanel();
  39536. /** Tries to close all the documents.
  39537. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39538. be called for each open document, and any of these calls fails, this method
  39539. will stop and return false, leaving some documents still open.
  39540. If checkItsOkToCloseFirst is false, then all documents will be closed
  39541. unconditionally.
  39542. @see closeDocument
  39543. */
  39544. bool closeAllDocuments (bool checkItsOkToCloseFirst);
  39545. /** Adds a document component to the panel.
  39546. If the number of documents would exceed the limit set by setMaximumNumDocuments() then
  39547. this will fail and return false. (If it does fail, the component passed-in will not be
  39548. deleted, even if deleteWhenRemoved was set to true).
  39549. The MultiDocumentPanel will deal with creating a window border to go around your component,
  39550. so just pass in the bare content component here, no need to give it a ResizableWindow
  39551. or DocumentWindow.
  39552. @param component the component to add
  39553. @param backgroundColour the background colour to use to fill the component's
  39554. window or tab
  39555. @param deleteWhenRemoved if true, then when the component is removed by closeDocument()
  39556. or closeAllDocuments(), then it will be deleted. If false, then
  39557. the caller must handle the component's deletion
  39558. */
  39559. bool addDocument (Component* component,
  39560. const Colour& backgroundColour,
  39561. bool deleteWhenRemoved);
  39562. /** Closes one of the documents.
  39563. If checkItsOkToCloseFirst is true, then the tryToCloseDocument() method will
  39564. be called, and if it fails, this method will return false without closing the
  39565. document.
  39566. If checkItsOkToCloseFirst is false, then the documents will be closed
  39567. unconditionally.
  39568. The component will be deleted if the deleteWhenRemoved parameter was set to
  39569. true when it was added with addDocument.
  39570. @see addDocument, closeAllDocuments
  39571. */
  39572. bool closeDocument (Component* component,
  39573. bool checkItsOkToCloseFirst);
  39574. /** Returns the number of open document windows.
  39575. @see getDocument
  39576. */
  39577. int getNumDocuments() const throw();
  39578. /** Returns one of the open documents.
  39579. The order of the documents in this array may change when they are added, removed
  39580. or moved around.
  39581. @see getNumDocuments
  39582. */
  39583. Component* getDocument (int index) const throw();
  39584. /** Returns the document component that is currently focused or on top.
  39585. If currently using floating windows, then this will be the component in the currently
  39586. active window, or the top component if none are active.
  39587. If it's currently in tabbed mode, then it'll return the component in the active tab.
  39588. @see setActiveDocument
  39589. */
  39590. Component* getActiveDocument() const throw();
  39591. /** Makes one of the components active and brings it to the top.
  39592. @see getActiveDocument
  39593. */
  39594. void setActiveDocument (Component* component);
  39595. /** Callback which gets invoked when the currently-active document changes. */
  39596. virtual void activeDocumentChanged();
  39597. /** Sets a limit on how many windows can be open at once.
  39598. If this is zero or less there's no limit (the default). addDocument() will fail
  39599. if this number is exceeded.
  39600. */
  39601. void setMaximumNumDocuments (int maximumNumDocuments);
  39602. /** Sets an option to make the document fullscreen if there's only one document open.
  39603. If set to true, then if there's only one document, it'll fill the whole of this
  39604. component without tabs or a window border. If false, then tabs or a window
  39605. will always be shown, even if there's only one document. If there's more than
  39606. one document open, then this option makes no difference.
  39607. */
  39608. void useFullscreenWhenOneDocument (bool shouldUseTabs);
  39609. /** Returns the result of the last time useFullscreenWhenOneDocument() was called.
  39610. */
  39611. bool isFullscreenWhenOneDocument() const throw();
  39612. /** The different layout modes available. */
  39613. enum LayoutMode
  39614. {
  39615. FloatingWindows, /**< In this mode, there are overlapping DocumentWindow components for each document. */
  39616. MaximisedWindowsWithTabs /**< In this mode, a TabbedComponent is used to show one document at a time. */
  39617. };
  39618. /** Changes the panel's mode.
  39619. @see LayoutMode, getLayoutMode
  39620. */
  39621. void setLayoutMode (LayoutMode newLayoutMode);
  39622. /** Returns the current layout mode. */
  39623. LayoutMode getLayoutMode() const throw() { return mode; }
  39624. /** Sets the background colour for the whole panel.
  39625. Each document has its own background colour, but this is the one used to fill the areas
  39626. behind them.
  39627. */
  39628. void setBackgroundColour (const Colour& newBackgroundColour);
  39629. /** Returns the current background colour.
  39630. @see setBackgroundColour
  39631. */
  39632. const Colour& getBackgroundColour() const throw() { return backgroundColour; }
  39633. /** A subclass must override this to say whether its currently ok for a document
  39634. to be closed.
  39635. This method is called by closeDocument() and closeAllDocuments() to indicate that
  39636. a document should be saved if possible, ready for it to be closed.
  39637. If this method returns true, then it means the document is ok and can be closed.
  39638. If it returns false, then it means that the closeDocument() method should stop
  39639. and not close.
  39640. Normally, you'd use this method to ask the user if they want to save any changes,
  39641. then return true if the save operation went ok. If the user cancelled the save
  39642. operation you could return false here to abort the close operation.
  39643. If your component is based on the FileBasedDocument class, then you'd probably want
  39644. to call FileBasedDocument::saveIfNeededAndUserAgrees() and return true if this returned
  39645. FileBasedDocument::savedOk
  39646. @see closeDocument, FileBasedDocument::saveIfNeededAndUserAgrees()
  39647. */
  39648. virtual bool tryToCloseDocument (Component* component) = 0;
  39649. /** Creates a new window to be used for a document.
  39650. The default implementation of this just returns a basic MultiDocumentPanelWindow object,
  39651. but you might want to override it to return a custom component.
  39652. */
  39653. virtual MultiDocumentPanelWindow* createNewDocumentWindow();
  39654. /** @internal */
  39655. void paint (Graphics& g);
  39656. /** @internal */
  39657. void resized();
  39658. /** @internal */
  39659. void componentNameChanged (Component&);
  39660. juce_UseDebuggingNewOperator
  39661. private:
  39662. LayoutMode mode;
  39663. Array <Component*> components;
  39664. TabbedComponent* tabComponent;
  39665. Colour backgroundColour;
  39666. int maximumNumDocuments, numDocsBeforeTabsUsed;
  39667. friend class MultiDocumentPanelWindow;
  39668. friend class MDITabbedComponentInternal;
  39669. Component* getContainerComp (Component* c) const;
  39670. void updateOrder();
  39671. void addWindow (Component* component);
  39672. };
  39673. #endif // __JUCE_MULTIDOCUMENTPANEL_JUCEHEADER__
  39674. /*** End of inlined file: juce_MultiDocumentPanel.h ***/
  39675. #endif
  39676. #ifndef __JUCE_RESIZABLEBORDERCOMPONENT_JUCEHEADER__
  39677. #endif
  39678. #ifndef __JUCE_RESIZABLECORNERCOMPONENT_JUCEHEADER__
  39679. #endif
  39680. #ifndef __JUCE_SCROLLBAR_JUCEHEADER__
  39681. #endif
  39682. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39683. /*** Start of inlined file: juce_StretchableLayoutManager.h ***/
  39684. #ifndef __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39685. #define __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39686. /**
  39687. For laying out a set of components, where the components have preferred sizes
  39688. and size limits, but where they are allowed to stretch to fill the available
  39689. space.
  39690. For example, if you have a component containing several other components, and
  39691. each one should be given a share of the total size, you could use one of these
  39692. to resize the child components when the parent component is resized. Then
  39693. you could add a StretchableLayoutResizerBar to easily let the user rescale them.
  39694. A StretchableLayoutManager operates only in one dimension, so if you have a set
  39695. of components stacked vertically on top of each other, you'd use one to manage their
  39696. heights. To build up complex arrangements of components, e.g. for applications
  39697. with multiple nested panels, you would use more than one StretchableLayoutManager.
  39698. E.g. by using two (one vertical, one horizontal), you could create a resizable
  39699. spreadsheet-style table.
  39700. E.g.
  39701. @code
  39702. class MyComp : public Component
  39703. {
  39704. StretchableLayoutManager myLayout;
  39705. MyComp()
  39706. {
  39707. myLayout.setItemLayout (0, // for item 0
  39708. 50, 100, // must be between 50 and 100 pixels in size
  39709. -0.6); // and its preferred size is 60% of the total available space
  39710. myLayout.setItemLayout (1, // for item 1
  39711. -0.2, -0.6, // size must be between 20% and 60% of the available space
  39712. 50); // and its preferred size is 50 pixels
  39713. }
  39714. void resized()
  39715. {
  39716. // make a list of two of our child components that we want to reposition
  39717. Component* comps[] = { myComp1, myComp2 };
  39718. // this will position the 2 components, one above the other, to fit
  39719. // vertically into the rectangle provided.
  39720. myLayout.layOutComponents (comps, 2,
  39721. 0, 0, getWidth(), getHeight(),
  39722. true);
  39723. }
  39724. };
  39725. @endcode
  39726. @see StretchableLayoutResizerBar
  39727. */
  39728. class JUCE_API StretchableLayoutManager
  39729. {
  39730. public:
  39731. /** Creates an empty layout.
  39732. You'll need to add some item properties to the layout before it can be used
  39733. to resize things - see setItemLayout().
  39734. */
  39735. StretchableLayoutManager();
  39736. /** Destructor. */
  39737. ~StretchableLayoutManager();
  39738. /** For a numbered item, this sets its size limits and preferred size.
  39739. @param itemIndex the index of the item to change.
  39740. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39741. indicates an absolute size in pixels. A negative number indicates a
  39742. proportion of the available space (e.g -0.5 is 50%)
  39743. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39744. indicates an absolute size in pixels. A negative number indicates a
  39745. proportion of the available space
  39746. @param preferredSize the size that this item would like to be, if there's enough room. A
  39747. positive number indicates an absolute size in pixels. A negative number
  39748. indicates a proportion of the available space
  39749. @see getItemLayout
  39750. */
  39751. void setItemLayout (int itemIndex,
  39752. double minimumSize,
  39753. double maximumSize,
  39754. double preferredSize);
  39755. /** For a numbered item, this returns its size limits and preferred size.
  39756. @param itemIndex the index of the item.
  39757. @param minimumSize the minimum size that this item is allowed to be - a positive number
  39758. indicates an absolute size in pixels. A negative number indicates a
  39759. proportion of the available space (e.g -0.5 is 50%)
  39760. @param maximumSize the maximum size that this item is allowed to be - a positive number
  39761. indicates an absolute size in pixels. A negative number indicates a
  39762. proportion of the available space
  39763. @param preferredSize the size that this item would like to be, if there's enough room. A
  39764. positive number indicates an absolute size in pixels. A negative number
  39765. indicates a proportion of the available space
  39766. @returns false if the item's properties hadn't been set
  39767. @see setItemLayout
  39768. */
  39769. bool getItemLayout (int itemIndex,
  39770. double& minimumSize,
  39771. double& maximumSize,
  39772. double& preferredSize) const;
  39773. /** Clears all the properties that have been set with setItemLayout() and resets
  39774. this object to its initial state.
  39775. */
  39776. void clearAllItems();
  39777. /** Takes a set of components that correspond to the layout's items, and positions
  39778. them to fill a space.
  39779. This will try to give each item its preferred size, whether that's a relative size
  39780. or an absolute one.
  39781. @param components an array of components that correspond to each of the
  39782. numbered items that the StretchableLayoutManager object
  39783. has been told about with setItemLayout()
  39784. @param numComponents the number of components in the array that is passed-in. This
  39785. should be the same as the number of items this object has been
  39786. told about.
  39787. @param x the left of the rectangle in which the components should
  39788. be laid out
  39789. @param y the top of the rectangle in which the components should
  39790. be laid out
  39791. @param width the width of the rectangle in which the components should
  39792. be laid out
  39793. @param height the height of the rectangle in which the components should
  39794. be laid out
  39795. @param vertically if true, the components will be positioned in a vertical stack,
  39796. so that they fill the height of the rectangle. If false, they
  39797. will be placed side-by-side in a horizontal line, filling the
  39798. available width
  39799. @param resizeOtherDimension if true, this means that the components will have their
  39800. other dimension resized to fit the space - i.e. if the 'vertically'
  39801. parameter is true, their x-positions and widths are adjusted to fit
  39802. the x and width parameters; if 'vertically' is false, their y-positions
  39803. and heights are adjusted to fit the y and height parameters.
  39804. */
  39805. void layOutComponents (Component** components,
  39806. int numComponents,
  39807. int x, int y, int width, int height,
  39808. bool vertically,
  39809. bool resizeOtherDimension);
  39810. /** Returns the current position of one of the items.
  39811. This is only a valid call after layOutComponents() has been called, as it
  39812. returns the last position that this item was placed at. If the layout was
  39813. vertical, the value returned will be the y position of the top of the item,
  39814. relative to the top of the rectangle in which the items were placed (so for
  39815. example, item 0 will always have position of 0, even in the rectangle passed
  39816. in to layOutComponents() wasn't at y = 0). If the layout was done horizontally,
  39817. the position returned is the item's left-hand position, again relative to the
  39818. x position of the rectangle used.
  39819. @see getItemCurrentSize, setItemPosition
  39820. */
  39821. int getItemCurrentPosition (int itemIndex) const;
  39822. /** Returns the current size of one of the items.
  39823. This is only meaningful after layOutComponents() has been called, as it
  39824. returns the last size that this item was given. If the layout was done
  39825. vertically, it'll return the item's height in pixels; if it was horizontal,
  39826. it'll return its width.
  39827. @see getItemCurrentRelativeSize
  39828. */
  39829. int getItemCurrentAbsoluteSize (int itemIndex) const;
  39830. /** Returns the current size of one of the items.
  39831. This is only meaningful after layOutComponents() has been called, as it
  39832. returns the last size that this item was given. If the layout was done
  39833. vertically, it'll return a negative value representing the item's height relative
  39834. to the last size used for laying the components out; if the layout was done
  39835. horizontally it'll be the proportion of its width.
  39836. @see getItemCurrentAbsoluteSize
  39837. */
  39838. double getItemCurrentRelativeSize (int itemIndex) const;
  39839. /** Moves one of the items, shifting along any other items as necessary in
  39840. order to get it to the desired position.
  39841. Calling this method will also update the preferred sizes of the items it
  39842. shuffles along, so that they reflect their new positions.
  39843. (This is the method that a StretchableLayoutResizerBar uses to shift the items
  39844. about when it's dragged).
  39845. @param itemIndex the item to move
  39846. @param newPosition the absolute position that you'd like this item to move
  39847. to. The item might not be able to always reach exactly this position,
  39848. because other items may have minimum sizes that constrain how
  39849. far it can go
  39850. */
  39851. void setItemPosition (int itemIndex,
  39852. int newPosition);
  39853. juce_UseDebuggingNewOperator
  39854. private:
  39855. struct ItemLayoutProperties
  39856. {
  39857. int itemIndex;
  39858. int currentSize;
  39859. double minSize, maxSize, preferredSize;
  39860. };
  39861. OwnedArray <ItemLayoutProperties> items;
  39862. int totalSize;
  39863. static int sizeToRealSize (double size, int totalSpace);
  39864. ItemLayoutProperties* getInfoFor (int itemIndex) const;
  39865. void setTotalSize (int newTotalSize);
  39866. int fitComponentsIntoSpace (int startIndex, int endIndex, int availableSpace, int startPos);
  39867. int getMinimumSizeOfItems (int startIndex, int endIndex) const;
  39868. int getMaximumSizeOfItems (int startIndex, int endIndex) const;
  39869. void updatePrefSizesToMatchCurrentPositions();
  39870. StretchableLayoutManager (const StretchableLayoutManager&);
  39871. StretchableLayoutManager& operator= (const StretchableLayoutManager&);
  39872. };
  39873. #endif // __JUCE_STRETCHABLELAYOUTMANAGER_JUCEHEADER__
  39874. /*** End of inlined file: juce_StretchableLayoutManager.h ***/
  39875. #endif
  39876. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39877. /*** Start of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39878. #ifndef __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39879. #define __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39880. /**
  39881. A component that acts as one of the vertical or horizontal bars you see being
  39882. used to resize panels in a window.
  39883. One of these acts with a StretchableLayoutManager to resize the other components.
  39884. @see StretchableLayoutManager
  39885. */
  39886. class JUCE_API StretchableLayoutResizerBar : public Component
  39887. {
  39888. public:
  39889. /** Creates a resizer bar for use on a specified layout.
  39890. @param layoutToUse the layout that will be affected when this bar
  39891. is dragged
  39892. @param itemIndexInLayout the item index in the layout that corresponds to
  39893. this bar component. You'll need to set up the item
  39894. properties in a suitable way for a divider bar, e.g.
  39895. for an 8-pixel wide bar which, you could call
  39896. myLayout->setItemLayout (barIndex, 8, 8, 8)
  39897. @param isBarVertical true if it's an upright bar that you drag left and
  39898. right; false for a horizontal one that you drag up and
  39899. down
  39900. */
  39901. StretchableLayoutResizerBar (StretchableLayoutManager* layoutToUse,
  39902. int itemIndexInLayout,
  39903. bool isBarVertical);
  39904. /** Destructor. */
  39905. ~StretchableLayoutResizerBar();
  39906. /** This is called when the bar is dragged.
  39907. This method must update the positions of any components whose position is
  39908. determined by the StretchableLayoutManager, because they might have just
  39909. moved.
  39910. The default implementation calls the resized() method of this component's
  39911. parent component, because that's often where you're likely to apply the
  39912. layout, but it can be overridden for more specific needs.
  39913. */
  39914. virtual void hasBeenMoved();
  39915. /** @internal */
  39916. void paint (Graphics& g);
  39917. /** @internal */
  39918. void mouseDown (const MouseEvent& e);
  39919. /** @internal */
  39920. void mouseDrag (const MouseEvent& e);
  39921. juce_UseDebuggingNewOperator
  39922. private:
  39923. StretchableLayoutManager* layout;
  39924. int itemIndex, mouseDownPos;
  39925. bool isVertical;
  39926. StretchableLayoutResizerBar (const StretchableLayoutResizerBar&);
  39927. StretchableLayoutResizerBar& operator= (const StretchableLayoutResizerBar&);
  39928. };
  39929. #endif // __JUCE_STRETCHABLELAYOUTRESIZERBAR_JUCEHEADER__
  39930. /*** End of inlined file: juce_StretchableLayoutResizerBar.h ***/
  39931. #endif
  39932. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39933. /*** Start of inlined file: juce_StretchableObjectResizer.h ***/
  39934. #ifndef __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39935. #define __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39936. /**
  39937. A utility class for fitting a set of objects whose sizes can vary between
  39938. a minimum and maximum size, into a space.
  39939. This is a trickier algorithm than it would first seem, so I've put it in this
  39940. class to allow it to be shared by various bits of code.
  39941. To use it, create one of these objects, call addItem() to add the list of items
  39942. you need, then call resizeToFit(), which will change all their sizes. You can
  39943. then retrieve the new sizes with getItemSize() and getNumItems().
  39944. It's currently used by the TableHeaderComponent for stretching out the table
  39945. headings to fill the table's width.
  39946. */
  39947. class StretchableObjectResizer
  39948. {
  39949. public:
  39950. /** Creates an empty object resizer. */
  39951. StretchableObjectResizer();
  39952. /** Destructor. */
  39953. ~StretchableObjectResizer();
  39954. /** Adds an item to the list.
  39955. The order parameter lets you specify groups of items that are resized first when some
  39956. space needs to be found. Those items with an order of 0 will be the first ones to be
  39957. resized, and if that doesn't provide enough space to meet the requirements, the algorithm
  39958. will then try resizing the items with an order of 1, then 2, and so on.
  39959. */
  39960. void addItem (double currentSize,
  39961. double minSize,
  39962. double maxSize,
  39963. int order = 0);
  39964. /** Resizes all the items to fit this amount of space.
  39965. This will attempt to fit them in without exceeding each item's miniumum and
  39966. maximum sizes. In cases where none of the items can be expanded or enlarged any
  39967. further, the final size may be greater or less than the size passed in.
  39968. After calling this method, you can retrieve the new sizes with the getItemSize()
  39969. method.
  39970. */
  39971. void resizeToFit (double targetSize);
  39972. /** Returns the number of items that have been added. */
  39973. int getNumItems() const throw() { return items.size(); }
  39974. /** Returns the size of one of the items. */
  39975. double getItemSize (int index) const throw();
  39976. juce_UseDebuggingNewOperator
  39977. private:
  39978. struct Item
  39979. {
  39980. double size;
  39981. double minSize;
  39982. double maxSize;
  39983. int order;
  39984. };
  39985. OwnedArray <Item> items;
  39986. StretchableObjectResizer (const StretchableObjectResizer&);
  39987. StretchableObjectResizer& operator= (const StretchableObjectResizer&);
  39988. };
  39989. #endif // __JUCE_STRETCHABLEOBJECTRESIZER_JUCEHEADER__
  39990. /*** End of inlined file: juce_StretchableObjectResizer.h ***/
  39991. #endif
  39992. #ifndef __JUCE_TABBEDBUTTONBAR_JUCEHEADER__
  39993. #endif
  39994. #ifndef __JUCE_TABBEDCOMPONENT_JUCEHEADER__
  39995. #endif
  39996. #ifndef __JUCE_VIEWPORT_JUCEHEADER__
  39997. #endif
  39998. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  39999. /*** Start of inlined file: juce_LookAndFeel.h ***/
  40000. #ifndef __JUCE_LOOKANDFEEL_JUCEHEADER__
  40001. #define __JUCE_LOOKANDFEEL_JUCEHEADER__
  40002. /*** Start of inlined file: juce_AlertWindow.h ***/
  40003. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  40004. #define __JUCE_ALERTWINDOW_JUCEHEADER__
  40005. /*** Start of inlined file: juce_TextLayout.h ***/
  40006. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  40007. #define __JUCE_TEXTLAYOUT_JUCEHEADER__
  40008. class Graphics;
  40009. /**
  40010. A laid-out arrangement of text.
  40011. You can add text in different fonts to a TextLayout object, then call its
  40012. layout() method to word-wrap it into lines. The layout can then be drawn
  40013. using a graphics context.
  40014. It's handy if you've got a message to display, because you can format it,
  40015. measure the extent of the layout, and then create a suitably-sized window
  40016. to show it in.
  40017. @see Font, Graphics::drawFittedText, GlyphArrangement
  40018. */
  40019. class JUCE_API TextLayout
  40020. {
  40021. public:
  40022. /** Creates an empty text layout.
  40023. Text can then be appended using the appendText() method.
  40024. */
  40025. TextLayout();
  40026. /** Creates a copy of another layout object. */
  40027. TextLayout (const TextLayout& other);
  40028. /** Creates a text layout from an initial string and font. */
  40029. TextLayout (const String& text, const Font& font);
  40030. /** Destructor. */
  40031. ~TextLayout();
  40032. /** Copies another layout onto this one. */
  40033. TextLayout& operator= (const TextLayout& layoutToCopy);
  40034. /** Clears the layout, removing all its text. */
  40035. void clear();
  40036. /** Adds a string to the end of the arrangement.
  40037. The string will be broken onto new lines wherever it contains
  40038. carriage-returns or linefeeds. After adding it, you can call layout()
  40039. to wrap long lines into a paragraph and justify it.
  40040. */
  40041. void appendText (const String& textToAppend,
  40042. const Font& fontToUse);
  40043. /** Replaces all the text with a new string.
  40044. This is equivalent to calling clear() followed by appendText().
  40045. */
  40046. void setText (const String& newText,
  40047. const Font& fontToUse);
  40048. /** Breaks the text up to form a paragraph with the given width.
  40049. @param maximumWidth any text wider than this will be split
  40050. across multiple lines
  40051. @param justification how the lines are to be laid-out horizontally
  40052. @param attemptToBalanceLineLengths if true, it will try to split the lines at a
  40053. width that keeps all the lines of text at a
  40054. similar length - this is good when you're displaying
  40055. a short message and don't want it to get split
  40056. onto two lines with only a couple of words on
  40057. the second line, which looks untidy.
  40058. */
  40059. void layout (int maximumWidth,
  40060. const Justification& justification,
  40061. bool attemptToBalanceLineLengths);
  40062. /** Returns the overall width of the entire text layout. */
  40063. int getWidth() const;
  40064. /** Returns the overall height of the entire text layout. */
  40065. int getHeight() const;
  40066. /** Returns the total number of lines of text. */
  40067. int getNumLines() const { return totalLines; }
  40068. /** Returns the width of a particular line of text.
  40069. @param lineNumber the line, from 0 to (getNumLines() - 1)
  40070. */
  40071. int getLineWidth (int lineNumber) const;
  40072. /** Renders the text at a specified position using a graphics context.
  40073. */
  40074. void draw (Graphics& g, int topLeftX, int topLeftY) const;
  40075. /** Renders the text within a specified rectangle using a graphics context.
  40076. The justification flags dictate how the block of text should be positioned
  40077. within the rectangle.
  40078. */
  40079. void drawWithin (Graphics& g,
  40080. int x, int y, int w, int h,
  40081. const Justification& layoutFlags) const;
  40082. juce_UseDebuggingNewOperator
  40083. private:
  40084. class Token;
  40085. friend class OwnedArray <Token>;
  40086. OwnedArray <Token> tokens;
  40087. int totalLines;
  40088. };
  40089. #endif // __JUCE_TEXTLAYOUT_JUCEHEADER__
  40090. /*** End of inlined file: juce_TextLayout.h ***/
  40091. /** A window that displays a message and has buttons for the user to react to it.
  40092. For simple dialog boxes with just a couple of buttons on them, there are
  40093. some static methods for running these.
  40094. For more complex dialogs, an AlertWindow can be created, then it can have some
  40095. buttons and components added to it, and its runModalLoop() method is then used to
  40096. show it. The value returned by runModalLoop() shows which button the
  40097. user pressed to dismiss the box.
  40098. @see ThreadWithProgressWindow
  40099. */
  40100. class JUCE_API AlertWindow : public TopLevelWindow,
  40101. private ButtonListener
  40102. {
  40103. public:
  40104. /** The type of icon to show in the dialog box. */
  40105. enum AlertIconType
  40106. {
  40107. NoIcon, /**< No icon will be shown on the dialog box. */
  40108. QuestionIcon, /**< A question-mark icon, for dialog boxes that need the
  40109. user to answer a question. */
  40110. WarningIcon, /**< An exclamation mark to indicate that the dialog is a
  40111. warning about something and shouldn't be ignored. */
  40112. InfoIcon /**< An icon that indicates that the dialog box is just
  40113. giving the user some information, which doesn't require
  40114. a response from them. */
  40115. };
  40116. /** Creates an AlertWindow.
  40117. @param title the headline to show at the top of the dialog box
  40118. @param message a longer, more descriptive message to show underneath the
  40119. headline
  40120. @param iconType the type of icon to display
  40121. @param associatedComponent if this is non-zero, it specifies the component that the
  40122. alert window should be associated with. Depending on the look
  40123. and feel, this might be used for positioning of the alert window.
  40124. */
  40125. AlertWindow (const String& title,
  40126. const String& message,
  40127. AlertIconType iconType,
  40128. Component* associatedComponent = 0);
  40129. /** Destroys the AlertWindow */
  40130. ~AlertWindow();
  40131. /** Returns the type of alert icon that was specified when the window
  40132. was created. */
  40133. AlertIconType getAlertType() const throw() { return alertIconType; }
  40134. /** Changes the dialog box's message.
  40135. This will also resize the window to fit the new message if required.
  40136. */
  40137. void setMessage (const String& message);
  40138. /** Adds a button to the window.
  40139. @param name the text to show on the button
  40140. @param returnValue the value that should be returned from runModalLoop()
  40141. if this is the button that the user presses.
  40142. @param shortcutKey1 an optional key that can be pressed to trigger this button
  40143. @param shortcutKey2 a second optional key that can be pressed to trigger this button
  40144. */
  40145. void addButton (const String& name,
  40146. int returnValue,
  40147. const KeyPress& shortcutKey1 = KeyPress(),
  40148. const KeyPress& shortcutKey2 = KeyPress());
  40149. /** Returns the number of buttons that the window currently has. */
  40150. int getNumButtons() const;
  40151. /** Invokes a click of one of the buttons. */
  40152. void triggerButtonClick (const String& buttonName);
  40153. /** Adds a textbox to the window for entering strings.
  40154. @param name an internal name for the text-box. This is the name to pass to
  40155. the getTextEditorContents() method to find out what the
  40156. user typed-in.
  40157. @param initialContents a string to show in the text box when it's first shown
  40158. @param onScreenLabel if this is non-empty, it will be displayed next to the
  40159. text-box to label it.
  40160. @param isPasswordBox if true, the text editor will display asterisks instead of
  40161. the actual text
  40162. @see getTextEditorContents
  40163. */
  40164. void addTextEditor (const String& name,
  40165. const String& initialContents,
  40166. const String& onScreenLabel = String::empty,
  40167. bool isPasswordBox = false);
  40168. /** Returns the contents of a named textbox.
  40169. After showing an AlertWindow that contains a text editor, this can be
  40170. used to find out what the user has typed into it.
  40171. @param nameOfTextEditor the name of the text box that you're interested in
  40172. @see addTextEditor
  40173. */
  40174. const String getTextEditorContents (const String& nameOfTextEditor) const;
  40175. /** Adds a drop-down list of choices to the box.
  40176. After the box has been shown, the getComboBoxComponent() method can
  40177. be used to find out which item the user picked.
  40178. @param name the label to use for the drop-down list
  40179. @param items the list of items to show in it
  40180. @param onScreenLabel if this is non-empty, it will be displayed next to the
  40181. combo-box to label it.
  40182. @see getComboBoxComponent
  40183. */
  40184. void addComboBox (const String& name,
  40185. const StringArray& items,
  40186. const String& onScreenLabel = String::empty);
  40187. /** Returns a drop-down list that was added to the AlertWindow.
  40188. @param nameOfList the name that was passed into the addComboBox() method
  40189. when creating the drop-down
  40190. @returns the ComboBox component, or 0 if none was found for the given name.
  40191. */
  40192. ComboBox* getComboBoxComponent (const String& nameOfList) const;
  40193. /** Adds a block of text.
  40194. This is handy for adding a multi-line note next to a textbox or combo-box,
  40195. to provide more details about what's going on.
  40196. */
  40197. void addTextBlock (const String& text);
  40198. /** Adds a progress-bar to the window.
  40199. @param progressValue a variable that will be repeatedly checked while the
  40200. dialog box is visible, to see how far the process has
  40201. got. The value should be in the range 0 to 1.0
  40202. */
  40203. void addProgressBarComponent (double& progressValue);
  40204. /** Adds a user-defined component to the dialog box.
  40205. @param component the component to add - its size should be set up correctly
  40206. before it is passed in. The caller is responsible for deleting
  40207. the component later on - the AlertWindow won't delete it.
  40208. */
  40209. void addCustomComponent (Component* component);
  40210. /** Returns the number of custom components in the dialog box.
  40211. @see getCustomComponent, addCustomComponent
  40212. */
  40213. int getNumCustomComponents() const;
  40214. /** Returns one of the custom components in the dialog box.
  40215. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  40216. will return 0
  40217. @see getNumCustomComponents, addCustomComponent
  40218. */
  40219. Component* getCustomComponent (int index) const;
  40220. /** Removes one of the custom components in the dialog box.
  40221. Note that this won't delete it, it just removes the component from the window
  40222. @param index a value 0 to (getNumCustomComponents() - 1). Out-of-range indexes
  40223. will return 0
  40224. @returns the component that was removed (or zero)
  40225. @see getNumCustomComponents, addCustomComponent
  40226. */
  40227. Component* removeCustomComponent (int index);
  40228. /** Returns true if the window contains any components other than just buttons.*/
  40229. bool containsAnyExtraComponents() const;
  40230. // easy-to-use message box functions:
  40231. /** Shows a dialog box that just has a message and a single button to get rid of it.
  40232. The box is shown modally, and the method returns after the user
  40233. has clicked the button (or pressed the escape or return keys).
  40234. @param iconType the type of icon to show
  40235. @param title the headline to show at the top of the box
  40236. @param message a longer, more descriptive message to show underneath the
  40237. headline
  40238. @param buttonText the text to show in the button - if this string is empty, the
  40239. default string "ok" (or a localised version) will be used.
  40240. @param associatedComponent if this is non-zero, it specifies the component that the
  40241. alert window should be associated with. Depending on the look
  40242. and feel, this might be used for positioning of the alert window.
  40243. */
  40244. static void JUCE_CALLTYPE showMessageBox (AlertIconType iconType,
  40245. const String& title,
  40246. const String& message,
  40247. const String& buttonText = String::empty,
  40248. Component* associatedComponent = 0);
  40249. /** Shows a dialog box with two buttons.
  40250. Ideal for ok/cancel or yes/no choices. The return key can also be used
  40251. to trigger the first button, and the escape key for the second button.
  40252. @param iconType the type of icon to show
  40253. @param title the headline to show at the top of the box
  40254. @param message a longer, more descriptive message to show underneath the
  40255. headline
  40256. @param button1Text the text to show in the first button - if this string is
  40257. empty, the default string "ok" (or a localised version of it)
  40258. will be used.
  40259. @param button2Text the text to show in the second button - if this string is
  40260. empty, the default string "cancel" (or a localised version of it)
  40261. will be used.
  40262. @param associatedComponent if this is non-zero, it specifies the component that the
  40263. alert window should be associated with. Depending on the look
  40264. and feel, this might be used for positioning of the alert window.
  40265. @returns true if button 1 was clicked, false if it was button 2
  40266. */
  40267. static bool JUCE_CALLTYPE showOkCancelBox (AlertIconType iconType,
  40268. const String& title,
  40269. const String& message,
  40270. const String& button1Text = String::empty,
  40271. const String& button2Text = String::empty,
  40272. Component* associatedComponent = 0);
  40273. /** Shows a dialog box with three buttons.
  40274. Ideal for yes/no/cancel boxes.
  40275. The escape key can be used to trigger the third button.
  40276. @param iconType the type of icon to show
  40277. @param title the headline to show at the top of the box
  40278. @param message a longer, more descriptive message to show underneath the
  40279. headline
  40280. @param button1Text the text to show in the first button - if an empty string, then
  40281. "yes" will be used (or a localised version of it)
  40282. @param button2Text the text to show in the first button - if an empty string, then
  40283. "no" will be used (or a localised version of it)
  40284. @param button3Text the text to show in the first button - if an empty string, then
  40285. "cancel" will be used (or a localised version of it)
  40286. @param associatedComponent if this is non-zero, it specifies the component that the
  40287. alert window should be associated with. Depending on the look
  40288. and feel, this might be used for positioning of the alert window.
  40289. @returns one of the following values:
  40290. - 0 if the third button was pressed (normally used for 'cancel')
  40291. - 1 if the first button was pressed (normally used for 'yes')
  40292. - 2 if the middle button was pressed (normally used for 'no')
  40293. */
  40294. static int JUCE_CALLTYPE showYesNoCancelBox (AlertIconType iconType,
  40295. const String& title,
  40296. const String& message,
  40297. const String& button1Text = String::empty,
  40298. const String& button2Text = String::empty,
  40299. const String& button3Text = String::empty,
  40300. Component* associatedComponent = 0);
  40301. /** Shows an operating-system native dialog box.
  40302. @param title the title to use at the top
  40303. @param bodyText the longer message to show
  40304. @param isOkCancel if true, this will show an ok/cancel box, if false,
  40305. it'll show a box with just an ok button
  40306. @returns true if the ok button was pressed, false if they pressed cancel.
  40307. */
  40308. static bool JUCE_CALLTYPE showNativeDialogBox (const String& title,
  40309. const String& bodyText,
  40310. bool isOkCancel);
  40311. /** A set of colour IDs to use to change the colour of various aspects of the alert box.
  40312. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  40313. methods.
  40314. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  40315. */
  40316. enum ColourIds
  40317. {
  40318. backgroundColourId = 0x1001800, /**< The background colour for the window. */
  40319. textColourId = 0x1001810, /**< The colour for the text. */
  40320. outlineColourId = 0x1001820 /**< An optional colour to use to draw a border around the window. */
  40321. };
  40322. juce_UseDebuggingNewOperator
  40323. protected:
  40324. /** @internal */
  40325. void paint (Graphics& g);
  40326. /** @internal */
  40327. void mouseDown (const MouseEvent& e);
  40328. /** @internal */
  40329. void mouseDrag (const MouseEvent& e);
  40330. /** @internal */
  40331. bool keyPressed (const KeyPress& key);
  40332. /** @internal */
  40333. void buttonClicked (Button* button);
  40334. /** @internal */
  40335. void lookAndFeelChanged();
  40336. /** @internal */
  40337. void userTriedToCloseWindow();
  40338. /** @internal */
  40339. int getDesktopWindowStyleFlags() const;
  40340. private:
  40341. String text;
  40342. TextLayout textLayout;
  40343. AlertIconType alertIconType;
  40344. ComponentBoundsConstrainer constrainer;
  40345. ComponentDragger dragger;
  40346. Rectangle<int> textArea;
  40347. Array<void*> buttons, textBoxes, comboBoxes;
  40348. Array<void*> progressBars, customComps, textBlocks, allComps;
  40349. StringArray textboxNames, comboBoxNames;
  40350. Font font;
  40351. Component* associatedComponent;
  40352. void updateLayout (bool onlyIncreaseSize);
  40353. // disable copy constructor
  40354. AlertWindow (const AlertWindow&);
  40355. AlertWindow& operator= (const AlertWindow&);
  40356. };
  40357. #endif // __JUCE_ALERTWINDOW_JUCEHEADER__
  40358. /*** End of inlined file: juce_AlertWindow.h ***/
  40359. class ToggleButton;
  40360. class TextButton;
  40361. class AlertWindow;
  40362. class TextLayout;
  40363. class ScrollBar;
  40364. class BubbleComponent;
  40365. class ComboBox;
  40366. class Button;
  40367. class FilenameComponent;
  40368. class DocumentWindow;
  40369. class ResizableWindow;
  40370. class GroupComponent;
  40371. class MenuBarComponent;
  40372. class DropShadower;
  40373. class GlyphArrangement;
  40374. class PropertyComponent;
  40375. class TableHeaderComponent;
  40376. class Toolbar;
  40377. class ToolbarItemComponent;
  40378. class PopupMenu;
  40379. class ProgressBar;
  40380. class FileBrowserComponent;
  40381. class DirectoryContentsDisplayComponent;
  40382. class FilePreviewComponent;
  40383. class ImageButton;
  40384. class CallOutBox;
  40385. /**
  40386. LookAndFeel objects define the appearance of all the JUCE widgets, and subclasses
  40387. can be used to apply different 'skins' to the application.
  40388. */
  40389. class JUCE_API LookAndFeel
  40390. {
  40391. public:
  40392. /** Creates the default JUCE look and feel. */
  40393. LookAndFeel();
  40394. /** Destructor. */
  40395. virtual ~LookAndFeel();
  40396. /** Returns the current default look-and-feel for a component to use when it
  40397. hasn't got one explicitly set.
  40398. @see setDefaultLookAndFeel
  40399. */
  40400. static LookAndFeel& getDefaultLookAndFeel() throw();
  40401. /** Changes the default look-and-feel.
  40402. @param newDefaultLookAndFeel the new look-and-feel object to use - if this is
  40403. set to 0, it will revert to using the default one. The
  40404. object passed-in must be deleted by the caller when
  40405. it's no longer needed.
  40406. @see getDefaultLookAndFeel
  40407. */
  40408. static void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw();
  40409. /** Looks for a colour that has been registered with the given colour ID number.
  40410. If a colour has been set for this ID number using setColour(), then it is
  40411. returned. If none has been set, it will just return Colours::black.
  40412. The colour IDs for various purposes are stored as enums in the components that
  40413. they are relevent to - for an example, see Slider::ColourIds,
  40414. Label::ColourIds, TextEditor::ColourIds, TreeView::ColourIds, etc.
  40415. If you're looking up a colour for use in drawing a component, it's usually
  40416. best not to call this directly, but to use the Component::findColour() method
  40417. instead. That will first check whether a suitable colour has been registered
  40418. directly with the component, and will fall-back on calling the component's
  40419. LookAndFeel's findColour() method if none is found.
  40420. @see setColour, Component::findColour, Component::setColour
  40421. */
  40422. const Colour findColour (int colourId) const throw();
  40423. /** Registers a colour to be used for a particular purpose.
  40424. For more details, see the comments for findColour().
  40425. @see findColour, Component::findColour, Component::setColour
  40426. */
  40427. void setColour (int colourId, const Colour& colour) throw();
  40428. /** Returns true if the specified colour ID has been explicitly set using the
  40429. setColour() method.
  40430. */
  40431. bool isColourSpecified (int colourId) const throw();
  40432. virtual const Typeface::Ptr getTypefaceForFont (const Font& font);
  40433. /** Allows you to change the default sans-serif font.
  40434. If you need to supply your own Typeface object for any of the default fonts, rather
  40435. than just supplying the name (e.g. if you want to use an embedded font), then
  40436. you should instead override getTypefaceForFont() to create and return the typeface.
  40437. */
  40438. void setDefaultSansSerifTypefaceName (const String& newName);
  40439. /** Override this to get the chance to swap a component's mouse cursor for a
  40440. customised one.
  40441. */
  40442. virtual const MouseCursor getMouseCursorFor (Component& component);
  40443. /** Draws the lozenge-shaped background for a standard button. */
  40444. virtual void drawButtonBackground (Graphics& g,
  40445. Button& button,
  40446. const Colour& backgroundColour,
  40447. bool isMouseOverButton,
  40448. bool isButtonDown);
  40449. virtual const Font getFontForTextButton (TextButton& button);
  40450. /** Draws the text for a TextButton. */
  40451. virtual void drawButtonText (Graphics& g,
  40452. TextButton& button,
  40453. bool isMouseOverButton,
  40454. bool isButtonDown);
  40455. /** Draws the contents of a standard ToggleButton. */
  40456. virtual void drawToggleButton (Graphics& g,
  40457. ToggleButton& button,
  40458. bool isMouseOverButton,
  40459. bool isButtonDown);
  40460. virtual void changeToggleButtonWidthToFitText (ToggleButton& button);
  40461. virtual void drawTickBox (Graphics& g,
  40462. Component& component,
  40463. float x, float y, float w, float h,
  40464. bool ticked,
  40465. bool isEnabled,
  40466. bool isMouseOverButton,
  40467. bool isButtonDown);
  40468. /* AlertWindow handling..
  40469. */
  40470. virtual AlertWindow* createAlertWindow (const String& title,
  40471. const String& message,
  40472. const String& button1,
  40473. const String& button2,
  40474. const String& button3,
  40475. AlertWindow::AlertIconType iconType,
  40476. int numButtons,
  40477. Component* associatedComponent);
  40478. virtual void drawAlertBox (Graphics& g,
  40479. AlertWindow& alert,
  40480. const Rectangle<int>& textArea,
  40481. TextLayout& textLayout);
  40482. virtual int getAlertBoxWindowFlags();
  40483. virtual int getAlertWindowButtonHeight();
  40484. virtual const Font getAlertWindowFont();
  40485. /** Draws a progress bar.
  40486. If the progress value is less than 0 or greater than 1.0, this should draw a spinning
  40487. bar that fills the whole space (i.e. to say that the app is still busy but the progress
  40488. isn't known). It can use the current time as a basis for playing an animation.
  40489. (Used by progress bars in AlertWindow).
  40490. */
  40491. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40492. int width, int height,
  40493. double progress, const String& textToShow);
  40494. // Draws a small image that spins to indicate that something's happening..
  40495. // This method should use the current time to animate itself, so just keep
  40496. // repainting it every so often.
  40497. virtual void drawSpinningWaitAnimation (Graphics& g, const Colour& colour,
  40498. int x, int y, int w, int h);
  40499. /** Draws one of the buttons on a scrollbar.
  40500. @param g the context to draw into
  40501. @param scrollbar the bar itself
  40502. @param width the width of the button
  40503. @param height the height of the button
  40504. @param buttonDirection the direction of the button, where 0 = up, 1 = right, 2 = down, 3 = left
  40505. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40506. @param isMouseOverButton whether the mouse is currently over the button (also true if it's held down)
  40507. @param isButtonDown whether the mouse button's held down
  40508. */
  40509. virtual void drawScrollbarButton (Graphics& g,
  40510. ScrollBar& scrollbar,
  40511. int width, int height,
  40512. int buttonDirection,
  40513. bool isScrollbarVertical,
  40514. bool isMouseOverButton,
  40515. bool isButtonDown);
  40516. /** Draws the thumb area of a scrollbar.
  40517. @param g the context to draw into
  40518. @param scrollbar the bar itself
  40519. @param x the x position of the left edge of the thumb area to draw in
  40520. @param y the y position of the top edge of the thumb area to draw in
  40521. @param width the width of the thumb area to draw in
  40522. @param height the height of the thumb area to draw in
  40523. @param isScrollbarVertical true if it's a vertical bar, false if horizontal
  40524. @param thumbStartPosition for vertical bars, the y co-ordinate of the top of the
  40525. thumb, or its x position for horizontal bars
  40526. @param thumbSize for vertical bars, the height of the thumb, or its width for
  40527. horizontal bars. This may be 0 if the thumb shouldn't be drawn.
  40528. @param isMouseOver whether the mouse is over the thumb area, also true if the mouse is
  40529. currently dragging the thumb
  40530. @param isMouseDown whether the mouse is currently dragging the scrollbar
  40531. */
  40532. virtual void drawScrollbar (Graphics& g,
  40533. ScrollBar& scrollbar,
  40534. int x, int y,
  40535. int width, int height,
  40536. bool isScrollbarVertical,
  40537. int thumbStartPosition,
  40538. int thumbSize,
  40539. bool isMouseOver,
  40540. bool isMouseDown);
  40541. /** Returns the component effect to use for a scrollbar */
  40542. virtual ImageEffectFilter* getScrollbarEffect();
  40543. /** Returns the minimum length in pixels to use for a scrollbar thumb. */
  40544. virtual int getMinimumScrollbarThumbSize (ScrollBar& scrollbar);
  40545. /** Returns the default thickness to use for a scrollbar. */
  40546. virtual int getDefaultScrollbarWidth();
  40547. /** Returns the length in pixels to use for a scrollbar button. */
  40548. virtual int getScrollbarButtonSize (ScrollBar& scrollbar);
  40549. /** Returns a tick shape for use in yes/no boxes, etc. */
  40550. virtual const Path getTickShape (float height);
  40551. /** Returns a cross shape for use in yes/no boxes, etc. */
  40552. virtual const Path getCrossShape (float height);
  40553. /** Draws the + or - box in a treeview. */
  40554. virtual void drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool isMouseOver);
  40555. virtual void fillTextEditorBackground (Graphics& g, int width, int height, TextEditor& textEditor);
  40556. virtual void drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor);
  40557. // these return an image from the ImageCache, so use ImageCache::release() to free it
  40558. virtual const Image getDefaultFolderImage();
  40559. virtual const Image getDefaultDocumentFileImage();
  40560. virtual void createFileChooserHeaderText (const String& title,
  40561. const String& instructions,
  40562. GlyphArrangement& destArrangement,
  40563. int width);
  40564. virtual void drawFileBrowserRow (Graphics& g, int width, int height,
  40565. const String& filename, Image* icon,
  40566. const String& fileSizeDescription,
  40567. const String& fileTimeDescription,
  40568. bool isDirectory,
  40569. bool isItemSelected,
  40570. int itemIndex);
  40571. virtual Button* createFileBrowserGoUpButton();
  40572. virtual void layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  40573. DirectoryContentsDisplayComponent* fileListComponent,
  40574. FilePreviewComponent* previewComp,
  40575. ComboBox* currentPathBox,
  40576. TextEditor* filenameBox,
  40577. Button* goUpButton);
  40578. virtual void drawBubble (Graphics& g,
  40579. float tipX, float tipY,
  40580. float boxX, float boxY, float boxW, float boxH);
  40581. /** Fills the background of a popup menu component. */
  40582. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40583. /** Draws one of the items in a popup menu. */
  40584. virtual void drawPopupMenuItem (Graphics& g,
  40585. int width, int height,
  40586. bool isSeparator,
  40587. bool isActive,
  40588. bool isHighlighted,
  40589. bool isTicked,
  40590. bool hasSubMenu,
  40591. const String& text,
  40592. const String& shortcutKeyText,
  40593. Image* image,
  40594. const Colour* const textColour);
  40595. /** Returns the size and style of font to use in popup menus. */
  40596. virtual const Font getPopupMenuFont();
  40597. virtual void drawPopupMenuUpDownArrow (Graphics& g,
  40598. int width, int height,
  40599. bool isScrollUpArrow);
  40600. /** Finds the best size for an item in a popup menu. */
  40601. virtual void getIdealPopupMenuItemSize (const String& text,
  40602. bool isSeparator,
  40603. int standardMenuItemHeight,
  40604. int& idealWidth,
  40605. int& idealHeight);
  40606. virtual int getMenuWindowFlags();
  40607. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40608. bool isMouseOverBar,
  40609. MenuBarComponent& menuBar);
  40610. virtual int getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40611. virtual const Font getMenuBarFont (MenuBarComponent& menuBar, int itemIndex, const String& itemText);
  40612. virtual void drawMenuBarItem (Graphics& g,
  40613. int width, int height,
  40614. int itemIndex,
  40615. const String& itemText,
  40616. bool isMouseOverItem,
  40617. bool isMenuOpen,
  40618. bool isMouseOverBar,
  40619. MenuBarComponent& menuBar);
  40620. virtual void drawComboBox (Graphics& g, int width, int height,
  40621. bool isButtonDown,
  40622. int buttonX, int buttonY,
  40623. int buttonW, int buttonH,
  40624. ComboBox& box);
  40625. virtual const Font getComboBoxFont (ComboBox& box);
  40626. virtual Label* createComboBoxTextBox (ComboBox& box);
  40627. virtual void positionComboBoxText (ComboBox& box, Label& labelToPosition);
  40628. virtual void drawLabel (Graphics& g, Label& label);
  40629. virtual void drawLinearSlider (Graphics& g,
  40630. int x, int y,
  40631. int width, int height,
  40632. float sliderPos,
  40633. float minSliderPos,
  40634. float maxSliderPos,
  40635. const Slider::SliderStyle style,
  40636. Slider& slider);
  40637. virtual void drawLinearSliderBackground (Graphics& g,
  40638. int x, int y,
  40639. int width, int height,
  40640. float sliderPos,
  40641. float minSliderPos,
  40642. float maxSliderPos,
  40643. const Slider::SliderStyle style,
  40644. Slider& slider);
  40645. virtual void drawLinearSliderThumb (Graphics& g,
  40646. int x, int y,
  40647. int width, int height,
  40648. float sliderPos,
  40649. float minSliderPos,
  40650. float maxSliderPos,
  40651. const Slider::SliderStyle style,
  40652. Slider& slider);
  40653. virtual int getSliderThumbRadius (Slider& slider);
  40654. virtual void drawRotarySlider (Graphics& g,
  40655. int x, int y,
  40656. int width, int height,
  40657. float sliderPosProportional,
  40658. float rotaryStartAngle,
  40659. float rotaryEndAngle,
  40660. Slider& slider);
  40661. virtual Button* createSliderButton (bool isIncrement);
  40662. virtual Label* createSliderTextBox (Slider& slider);
  40663. virtual ImageEffectFilter* getSliderEffect();
  40664. virtual void getTooltipSize (const String& tipText, int& width, int& height);
  40665. virtual void drawTooltip (Graphics& g, const String& text, int width, int height);
  40666. virtual Button* createFilenameComponentBrowseButton (const String& text);
  40667. virtual void layoutFilenameComponent (FilenameComponent& filenameComp,
  40668. ComboBox* filenameBox, Button* browseButton);
  40669. virtual void drawCornerResizer (Graphics& g,
  40670. int w, int h,
  40671. bool isMouseOver,
  40672. bool isMouseDragging);
  40673. virtual void drawResizableFrame (Graphics& g,
  40674. int w, int h,
  40675. const BorderSize& borders);
  40676. virtual void fillResizableWindowBackground (Graphics& g, int w, int h,
  40677. const BorderSize& border,
  40678. ResizableWindow& window);
  40679. virtual void drawResizableWindowBorder (Graphics& g,
  40680. int w, int h,
  40681. const BorderSize& border,
  40682. ResizableWindow& window);
  40683. virtual void drawDocumentWindowTitleBar (DocumentWindow& window,
  40684. Graphics& g, int w, int h,
  40685. int titleSpaceX, int titleSpaceW,
  40686. const Image* icon,
  40687. bool drawTitleTextOnLeft);
  40688. virtual Button* createDocumentWindowButton (int buttonType);
  40689. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40690. int titleBarX, int titleBarY,
  40691. int titleBarW, int titleBarH,
  40692. Button* minimiseButton,
  40693. Button* maximiseButton,
  40694. Button* closeButton,
  40695. bool positionTitleBarButtonsOnLeft);
  40696. virtual int getDefaultMenuBarHeight();
  40697. virtual DropShadower* createDropShadowerForComponent (Component* component);
  40698. virtual void drawStretchableLayoutResizerBar (Graphics& g,
  40699. int w, int h,
  40700. bool isVerticalBar,
  40701. bool isMouseOver,
  40702. bool isMouseDragging);
  40703. virtual void drawGroupComponentOutline (Graphics& g, int w, int h,
  40704. const String& text,
  40705. const Justification& position,
  40706. GroupComponent& group);
  40707. virtual void createTabButtonShape (Path& p,
  40708. int width, int height,
  40709. int tabIndex,
  40710. const String& text,
  40711. Button& button,
  40712. TabbedButtonBar::Orientation orientation,
  40713. bool isMouseOver,
  40714. bool isMouseDown,
  40715. bool isFrontTab);
  40716. virtual void fillTabButtonShape (Graphics& g,
  40717. const Path& path,
  40718. const Colour& preferredBackgroundColour,
  40719. int tabIndex,
  40720. const String& text,
  40721. Button& button,
  40722. TabbedButtonBar::Orientation orientation,
  40723. bool isMouseOver,
  40724. bool isMouseDown,
  40725. bool isFrontTab);
  40726. virtual void drawTabButtonText (Graphics& g,
  40727. int x, int y, int w, int h,
  40728. const Colour& preferredBackgroundColour,
  40729. int tabIndex,
  40730. const String& text,
  40731. Button& button,
  40732. TabbedButtonBar::Orientation orientation,
  40733. bool isMouseOver,
  40734. bool isMouseDown,
  40735. bool isFrontTab);
  40736. virtual int getTabButtonOverlap (int tabDepth);
  40737. virtual int getTabButtonSpaceAroundImage();
  40738. virtual int getTabButtonBestWidth (int tabIndex,
  40739. const String& text,
  40740. int tabDepth,
  40741. Button& button);
  40742. virtual void drawTabButton (Graphics& g,
  40743. int w, int h,
  40744. const Colour& preferredColour,
  40745. int tabIndex,
  40746. const String& text,
  40747. Button& button,
  40748. TabbedButtonBar::Orientation orientation,
  40749. bool isMouseOver,
  40750. bool isMouseDown,
  40751. bool isFrontTab);
  40752. virtual void drawTabAreaBehindFrontButton (Graphics& g,
  40753. int w, int h,
  40754. TabbedButtonBar& tabBar,
  40755. TabbedButtonBar::Orientation orientation);
  40756. virtual Button* createTabBarExtrasButton();
  40757. virtual void drawImageButton (Graphics& g, Image* image,
  40758. int imageX, int imageY, int imageW, int imageH,
  40759. const Colour& overlayColour,
  40760. float imageOpacity,
  40761. ImageButton& button);
  40762. virtual void drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header);
  40763. virtual void drawTableHeaderColumn (Graphics& g, const String& columnName, int columnId,
  40764. int width, int height,
  40765. bool isMouseOver, bool isMouseDown,
  40766. int columnFlags);
  40767. virtual void paintToolbarBackground (Graphics& g, int width, int height, Toolbar& toolbar);
  40768. virtual Button* createToolbarMissingItemsButton (Toolbar& toolbar);
  40769. virtual void paintToolbarButtonBackground (Graphics& g, int width, int height,
  40770. bool isMouseOver, bool isMouseDown,
  40771. ToolbarItemComponent& component);
  40772. virtual void paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  40773. const String& text, ToolbarItemComponent& component);
  40774. virtual void drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  40775. bool isOpen, int width, int height);
  40776. virtual void drawPropertyComponentBackground (Graphics& g, int width, int height,
  40777. PropertyComponent& component);
  40778. virtual void drawPropertyComponentLabel (Graphics& g, int width, int height,
  40779. PropertyComponent& component);
  40780. virtual const Rectangle<int> getPropertyComponentContentPosition (PropertyComponent& component);
  40781. void drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path);
  40782. virtual void drawLevelMeter (Graphics& g, int width, int height, float level);
  40783. virtual void drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription);
  40784. /**
  40785. */
  40786. virtual void playAlertSound();
  40787. /** Utility function to draw a shiny, glassy circle (for round LED-type buttons). */
  40788. static void drawGlassSphere (Graphics& g,
  40789. float x, float y,
  40790. float diameter,
  40791. const Colour& colour,
  40792. float outlineThickness) throw();
  40793. static void drawGlassPointer (Graphics& g,
  40794. float x, float y,
  40795. float diameter,
  40796. const Colour& colour, float outlineThickness,
  40797. int direction) throw();
  40798. /** Utility function to draw a shiny, glassy oblong (for text buttons). */
  40799. static void drawGlassLozenge (Graphics& g,
  40800. float x, float y,
  40801. float width, float height,
  40802. const Colour& colour,
  40803. float outlineThickness,
  40804. float cornerSize,
  40805. bool flatOnLeft, bool flatOnRight,
  40806. bool flatOnTop, bool flatOnBottom) throw();
  40807. juce_UseDebuggingNewOperator
  40808. private:
  40809. friend void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI();
  40810. static void clearDefaultLookAndFeel() throw(); // called at shutdown
  40811. Array <int> colourIds;
  40812. Array <Colour> colours;
  40813. // default typeface names
  40814. String defaultSans, defaultSerif, defaultFixed;
  40815. void drawShinyButtonShape (Graphics& g,
  40816. float x, float y, float w, float h, float maxCornerSize,
  40817. const Colour& baseColour,
  40818. float strokeWidth,
  40819. bool flatOnLeft,
  40820. bool flatOnRight,
  40821. bool flatOnTop,
  40822. bool flatOnBottom) throw();
  40823. LookAndFeel (const LookAndFeel&);
  40824. LookAndFeel& operator= (const LookAndFeel&);
  40825. };
  40826. #endif // __JUCE_LOOKANDFEEL_JUCEHEADER__
  40827. /*** End of inlined file: juce_LookAndFeel.h ***/
  40828. #endif
  40829. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40830. /*** Start of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40831. #ifndef __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40832. #define __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40833. /**
  40834. The original Juce look-and-feel.
  40835. */
  40836. class JUCE_API OldSchoolLookAndFeel : public LookAndFeel
  40837. {
  40838. public:
  40839. /** Creates the default JUCE look and feel. */
  40840. OldSchoolLookAndFeel();
  40841. /** Destructor. */
  40842. virtual ~OldSchoolLookAndFeel();
  40843. /** Draws the lozenge-shaped background for a standard button. */
  40844. virtual void drawButtonBackground (Graphics& g,
  40845. Button& button,
  40846. const Colour& backgroundColour,
  40847. bool isMouseOverButton,
  40848. bool isButtonDown);
  40849. /** Draws the contents of a standard ToggleButton. */
  40850. virtual void drawToggleButton (Graphics& g,
  40851. ToggleButton& button,
  40852. bool isMouseOverButton,
  40853. bool isButtonDown);
  40854. virtual void drawTickBox (Graphics& g,
  40855. Component& component,
  40856. float x, float y, float w, float h,
  40857. bool ticked,
  40858. bool isEnabled,
  40859. bool isMouseOverButton,
  40860. bool isButtonDown);
  40861. virtual void drawProgressBar (Graphics& g, ProgressBar& progressBar,
  40862. int width, int height,
  40863. double progress, const String& textToShow);
  40864. virtual void drawScrollbarButton (Graphics& g,
  40865. ScrollBar& scrollbar,
  40866. int width, int height,
  40867. int buttonDirection,
  40868. bool isScrollbarVertical,
  40869. bool isMouseOverButton,
  40870. bool isButtonDown);
  40871. virtual void drawScrollbar (Graphics& g,
  40872. ScrollBar& scrollbar,
  40873. int x, int y,
  40874. int width, int height,
  40875. bool isScrollbarVertical,
  40876. int thumbStartPosition,
  40877. int thumbSize,
  40878. bool isMouseOver,
  40879. bool isMouseDown);
  40880. virtual ImageEffectFilter* getScrollbarEffect();
  40881. virtual void drawTextEditorOutline (Graphics& g,
  40882. int width, int height,
  40883. TextEditor& textEditor);
  40884. /** Fills the background of a popup menu component. */
  40885. virtual void drawPopupMenuBackground (Graphics& g, int width, int height);
  40886. virtual void drawMenuBarBackground (Graphics& g, int width, int height,
  40887. bool isMouseOverBar,
  40888. MenuBarComponent& menuBar);
  40889. virtual void drawComboBox (Graphics& g, int width, int height,
  40890. bool isButtonDown,
  40891. int buttonX, int buttonY,
  40892. int buttonW, int buttonH,
  40893. ComboBox& box);
  40894. virtual const Font getComboBoxFont (ComboBox& box);
  40895. virtual void drawLinearSlider (Graphics& g,
  40896. int x, int y,
  40897. int width, int height,
  40898. float sliderPos,
  40899. float minSliderPos,
  40900. float maxSliderPos,
  40901. const Slider::SliderStyle style,
  40902. Slider& slider);
  40903. virtual int getSliderThumbRadius (Slider& slider);
  40904. virtual Button* createSliderButton (bool isIncrement);
  40905. virtual ImageEffectFilter* getSliderEffect();
  40906. virtual void drawCornerResizer (Graphics& g,
  40907. int w, int h,
  40908. bool isMouseOver,
  40909. bool isMouseDragging);
  40910. virtual Button* createDocumentWindowButton (int buttonType);
  40911. virtual void positionDocumentWindowButtons (DocumentWindow& window,
  40912. int titleBarX, int titleBarY,
  40913. int titleBarW, int titleBarH,
  40914. Button* minimiseButton,
  40915. Button* maximiseButton,
  40916. Button* closeButton,
  40917. bool positionTitleBarButtonsOnLeft);
  40918. juce_UseDebuggingNewOperator
  40919. private:
  40920. DropShadowEffect scrollbarShadow;
  40921. OldSchoolLookAndFeel (const OldSchoolLookAndFeel&);
  40922. OldSchoolLookAndFeel& operator= (const OldSchoolLookAndFeel&);
  40923. };
  40924. #endif // __JUCE_OLDSCHOOLLOOKANDFEEL_JUCEHEADER__
  40925. /*** End of inlined file: juce_OldSchoolLookAndFeel.h ***/
  40926. #endif
  40927. #ifndef __JUCE_MENUBARCOMPONENT_JUCEHEADER__
  40928. #endif
  40929. #ifndef __JUCE_MENUBARMODEL_JUCEHEADER__
  40930. #endif
  40931. #ifndef __JUCE_POPUPMENU_JUCEHEADER__
  40932. #endif
  40933. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40934. /*** Start of inlined file: juce_PopupMenuCustomComponent.h ***/
  40935. #ifndef __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40936. #define __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40937. /** A user-defined copmonent that can appear inside one of the rows of a popup menu.
  40938. @see PopupMenu::addCustomItem
  40939. */
  40940. class JUCE_API PopupMenuCustomComponent : public Component,
  40941. public ReferenceCountedObject
  40942. {
  40943. public:
  40944. /** Destructor. */
  40945. ~PopupMenuCustomComponent();
  40946. /** Chooses the size that this component would like to have.
  40947. Note that the size which this method returns isn't necessarily the one that
  40948. the menu will give it, as it will be stretched to fit the other items in
  40949. the menu.
  40950. */
  40951. virtual void getIdealSize (int& idealWidth,
  40952. int& idealHeight) = 0;
  40953. /** Dismisses the menu indicating that this item has been chosen.
  40954. This will cause the menu to exit from its modal state, returning
  40955. this item's id as the result.
  40956. */
  40957. void triggerMenuItem();
  40958. /** Returns true if this item should be highlighted because the mouse is
  40959. over it.
  40960. You can call this method in your paint() method to find out whether
  40961. to draw a highlight.
  40962. */
  40963. bool isItemHighlighted() const throw() { return isHighlighted; }
  40964. protected:
  40965. /** Constructor.
  40966. If isTriggeredAutomatically is true, then the menu will automatically detect
  40967. a click on this component and use that to trigger it. If it's false, then it's
  40968. up to your class to manually trigger the item if it wants to.
  40969. */
  40970. PopupMenuCustomComponent (bool isTriggeredAutomatically = true);
  40971. private:
  40972. friend class PopupMenu;
  40973. friend class PopupMenu::ItemComponent;
  40974. friend class PopupMenu::Window;
  40975. bool isHighlighted, isTriggeredAutomatically;
  40976. PopupMenuCustomComponent (const PopupMenuCustomComponent&);
  40977. PopupMenuCustomComponent& operator= (const PopupMenuCustomComponent&);
  40978. };
  40979. #endif // __JUCE_POPUPMENUCUSTOMCOMPONENT_JUCEHEADER__
  40980. /*** End of inlined file: juce_PopupMenuCustomComponent.h ***/
  40981. #endif
  40982. #ifndef __JUCE_COMPONENTDRAGGER_JUCEHEADER__
  40983. #endif
  40984. #ifndef __JUCE_DRAGANDDROPCONTAINER_JUCEHEADER__
  40985. #endif
  40986. #ifndef __JUCE_DRAGANDDROPTARGET_JUCEHEADER__
  40987. #endif
  40988. #ifndef __JUCE_FILEDRAGANDDROPTARGET_JUCEHEADER__
  40989. #endif
  40990. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40991. /*** Start of inlined file: juce_LassoComponent.h ***/
  40992. #ifndef __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40993. #define __JUCE_LASSOCOMPONENT_JUCEHEADER__
  40994. /*** Start of inlined file: juce_SelectedItemSet.h ***/
  40995. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40996. #define __JUCE_SELECTEDITEMSET_JUCEHEADER__
  40997. /** Manages a list of selectable items.
  40998. Use one of these to keep a track of things that the user has highlighted, like
  40999. icons or things in a list.
  41000. The class is templated so that you can use it to hold either a set of pointers
  41001. to objects, or a set of ID numbers or handles, for cases where each item may
  41002. not always have a corresponding object.
  41003. To be informed when items are selected/deselected, register a ChangeListener with
  41004. this object.
  41005. @see SelectableObject
  41006. */
  41007. template <class SelectableItemType>
  41008. class JUCE_API SelectedItemSet : public ChangeBroadcaster
  41009. {
  41010. public:
  41011. typedef SelectableItemType ItemType;
  41012. typedef PARAMETER_TYPE (SelectableItemType) ParameterType;
  41013. /** Creates an empty set. */
  41014. SelectedItemSet()
  41015. {
  41016. }
  41017. /** Creates a set based on an array of items. */
  41018. explicit SelectedItemSet (const Array <SelectableItemType>& items)
  41019. : selectedItems (items)
  41020. {
  41021. }
  41022. /** Creates a copy of another set. */
  41023. SelectedItemSet (const SelectedItemSet& other)
  41024. : selectedItems (other.selectedItems)
  41025. {
  41026. }
  41027. /** Creates a copy of another set. */
  41028. SelectedItemSet& operator= (const SelectedItemSet& other)
  41029. {
  41030. if (selectedItems != other.selectedItems)
  41031. {
  41032. selectedItems = other.selectedItems;
  41033. changed();
  41034. }
  41035. return *this;
  41036. }
  41037. /** Destructor. */
  41038. ~SelectedItemSet()
  41039. {
  41040. }
  41041. /** Clears any other currently selected items, and selects this item.
  41042. If this item is already the only thing selected, no change notification
  41043. will be sent out.
  41044. @see addToSelection, addToSelectionBasedOnModifiers
  41045. */
  41046. void selectOnly (ParameterType item)
  41047. {
  41048. if (isSelected (item))
  41049. {
  41050. for (int i = selectedItems.size(); --i >= 0;)
  41051. {
  41052. if (selectedItems.getUnchecked(i) != item)
  41053. {
  41054. deselect (selectedItems.getUnchecked(i));
  41055. i = jmin (i, selectedItems.size());
  41056. }
  41057. }
  41058. }
  41059. else
  41060. {
  41061. deselectAll();
  41062. changed();
  41063. selectedItems.add (item);
  41064. itemSelected (item);
  41065. }
  41066. }
  41067. /** Selects an item.
  41068. If the item is already selected, no change notification will be sent out.
  41069. @see selectOnly, addToSelectionBasedOnModifiers
  41070. */
  41071. void addToSelection (ParameterType item)
  41072. {
  41073. if (! isSelected (item))
  41074. {
  41075. changed();
  41076. selectedItems.add (item);
  41077. itemSelected (item);
  41078. }
  41079. }
  41080. /** Selects or deselects an item.
  41081. This will use the modifier keys to decide whether to deselect other items
  41082. first.
  41083. So if the shift key is held down, the item will be added without deselecting
  41084. anything (same as calling addToSelection() )
  41085. If no modifiers are down, the current selection will be cleared first (same
  41086. as calling selectOnly() )
  41087. If the ctrl (or command on the Mac) key is held down, the item will be toggled -
  41088. so it'll be added to the set unless it's already there, in which case it'll be
  41089. deselected.
  41090. If the items that you're selecting can also be dragged, you may need to use the
  41091. addToSelectionOnMouseDown() and addToSelectionOnMouseUp() calls to handle the
  41092. subtleties of this kind of usage.
  41093. @see selectOnly, addToSelection, addToSelectionOnMouseDown, addToSelectionOnMouseUp
  41094. */
  41095. void addToSelectionBasedOnModifiers (ParameterType item,
  41096. const ModifierKeys& modifiers)
  41097. {
  41098. if (modifiers.isShiftDown())
  41099. {
  41100. addToSelection (item);
  41101. }
  41102. else if (modifiers.isCommandDown())
  41103. {
  41104. if (isSelected (item))
  41105. deselect (item);
  41106. else
  41107. addToSelection (item);
  41108. }
  41109. else
  41110. {
  41111. selectOnly (item);
  41112. }
  41113. }
  41114. /** Selects or deselects items that can also be dragged, based on a mouse-down event.
  41115. If you call addToSelectionOnMouseDown() at the start of your mouseDown event,
  41116. and then call addToSelectionOnMouseUp() at the end of your mouseUp event, this
  41117. makes it easy to handle multiple-selection of sets of objects that can also
  41118. be dragged.
  41119. For example, if you have several items already selected, and you click on
  41120. one of them (without dragging), then you'd expect this to deselect the other, and
  41121. just select the item you clicked on. But if you had clicked on this item and
  41122. dragged it, you'd have expected them all to stay selected.
  41123. When you call this method, you'll need to store the boolean result, because the
  41124. addToSelectionOnMouseUp() method will need to be know this value.
  41125. @see addToSelectionOnMouseUp, addToSelectionBasedOnModifiers
  41126. */
  41127. bool addToSelectionOnMouseDown (ParameterType item,
  41128. const ModifierKeys& modifiers)
  41129. {
  41130. if (isSelected (item))
  41131. {
  41132. return ! modifiers.isPopupMenu();
  41133. }
  41134. else
  41135. {
  41136. addToSelectionBasedOnModifiers (item, modifiers);
  41137. return false;
  41138. }
  41139. }
  41140. /** Selects or deselects items that can also be dragged, based on a mouse-up event.
  41141. Call this during a mouseUp callback, when you have previously called the
  41142. addToSelectionOnMouseDown() method during your mouseDown event.
  41143. See addToSelectionOnMouseDown() for more info
  41144. @param item the item to select (or deselect)
  41145. @param modifiers the modifiers from the mouse-up event
  41146. @param wasItemDragged true if your item was dragged during the mouse click
  41147. @param resultOfMouseDownSelectMethod this is the boolean return value that came
  41148. back from the addToSelectionOnMouseDown() call that you
  41149. should have made during the matching mouseDown event
  41150. */
  41151. void addToSelectionOnMouseUp (ParameterType item,
  41152. const ModifierKeys& modifiers,
  41153. const bool wasItemDragged,
  41154. const bool resultOfMouseDownSelectMethod)
  41155. {
  41156. if (resultOfMouseDownSelectMethod && ! wasItemDragged)
  41157. addToSelectionBasedOnModifiers (item, modifiers);
  41158. }
  41159. /** Deselects an item. */
  41160. void deselect (ParameterType item)
  41161. {
  41162. const int i = selectedItems.indexOf (item);
  41163. if (i >= 0)
  41164. {
  41165. changed();
  41166. itemDeselected (selectedItems.remove (i));
  41167. }
  41168. }
  41169. /** Deselects all items. */
  41170. void deselectAll()
  41171. {
  41172. if (selectedItems.size() > 0)
  41173. {
  41174. changed();
  41175. for (int i = selectedItems.size(); --i >= 0;)
  41176. {
  41177. itemDeselected (selectedItems.remove (i));
  41178. i = jmin (i, selectedItems.size());
  41179. }
  41180. }
  41181. }
  41182. /** Returns the number of currently selected items.
  41183. @see getSelectedItem
  41184. */
  41185. int getNumSelected() const throw()
  41186. {
  41187. return selectedItems.size();
  41188. }
  41189. /** Returns one of the currently selected items.
  41190. Returns 0 if the index is out-of-range.
  41191. @see getNumSelected
  41192. */
  41193. SelectableItemType getSelectedItem (const int index) const throw()
  41194. {
  41195. return selectedItems [index];
  41196. }
  41197. /** True if this item is currently selected. */
  41198. bool isSelected (ParameterType item) const throw()
  41199. {
  41200. return selectedItems.contains (item);
  41201. }
  41202. const Array <SelectableItemType>& getItemArray() const throw() { return selectedItems; }
  41203. /** Can be overridden to do special handling when an item is selected.
  41204. For example, if the item is an object, you might want to call it and tell
  41205. it that it's being selected.
  41206. */
  41207. virtual void itemSelected (SelectableItemType item) { (void) item; }
  41208. /** Can be overridden to do special handling when an item is deselected.
  41209. For example, if the item is an object, you might want to call it and tell
  41210. it that it's being deselected.
  41211. */
  41212. virtual void itemDeselected (SelectableItemType item) { (void) item; }
  41213. /** Used internally, but can be called to force a change message to be sent to the ChangeListeners.
  41214. */
  41215. void changed (const bool synchronous = false)
  41216. {
  41217. if (synchronous)
  41218. sendSynchronousChangeMessage (this);
  41219. else
  41220. sendChangeMessage (this);
  41221. }
  41222. juce_UseDebuggingNewOperator
  41223. private:
  41224. Array <SelectableItemType> selectedItems;
  41225. };
  41226. #endif // __JUCE_SELECTEDITEMSET_JUCEHEADER__
  41227. /*** End of inlined file: juce_SelectedItemSet.h ***/
  41228. /**
  41229. A class used by the LassoComponent to manage the things that it selects.
  41230. This allows the LassoComponent to find out which items are within the lasso,
  41231. and to change the list of selected items.
  41232. @see LassoComponent, SelectedItemSet
  41233. */
  41234. template <class SelectableItemType>
  41235. class LassoSource
  41236. {
  41237. public:
  41238. /** Destructor. */
  41239. virtual ~LassoSource() {}
  41240. /** Returns the set of items that lie within a given lassoable region.
  41241. Your implementation of this method must find all the relevent items that lie
  41242. within the given rectangle. and add them to the itemsFound array.
  41243. The co-ordinates are relative to the top-left of the lasso component's parent
  41244. component. (i.e. they are the same as the size and position of the lasso
  41245. component itself).
  41246. */
  41247. virtual void findLassoItemsInArea (Array <SelectableItemType>& itemsFound,
  41248. const Rectangle<int>& area) = 0;
  41249. /** Returns the SelectedItemSet that the lasso should update.
  41250. This set will be continuously updated by the LassoComponent as it gets
  41251. dragged around, so make sure that you've got a ChangeListener attached to
  41252. the set so that your UI objects will know when the selection changes and
  41253. be able to update themselves appropriately.
  41254. */
  41255. virtual SelectedItemSet <SelectableItemType>& getLassoSelection() = 0;
  41256. };
  41257. /**
  41258. A component that acts as a rectangular selection region, which you drag with
  41259. the mouse to select groups of objects (in conjunction with a SelectedItemSet).
  41260. To use one of these:
  41261. - In your mouseDown or mouseDrag event, add the LassoComponent to your parent
  41262. component, and call its beginLasso() method, giving it a
  41263. suitable LassoSource object that it can use to find out which items are in
  41264. the active area.
  41265. - Each time your parent component gets a mouseDrag event, call dragLasso()
  41266. to update the lasso's position - it will use its LassoSource to calculate and
  41267. update the current selection.
  41268. - After the drag has finished and you get a mouseUp callback, you should call
  41269. endLasso() to clean up. This will make the lasso component invisible, and you
  41270. can remove it from the parent component, or delete it.
  41271. The class takes into account the modifier keys that are being held down while
  41272. the lasso is being dragged, so if shift is pressed, then any lassoed items will
  41273. be added to the original selection; if ctrl or command is pressed, they will be
  41274. xor'ed with any previously selected items.
  41275. @see LassoSource, SelectedItemSet
  41276. */
  41277. template <class SelectableItemType>
  41278. class LassoComponent : public Component
  41279. {
  41280. public:
  41281. /** Creates a Lasso component.
  41282. The fill colour is used to fill the lasso'ed rectangle, and the outline
  41283. colour is used to draw a line around its edge.
  41284. */
  41285. explicit LassoComponent (const int outlineThickness_ = 1)
  41286. : source (0),
  41287. outlineThickness (outlineThickness_)
  41288. {
  41289. }
  41290. /** Destructor. */
  41291. ~LassoComponent()
  41292. {
  41293. }
  41294. /** Call this in your mouseDown event, to initialise a drag.
  41295. Pass in a suitable LassoSource object which the lasso will use to find
  41296. the items and change the selection.
  41297. After using this method to initialise the lasso, repeatedly call dragLasso()
  41298. in your component's mouseDrag callback.
  41299. @see dragLasso, endLasso, LassoSource
  41300. */
  41301. void beginLasso (const MouseEvent& e,
  41302. LassoSource <SelectableItemType>* const lassoSource)
  41303. {
  41304. jassert (source == 0); // this suggests that you didn't call endLasso() after the last drag...
  41305. jassert (lassoSource != 0); // the source can't be null!
  41306. jassert (getParentComponent() != 0); // you need to add this to a parent component for it to work!
  41307. source = lassoSource;
  41308. if (lassoSource != 0)
  41309. originalSelection = lassoSource->getLassoSelection().getItemArray();
  41310. setSize (0, 0);
  41311. dragStartPos = e.getMouseDownPosition();
  41312. }
  41313. /** Call this in your mouseDrag event, to update the lasso's position.
  41314. This must be repeatedly calling when the mouse is dragged, after you've
  41315. first initialised the lasso with beginLasso().
  41316. This method takes into account the modifier keys that are being held down, so
  41317. if shift is pressed, then the lassoed items will be added to any that were
  41318. previously selected; if ctrl or command is pressed, then they will be xor'ed
  41319. with previously selected items.
  41320. @see beginLasso, endLasso
  41321. */
  41322. void dragLasso (const MouseEvent& e)
  41323. {
  41324. if (source != 0)
  41325. {
  41326. setBounds (Rectangle<int> (dragStartPos, e.getPosition()));
  41327. setVisible (true);
  41328. Array <SelectableItemType> itemsInLasso;
  41329. source->findLassoItemsInArea (itemsInLasso, getBounds());
  41330. if (e.mods.isShiftDown())
  41331. {
  41332. itemsInLasso.removeValuesIn (originalSelection); // to avoid duplicates
  41333. itemsInLasso.addArray (originalSelection);
  41334. }
  41335. else if (e.mods.isCommandDown() || e.mods.isAltDown())
  41336. {
  41337. Array <SelectableItemType> originalMinusNew (originalSelection);
  41338. originalMinusNew.removeValuesIn (itemsInLasso);
  41339. itemsInLasso.removeValuesIn (originalSelection);
  41340. itemsInLasso.addArray (originalMinusNew);
  41341. }
  41342. source->getLassoSelection() = SelectedItemSet <SelectableItemType> (itemsInLasso);
  41343. }
  41344. }
  41345. /** Call this in your mouseUp event, after the lasso has been dragged.
  41346. @see beginLasso, dragLasso
  41347. */
  41348. void endLasso()
  41349. {
  41350. source = 0;
  41351. originalSelection.clear();
  41352. setVisible (false);
  41353. }
  41354. /** A set of colour IDs to use to change the colour of various aspects of the label.
  41355. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  41356. methods.
  41357. Note that you can also use the constants from TextEditor::ColourIds to change the
  41358. colour of the text editor that is opened when a label is editable.
  41359. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  41360. */
  41361. enum ColourIds
  41362. {
  41363. lassoFillColourId = 0x1000440, /**< The colour to fill the lasso rectangle with. */
  41364. lassoOutlineColourId = 0x1000441, /**< The colour to draw the outline with. */
  41365. };
  41366. /** @internal */
  41367. void paint (Graphics& g)
  41368. {
  41369. g.fillAll (findColour (lassoFillColourId));
  41370. g.setColour (findColour (lassoOutlineColourId));
  41371. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  41372. // this suggests that you've left a lasso comp lying around after the
  41373. // mouse drag has finished.. Be careful to call endLasso() when you get a
  41374. // mouse-up event.
  41375. jassert (isMouseButtonDownAnywhere());
  41376. }
  41377. /** @internal */
  41378. bool hitTest (int, int) { return false; }
  41379. juce_UseDebuggingNewOperator
  41380. private:
  41381. Array <SelectableItemType> originalSelection;
  41382. LassoSource <SelectableItemType>* source;
  41383. int outlineThickness;
  41384. Point<int> dragStartPos;
  41385. };
  41386. #endif // __JUCE_LASSOCOMPONENT_JUCEHEADER__
  41387. /*** End of inlined file: juce_LassoComponent.h ***/
  41388. #endif
  41389. #ifndef __JUCE_MOUSECURSOR_JUCEHEADER__
  41390. #endif
  41391. #ifndef __JUCE_MOUSEEVENT_JUCEHEADER__
  41392. #endif
  41393. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41394. /*** Start of inlined file: juce_MouseHoverDetector.h ***/
  41395. #ifndef __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41396. #define __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41397. /**
  41398. Monitors a component for mouse activity, and triggers a callback
  41399. when the mouse hovers in one place for a specified length of time.
  41400. To use a hover-detector, just create one and call its setHoverComponent()
  41401. method to start it watching a component. You can call setHoverComponent (0)
  41402. to make it inactive.
  41403. (Be careful not to delete a component that's being monitored without first
  41404. stopping or deleting the hover detector).
  41405. */
  41406. class JUCE_API MouseHoverDetector
  41407. {
  41408. public:
  41409. /** Creates a hover detector.
  41410. Initially the object is inactive, and you need to tell it which component
  41411. to monitor, using the setHoverComponent() method.
  41412. @param hoverTimeMillisecs the number of milliseconds for which the mouse
  41413. needs to stay still before the mouseHovered() method
  41414. is invoked. You can change this setting later with
  41415. the setHoverTimeMillisecs() method
  41416. */
  41417. MouseHoverDetector (const int hoverTimeMillisecs = 400);
  41418. /** Destructor. */
  41419. virtual ~MouseHoverDetector();
  41420. /** Changes the time for which the mouse has to stay still before it's considered
  41421. to be hovering.
  41422. */
  41423. void setHoverTimeMillisecs (const int newTimeInMillisecs);
  41424. /** Changes the component that's being monitored for hovering.
  41425. Be careful not to delete a component that's being monitored without first
  41426. stopping or deleting the hover detector.
  41427. */
  41428. void setHoverComponent (Component* const newSourceComponent);
  41429. protected:
  41430. /** Called back when the mouse hovers.
  41431. After the mouse has stayed still over the component for the length of time
  41432. specified by setHoverTimeMillisecs(), this method will be invoked.
  41433. When the mouse is first moved after this callback has occurred, the
  41434. mouseMovedAfterHover() method will be called.
  41435. @param mouseX the mouse's X position relative to the component being monitored
  41436. @param mouseY the mouse's Y position relative to the component being monitored
  41437. */
  41438. virtual void mouseHovered (int mouseX,
  41439. int mouseY) = 0;
  41440. /** Called when the mouse is moved away after just having hovered. */
  41441. virtual void mouseMovedAfterHover() = 0;
  41442. private:
  41443. class JUCE_API HoverDetectorInternal : public MouseListener,
  41444. public Timer
  41445. {
  41446. public:
  41447. MouseHoverDetector* owner;
  41448. int lastX, lastY;
  41449. void timerCallback();
  41450. void mouseEnter (const MouseEvent&);
  41451. void mouseExit (const MouseEvent&);
  41452. void mouseDown (const MouseEvent&);
  41453. void mouseUp (const MouseEvent&);
  41454. void mouseMove (const MouseEvent&);
  41455. void mouseWheelMove (const MouseEvent&, float, float);
  41456. } internalTimer;
  41457. friend class HoverDetectorInternal;
  41458. Component* source;
  41459. int hoverTimeMillisecs;
  41460. bool hasJustHovered;
  41461. void hoverTimerCallback();
  41462. void checkJustHoveredCallback();
  41463. MouseHoverDetector (const MouseHoverDetector&);
  41464. MouseHoverDetector& operator= (const MouseHoverDetector&);
  41465. };
  41466. #endif // __JUCE_MOUSEHOVERDETECTOR_JUCEHEADER__
  41467. /*** End of inlined file: juce_MouseHoverDetector.h ***/
  41468. #endif
  41469. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41470. /*** Start of inlined file: juce_MouseInputSource.h ***/
  41471. #ifndef __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41472. #define __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41473. class Component;
  41474. class ComponentPeer;
  41475. class MouseInputSourceInternal;
  41476. /**
  41477. Represents a linear source of mouse events from a mouse device or individual finger
  41478. in a multi-touch environment.
  41479. Each MouseEvent object contains a reference to the MouseInputSource that generated
  41480. it. In an environment with a single mouse for input, all events will come from the
  41481. same source, but in a multi-touch system, there may be multiple MouseInputSource
  41482. obects active, each representing a stream of events coming from a particular finger.
  41483. Events coming from a single MouseInputSource are always sent in a fixed and predictable
  41484. order: a mouseMove will never be called without a mouseEnter having been sent beforehand,
  41485. the only events that can happen between a mouseDown and its corresponding mouseUp are
  41486. mouseDrags, etc.
  41487. When there are multiple touches arriving from multiple MouseInputSources, their
  41488. event streams may arrive in an interleaved order, so you should use the getIndex()
  41489. method to find out which finger each event came from.
  41490. @see MouseEvent
  41491. */
  41492. class JUCE_API MouseInputSource
  41493. {
  41494. public:
  41495. /** Creates a MouseInputSource.
  41496. You should never actually create a MouseInputSource in your own code - the
  41497. library takes care of managing these objects.
  41498. */
  41499. MouseInputSource (int index, bool isMouseDevice);
  41500. /** Destructor. */
  41501. ~MouseInputSource();
  41502. /** Returns true if this object represents a normal desk-based mouse device. */
  41503. bool isMouse() const;
  41504. /** Returns true if this object represents a source of touch events - i.e. a finger or stylus. */
  41505. bool isTouch() const;
  41506. /** Returns true if this source has an on-screen pointer that can hover over
  41507. items without clicking them.
  41508. */
  41509. bool canHover() const;
  41510. /** Returns true if this source may have a scroll wheel. */
  41511. bool hasMouseWheel() const;
  41512. /** Returns this source's index in the global list of possible sources.
  41513. If the system only has a single mouse, there will only be a single MouseInputSource
  41514. with an index of 0.
  41515. If the system supports multi-touch input, then the index will represent a finger
  41516. number, starting from 0. When the first touch event begins, it will have finger
  41517. number 0, and then if a second touch happens while the first is still down, it
  41518. will have index 1, etc.
  41519. */
  41520. int getIndex() const;
  41521. /** Returns true if this device is currently being pressed. */
  41522. bool isDragging() const;
  41523. /** Returns the last-known screen position of this source. */
  41524. const Point<int> getScreenPosition() const;
  41525. /** Returns a set of modifiers that indicate which buttons are currently
  41526. held down on this device.
  41527. */
  41528. const ModifierKeys getCurrentModifiers() const;
  41529. /** Returns the component that was last known to be under this pointer. */
  41530. Component* getComponentUnderMouse() const;
  41531. /** Tells the device to dispatch a mouse-move event.
  41532. This is asynchronous - the event will occur on the message thread.
  41533. */
  41534. void triggerFakeMove() const;
  41535. /** Returns the number of clicks that should be counted as belonging to the
  41536. current mouse event.
  41537. So the mouse is currently down and it's the second click of a double-click, this
  41538. will return 2.
  41539. */
  41540. int getNumberOfMultipleClicks() const throw();
  41541. /** Returns the time at which the last mouse-down occurred. */
  41542. const Time getLastMouseDownTime() const throw();
  41543. /** Returns the screen position at which the last mouse-down occurred. */
  41544. const Point<int> getLastMouseDownPosition() const throw();
  41545. /** Returns true if this mouse is currently down, and if it has been dragged more
  41546. than a couple of pixels from the place it was pressed.
  41547. */
  41548. bool hasMouseMovedSignificantlySincePressed() const throw();
  41549. bool hasMouseCursor() const throw();
  41550. void showMouseCursor (const MouseCursor& cursor);
  41551. void hideCursor();
  41552. void revealCursor();
  41553. void forceMouseCursorUpdate();
  41554. bool canDoUnboundedMovement() const throw();
  41555. /** Allows the mouse to move beyond the edges of the screen.
  41556. Calling this method when the mouse button is currently pressed will remove the cursor
  41557. from the screen and allow the mouse to (seem to) move beyond the edges of the screen.
  41558. This means that the co-ordinates returned to mouseDrag() will be unbounded, and this
  41559. can be used for things like custom slider controls or dragging objects around, where
  41560. movement would be otherwise be limited by the mouse hitting the edges of the screen.
  41561. The unbounded mode is automatically turned off when the mouse button is released, or
  41562. it can be turned off explicitly by calling this method again.
  41563. @param isEnabled whether to turn this mode on or off
  41564. @param keepCursorVisibleUntilOffscreen if set to false, the cursor will immediately be
  41565. hidden; if true, it will only be hidden when it
  41566. is moved beyond the edge of the screen
  41567. */
  41568. void enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen = false);
  41569. juce_UseDebuggingNewOperator
  41570. /** @internal */
  41571. void handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, const ModifierKeys& mods);
  41572. /** @internal */
  41573. void handleWheel (ComponentPeer* peer, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  41574. private:
  41575. friend class Desktop;
  41576. friend class ComponentPeer;
  41577. friend class MouseInputSourceInternal;
  41578. ScopedPointer<MouseInputSourceInternal> pimpl;
  41579. MouseInputSource (const MouseInputSource&);
  41580. MouseInputSource& operator= (const MouseInputSource&);
  41581. };
  41582. #endif // __JUCE_MOUSEINPUTSOURCE_JUCEHEADER__
  41583. /*** End of inlined file: juce_MouseInputSource.h ***/
  41584. #endif
  41585. #ifndef __JUCE_MOUSELISTENER_JUCEHEADER__
  41586. #endif
  41587. #ifndef __JUCE_TOOLTIPCLIENT_JUCEHEADER__
  41588. #endif
  41589. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41590. /*** Start of inlined file: juce_BooleanPropertyComponent.h ***/
  41591. #ifndef __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41592. #define __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41593. /**
  41594. A PropertyComponent that contains an on/off toggle button.
  41595. This type of property component can be used if you have a boolean value to
  41596. toggle on/off.
  41597. @see PropertyComponent
  41598. */
  41599. class JUCE_API BooleanPropertyComponent : public PropertyComponent,
  41600. private ButtonListener
  41601. {
  41602. protected:
  41603. /** Creates a button component.
  41604. If you use this constructor, you must override the getState() and setState()
  41605. methods.
  41606. @param propertyName the property name to be passed to the PropertyComponent
  41607. @param buttonTextWhenTrue the text shown in the button when the value is true
  41608. @param buttonTextWhenFalse the text shown in the button when the value is false
  41609. */
  41610. BooleanPropertyComponent (const String& propertyName,
  41611. const String& buttonTextWhenTrue,
  41612. const String& buttonTextWhenFalse);
  41613. public:
  41614. /** Creates a button component.
  41615. @param valueToControl a Value object that this property should refer to.
  41616. @param propertyName the property name to be passed to the PropertyComponent
  41617. @param buttonText the text shown in the ToggleButton component
  41618. */
  41619. BooleanPropertyComponent (const Value& valueToControl,
  41620. const String& propertyName,
  41621. const String& buttonText);
  41622. /** Destructor. */
  41623. ~BooleanPropertyComponent();
  41624. /** Called to change the state of the boolean value. */
  41625. virtual void setState (bool newState);
  41626. /** Must return the current value of the property. */
  41627. virtual bool getState() const;
  41628. /** @internal */
  41629. void paint (Graphics& g);
  41630. /** @internal */
  41631. void refresh();
  41632. /** @internal */
  41633. void buttonClicked (Button*);
  41634. juce_UseDebuggingNewOperator
  41635. private:
  41636. ToggleButton button;
  41637. String onText, offText;
  41638. BooleanPropertyComponent (const BooleanPropertyComponent&);
  41639. BooleanPropertyComponent& operator= (const BooleanPropertyComponent&);
  41640. };
  41641. #endif // __JUCE_BOOLEANPROPERTYCOMPONENT_JUCEHEADER__
  41642. /*** End of inlined file: juce_BooleanPropertyComponent.h ***/
  41643. #endif
  41644. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41645. /*** Start of inlined file: juce_ButtonPropertyComponent.h ***/
  41646. #ifndef __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41647. #define __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41648. /**
  41649. A PropertyComponent that contains a button.
  41650. This type of property component can be used if you need a button to trigger some
  41651. kind of action.
  41652. @see PropertyComponent
  41653. */
  41654. class JUCE_API ButtonPropertyComponent : public PropertyComponent,
  41655. private ButtonListener
  41656. {
  41657. public:
  41658. /** Creates a button component.
  41659. @param propertyName the property name to be passed to the PropertyComponent
  41660. @param triggerOnMouseDown this is passed to the Button::setTriggeredOnMouseDown() method
  41661. */
  41662. ButtonPropertyComponent (const String& propertyName,
  41663. bool triggerOnMouseDown);
  41664. /** Destructor. */
  41665. ~ButtonPropertyComponent();
  41666. /** Called when the user clicks the button.
  41667. */
  41668. virtual void buttonClicked() = 0;
  41669. /** Returns the string that should be displayed in the button.
  41670. If you need to change this string, call refresh() to update the component.
  41671. */
  41672. virtual const String getButtonText() const = 0;
  41673. /** @internal */
  41674. void refresh();
  41675. /** @internal */
  41676. void buttonClicked (Button*);
  41677. juce_UseDebuggingNewOperator
  41678. private:
  41679. TextButton button;
  41680. ButtonPropertyComponent (const ButtonPropertyComponent&);
  41681. ButtonPropertyComponent& operator= (const ButtonPropertyComponent&);
  41682. };
  41683. #endif // __JUCE_BUTTONPROPERTYCOMPONENT_JUCEHEADER__
  41684. /*** End of inlined file: juce_ButtonPropertyComponent.h ***/
  41685. #endif
  41686. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41687. /*** Start of inlined file: juce_ChoicePropertyComponent.h ***/
  41688. #ifndef __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41689. #define __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41690. /**
  41691. A PropertyComponent that shows its value as a combo box.
  41692. This type of property component contains a list of options and has a
  41693. combo box to choose one.
  41694. Your subclass's constructor must add some strings to the choices StringArray
  41695. and these are shown in the list.
  41696. The getIndex() method will be called to find out which option is the currently
  41697. selected one. If you call refresh() it will call getIndex() to check whether
  41698. the value has changed, and will update the combo box if needed.
  41699. If the user selects a different item from the list, setIndex() will be
  41700. called to let your class process this.
  41701. @see PropertyComponent, PropertyPanel
  41702. */
  41703. class JUCE_API ChoicePropertyComponent : public PropertyComponent,
  41704. private ComboBoxListener
  41705. {
  41706. protected:
  41707. /** Creates the component.
  41708. Your subclass's constructor must add a list of options to the choices
  41709. member variable.
  41710. */
  41711. ChoicePropertyComponent (const String& propertyName);
  41712. public:
  41713. /** Creates the component.
  41714. @param valueToControl the value that the combo box will read and control
  41715. @param propertyName the name of the property
  41716. @param choices the list of possible values that the drop-down list will contain
  41717. @param correspondingValues a list of values corresponding to each item in the 'choices' StringArray.
  41718. These are the values that will be read and written to the
  41719. valueToControl value. This array must contain the same number of items
  41720. as the choices array
  41721. */
  41722. ChoicePropertyComponent (const Value& valueToControl,
  41723. const String& propertyName,
  41724. const StringArray& choices,
  41725. const Array <var>& correspondingValues);
  41726. /** Destructor. */
  41727. ~ChoicePropertyComponent();
  41728. /** Called when the user selects an item from the combo box.
  41729. Your subclass must use this callback to update the value that this component
  41730. represents. The index is the index of the chosen item in the choices
  41731. StringArray.
  41732. */
  41733. virtual void setIndex (int newIndex);
  41734. /** Returns the index of the item that should currently be shown.
  41735. This is the index of the item in the choices StringArray that will be
  41736. shown.
  41737. */
  41738. virtual int getIndex() const;
  41739. /** Returns the list of options. */
  41740. const StringArray& getChoices() const;
  41741. /** @internal */
  41742. void refresh();
  41743. /** @internal */
  41744. void comboBoxChanged (ComboBox*);
  41745. juce_UseDebuggingNewOperator
  41746. protected:
  41747. /** The list of options that will be shown in the combo box.
  41748. Your subclass must populate this array in its constructor. If any empty
  41749. strings are added, these will be replaced with horizontal separators (see
  41750. ComboBox::addSeparator() for more info).
  41751. */
  41752. StringArray choices;
  41753. private:
  41754. ComboBox comboBox;
  41755. bool isCustomClass;
  41756. class RemapperValueSource;
  41757. void createComboBox();
  41758. ChoicePropertyComponent (const ChoicePropertyComponent&);
  41759. ChoicePropertyComponent& operator= (const ChoicePropertyComponent&);
  41760. };
  41761. #endif // __JUCE_CHOICEPROPERTYCOMPONENT_JUCEHEADER__
  41762. /*** End of inlined file: juce_ChoicePropertyComponent.h ***/
  41763. #endif
  41764. #ifndef __JUCE_PROPERTYCOMPONENT_JUCEHEADER__
  41765. #endif
  41766. #ifndef __JUCE_PROPERTYPANEL_JUCEHEADER__
  41767. #endif
  41768. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41769. /*** Start of inlined file: juce_SliderPropertyComponent.h ***/
  41770. #ifndef __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41771. #define __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41772. /**
  41773. A PropertyComponent that shows its value as a slider.
  41774. @see PropertyComponent, Slider
  41775. */
  41776. class JUCE_API SliderPropertyComponent : public PropertyComponent,
  41777. private SliderListener
  41778. {
  41779. protected:
  41780. /** Creates the property component.
  41781. The ranges, interval and skew factor are passed to the Slider component.
  41782. If you need to customise the slider in other ways, your constructor can
  41783. access the slider member variable and change it directly.
  41784. */
  41785. SliderPropertyComponent (const String& propertyName,
  41786. double rangeMin,
  41787. double rangeMax,
  41788. double interval,
  41789. double skewFactor = 1.0);
  41790. public:
  41791. /** Creates the property component.
  41792. The ranges, interval and skew factor are passed to the Slider component.
  41793. If you need to customise the slider in other ways, your constructor can
  41794. access the slider member variable and change it directly.
  41795. */
  41796. SliderPropertyComponent (const Value& valueToControl,
  41797. const String& propertyName,
  41798. double rangeMin,
  41799. double rangeMax,
  41800. double interval,
  41801. double skewFactor = 1.0);
  41802. /** Destructor. */
  41803. ~SliderPropertyComponent();
  41804. /** Called when the user moves the slider to change its value.
  41805. Your subclass must use this method to update whatever item this property
  41806. represents.
  41807. */
  41808. virtual void setValue (double newValue);
  41809. /** Returns the value that the slider should show. */
  41810. virtual double getValue() const;
  41811. /** @internal */
  41812. void refresh();
  41813. /** @internal */
  41814. void changeListenerCallback (void*);
  41815. /** @internal */
  41816. void sliderValueChanged (Slider*);
  41817. juce_UseDebuggingNewOperator
  41818. protected:
  41819. /** The slider component being used in this component.
  41820. Your subclass has access to this in case it needs to customise it in some way.
  41821. */
  41822. Slider slider;
  41823. SliderPropertyComponent (const SliderPropertyComponent&);
  41824. SliderPropertyComponent& operator= (const SliderPropertyComponent&);
  41825. };
  41826. #endif // __JUCE_SLIDERPROPERTYCOMPONENT_JUCEHEADER__
  41827. /*** End of inlined file: juce_SliderPropertyComponent.h ***/
  41828. #endif
  41829. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41830. /*** Start of inlined file: juce_TextPropertyComponent.h ***/
  41831. #ifndef __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41832. #define __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41833. /**
  41834. A PropertyComponent that shows its value as editable text.
  41835. @see PropertyComponent
  41836. */
  41837. class JUCE_API TextPropertyComponent : public PropertyComponent
  41838. {
  41839. protected:
  41840. /** Creates a text property component.
  41841. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41842. sets whether the text editor allows carriage returns.
  41843. @see TextEditor
  41844. */
  41845. TextPropertyComponent (const String& propertyName,
  41846. int maxNumChars,
  41847. bool isMultiLine);
  41848. public:
  41849. /** Creates a text property component.
  41850. The maxNumChars is used to set the length of string allowable, and isMultiLine
  41851. sets whether the text editor allows carriage returns.
  41852. @see TextEditor
  41853. */
  41854. TextPropertyComponent (const Value& valueToControl,
  41855. const String& propertyName,
  41856. int maxNumChars,
  41857. bool isMultiLine);
  41858. /** Destructor. */
  41859. ~TextPropertyComponent();
  41860. /** Called when the user edits the text.
  41861. Your subclass must use this callback to change the value of whatever item
  41862. this property component represents.
  41863. */
  41864. virtual void setText (const String& newText);
  41865. /** Returns the text that should be shown in the text editor.
  41866. */
  41867. virtual const String getText() const;
  41868. /** @internal */
  41869. void refresh();
  41870. /** @internal */
  41871. void textWasEdited();
  41872. juce_UseDebuggingNewOperator
  41873. private:
  41874. Label* textEditor;
  41875. void createEditor (int maxNumChars, bool isMultiLine);
  41876. TextPropertyComponent (const TextPropertyComponent&);
  41877. TextPropertyComponent& operator= (const TextPropertyComponent&);
  41878. };
  41879. #endif // __JUCE_TEXTPROPERTYCOMPONENT_JUCEHEADER__
  41880. /*** End of inlined file: juce_TextPropertyComponent.h ***/
  41881. #endif
  41882. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41883. /*** Start of inlined file: juce_ActiveXControlComponent.h ***/
  41884. #ifndef __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41885. #define __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41886. #if JUCE_WINDOWS || DOXYGEN
  41887. /**
  41888. A Windows-specific class that can create and embed an ActiveX control inside
  41889. itself.
  41890. To use it, create one of these, put it in place and make sure it's visible in a
  41891. window, then use createControl() to instantiate an ActiveX control. The control
  41892. will then be moved and resized to follow the movements of this component.
  41893. Of course, since the control is a heavyweight window, it'll obliterate any
  41894. juce components that may overlap this component, but that's life.
  41895. */
  41896. class JUCE_API ActiveXControlComponent : public Component
  41897. {
  41898. public:
  41899. /** Create an initially-empty container. */
  41900. ActiveXControlComponent();
  41901. /** Destructor. */
  41902. ~ActiveXControlComponent();
  41903. /** Tries to create an ActiveX control and embed it in this peer.
  41904. The peer controlIID is a pointer to an IID structure - it's treated
  41905. as a void* because when including the Juce headers, you might not always
  41906. have included windows.h first, in which case IID wouldn't be defined.
  41907. e.g. @code
  41908. const IID myIID = __uuidof (QTControl);
  41909. myControlComp->createControl (&myIID);
  41910. @endcode
  41911. */
  41912. bool createControl (const void* controlIID);
  41913. /** Deletes the ActiveX control, if one has been created.
  41914. */
  41915. void deleteControl();
  41916. /** Returns true if a control is currently in use. */
  41917. bool isControlOpen() const throw() { return control != 0; }
  41918. /** Does a QueryInterface call on the embedded control object.
  41919. This allows you to cast the control to whatever type of COM object you need.
  41920. The iid parameter is a pointer to an IID structure - it's treated
  41921. as a void* because when including the Juce headers, you might not always
  41922. have included windows.h first, in which case IID wouldn't be defined, but
  41923. you should just pass a pointer to an IID.
  41924. e.g. @code
  41925. const IID iid = __uuidof (IOleWindow);
  41926. IOleWindow* oleWindow = (IOleWindow*) myControlComp->queryInterface (&iid);
  41927. if (oleWindow != 0)
  41928. {
  41929. HWND hwnd;
  41930. oleWindow->GetWindow (&hwnd);
  41931. ...
  41932. oleWindow->Release();
  41933. }
  41934. @endcode
  41935. */
  41936. void* queryInterface (const void* iid) const;
  41937. /** Set this to false to stop mouse events being allowed through to the control.
  41938. */
  41939. void setMouseEventsAllowed (bool eventsCanReachControl);
  41940. /** Returns true if mouse events are allowed to get through to the control.
  41941. */
  41942. bool areMouseEventsAllowed() const throw() { return mouseEventsAllowed; }
  41943. /** @internal */
  41944. void paint (Graphics& g);
  41945. /** @internal */
  41946. void* originalWndProc;
  41947. juce_UseDebuggingNewOperator
  41948. private:
  41949. class Pimpl;
  41950. friend class Pimpl;
  41951. friend class ScopedPointer <Pimpl>;
  41952. ScopedPointer <Pimpl> control;
  41953. bool mouseEventsAllowed;
  41954. void setControlBounds (const Rectangle<int>& bounds) const;
  41955. void setControlVisible (bool b) const;
  41956. ActiveXControlComponent (const ActiveXControlComponent&);
  41957. ActiveXControlComponent& operator= (const ActiveXControlComponent&);
  41958. };
  41959. #endif
  41960. #endif // __JUCE_ACTIVEXCONTROLCOMPONENT_JUCEHEADER__
  41961. /*** End of inlined file: juce_ActiveXControlComponent.h ***/
  41962. #endif
  41963. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41964. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  41965. #ifndef __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41966. #define __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  41967. /**
  41968. A component containing controls to let the user change the audio settings of
  41969. an AudioDeviceManager object.
  41970. Very easy to use - just create one of these and show it to the user.
  41971. @see AudioDeviceManager
  41972. */
  41973. class JUCE_API AudioDeviceSelectorComponent : public Component,
  41974. public ComboBoxListener,
  41975. public ButtonListener,
  41976. public ChangeListener
  41977. {
  41978. public:
  41979. /** Creates the component.
  41980. If your app needs only output channels, you might ask for a maximum of 0 input
  41981. channels, and the component won't display any options for choosing the input
  41982. channels. And likewise if you're doing an input-only app.
  41983. @param deviceManager the device manager that this component should control
  41984. @param minAudioInputChannels the minimum number of audio input channels that the application needs
  41985. @param maxAudioInputChannels the maximum number of audio input channels that the application needs
  41986. @param minAudioOutputChannels the minimum number of audio output channels that the application needs
  41987. @param maxAudioOutputChannels the maximum number of audio output channels that the application needs
  41988. @param showMidiInputOptions if true, the component will allow the user to select which midi inputs are enabled
  41989. @param showMidiOutputSelector if true, the component will let the user choose a default midi output device
  41990. @param showChannelsAsStereoPairs if true, channels will be treated as pairs; if false, channels will be
  41991. treated as a set of separate mono channels.
  41992. @param hideAdvancedOptionsWithButton if true, only the minimum amount of UI components
  41993. are shown, with an "advanced" button that shows the rest of them
  41994. */
  41995. AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager,
  41996. const int minAudioInputChannels,
  41997. const int maxAudioInputChannels,
  41998. const int minAudioOutputChannels,
  41999. const int maxAudioOutputChannels,
  42000. const bool showMidiInputOptions,
  42001. const bool showMidiOutputSelector,
  42002. const bool showChannelsAsStereoPairs,
  42003. const bool hideAdvancedOptionsWithButton);
  42004. /** Destructor */
  42005. ~AudioDeviceSelectorComponent();
  42006. /** @internal */
  42007. void resized();
  42008. /** @internal */
  42009. void comboBoxChanged (ComboBox*);
  42010. /** @internal */
  42011. void buttonClicked (Button*);
  42012. /** @internal */
  42013. void changeListenerCallback (void*);
  42014. /** @internal */
  42015. void childBoundsChanged (Component*);
  42016. juce_UseDebuggingNewOperator
  42017. private:
  42018. AudioDeviceManager& deviceManager;
  42019. ScopedPointer<ComboBox> deviceTypeDropDown;
  42020. ScopedPointer<Label> deviceTypeDropDownLabel;
  42021. ScopedPointer<Component> audioDeviceSettingsComp;
  42022. String audioDeviceSettingsCompType;
  42023. const int minOutputChannels, maxOutputChannels, minInputChannels, maxInputChannels;
  42024. const bool showChannelsAsStereoPairs;
  42025. const bool hideAdvancedOptionsWithButton;
  42026. class MidiInputSelectorComponentListBox;
  42027. friend class ScopedPointer<MidiInputSelectorComponentListBox>;
  42028. ScopedPointer<MidiInputSelectorComponentListBox> midiInputsList;
  42029. ScopedPointer<ComboBox> midiOutputSelector;
  42030. ScopedPointer<Label> midiInputsLabel, midiOutputLabel;
  42031. AudioDeviceSelectorComponent (const AudioDeviceSelectorComponent&);
  42032. AudioDeviceSelectorComponent& operator= (const AudioDeviceSelectorComponent&);
  42033. };
  42034. #endif // __JUCE_AUDIODEVICESELECTORCOMPONENT_JUCEHEADER__
  42035. /*** End of inlined file: juce_AudioDeviceSelectorComponent.h ***/
  42036. #endif
  42037. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42038. /*** Start of inlined file: juce_BubbleComponent.h ***/
  42039. #ifndef __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42040. #define __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42041. /**
  42042. A component for showing a message or other graphics inside a speech-bubble-shaped
  42043. outline, pointing at a location on the screen.
  42044. This is a base class that just draws and positions the bubble shape, but leaves
  42045. the drawing of any content up to a subclass. See BubbleMessageComponent for a subclass
  42046. that draws a text message.
  42047. To use it, create your subclass, then either add it to a parent component or
  42048. put it on the desktop with addToDesktop (0), use setPosition() to
  42049. resize and position it, then make it visible.
  42050. @see BubbleMessageComponent
  42051. */
  42052. class JUCE_API BubbleComponent : public Component
  42053. {
  42054. protected:
  42055. /** Creates a BubbleComponent.
  42056. Your subclass will need to implement the getContentSize() and paintContent()
  42057. methods to draw the bubble's contents.
  42058. */
  42059. BubbleComponent();
  42060. public:
  42061. /** Destructor. */
  42062. ~BubbleComponent();
  42063. /** A list of permitted placements for the bubble, relative to the co-ordinates
  42064. at which it should be pointing.
  42065. @see setAllowedPlacement
  42066. */
  42067. enum BubblePlacement
  42068. {
  42069. above = 1,
  42070. below = 2,
  42071. left = 4,
  42072. right = 8
  42073. };
  42074. /** Tells the bubble which positions it's allowed to put itself in, relative to the
  42075. point at which it's pointing.
  42076. By default when setPosition() is called, the bubble will place itself either
  42077. above, below, left, or right of the target area. You can pass in a bitwise-'or' of
  42078. the values in BubblePlacement to restrict this choice.
  42079. E.g. if you only want your bubble to appear above or below the target area,
  42080. use setAllowedPlacement (above | below);
  42081. @see BubblePlacement
  42082. */
  42083. void setAllowedPlacement (int newPlacement);
  42084. /** Moves and resizes the bubble to point at a given component.
  42085. This will resize the bubble to fit its content, then find a position for it
  42086. so that it's next to, but doesn't overlap the given component.
  42087. It'll put itself either above, below, or to the side of the component depending
  42088. on where there's the most space, honouring any restrictions that were set
  42089. with setAllowedPlacement().
  42090. */
  42091. void setPosition (Component* componentToPointTo);
  42092. /** Moves and resizes the bubble to point at a given point.
  42093. This will resize the bubble to fit its content, then position it
  42094. so that the tip of the bubble points to the given co-ordinate. The co-ordinates
  42095. are relative to either the bubble component's parent component if it has one, or
  42096. they are screen co-ordinates if not.
  42097. It'll put itself either above, below, or to the side of this point, depending
  42098. on where there's the most space, honouring any restrictions that were set
  42099. with setAllowedPlacement().
  42100. */
  42101. void setPosition (int arrowTipX,
  42102. int arrowTipY);
  42103. /** Moves and resizes the bubble to point at a given rectangle.
  42104. This will resize the bubble to fit its content, then find a position for it
  42105. so that it's next to, but doesn't overlap the given rectangle. The rectangle's
  42106. co-ordinates are relative to either the bubble component's parent component
  42107. if it has one, or they are screen co-ordinates if not.
  42108. It'll put itself either above, below, or to the side of the component depending
  42109. on where there's the most space, honouring any restrictions that were set
  42110. with setAllowedPlacement().
  42111. */
  42112. void setPosition (const Rectangle<int>& rectangleToPointTo);
  42113. protected:
  42114. /** Subclasses should override this to return the size of the content they
  42115. want to draw inside the bubble.
  42116. */
  42117. virtual void getContentSize (int& width, int& height) = 0;
  42118. /** Subclasses should override this to draw their bubble's contents.
  42119. The graphics object's clip region and the dimensions passed in here are
  42120. set up to paint just the rectangle inside the bubble.
  42121. */
  42122. virtual void paintContent (Graphics& g, int width, int height) = 0;
  42123. public:
  42124. /** @internal */
  42125. void paint (Graphics& g);
  42126. juce_UseDebuggingNewOperator
  42127. private:
  42128. Rectangle<int> content;
  42129. int side, allowablePlacements;
  42130. float arrowTipX, arrowTipY;
  42131. DropShadowEffect shadow;
  42132. BubbleComponent (const BubbleComponent&);
  42133. BubbleComponent& operator= (const BubbleComponent&);
  42134. };
  42135. #endif // __JUCE_BUBBLECOMPONENT_JUCEHEADER__
  42136. /*** End of inlined file: juce_BubbleComponent.h ***/
  42137. #endif
  42138. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42139. /*** Start of inlined file: juce_BubbleMessageComponent.h ***/
  42140. #ifndef __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42141. #define __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42142. /**
  42143. A speech-bubble component that displays a short message.
  42144. This can be used to show a message with the tail of the speech bubble
  42145. pointing to a particular component or location on the screen.
  42146. @see BubbleComponent
  42147. */
  42148. class JUCE_API BubbleMessageComponent : public BubbleComponent,
  42149. private Timer
  42150. {
  42151. public:
  42152. /** Creates a bubble component.
  42153. After creating one a BubbleComponent, do the following:
  42154. - add it to an appropriate parent component, or put it on the
  42155. desktop with Component::addToDesktop (0).
  42156. - use the showAt() method to show a message.
  42157. - it will make itself invisible after it times-out (and can optionally
  42158. also delete itself), or you can reuse it somewhere else by calling
  42159. showAt() again.
  42160. */
  42161. BubbleMessageComponent (int fadeOutLengthMs = 150);
  42162. /** Destructor. */
  42163. ~BubbleMessageComponent();
  42164. /** Shows a message bubble at a particular position.
  42165. This shows the bubble with its stem pointing to the given location
  42166. (co-ordinates being relative to its parent component).
  42167. For details about exactly how it decides where to position itself, see
  42168. BubbleComponent::updatePosition().
  42169. @param x the x co-ordinate of end of the bubble's tail
  42170. @param y the y co-ordinate of end of the bubble's tail
  42171. @param message the text to display
  42172. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  42173. from its parent compnent. If this is 0 or less, it
  42174. will stay there until manually removed.
  42175. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  42176. mouse button is pressed (anywhere on the screen)
  42177. @param deleteSelfAfterUse if true, then the component will delete itself after
  42178. it becomes invisible
  42179. */
  42180. void showAt (int x, int y,
  42181. const String& message,
  42182. int numMillisecondsBeforeRemoving,
  42183. bool removeWhenMouseClicked = true,
  42184. bool deleteSelfAfterUse = false);
  42185. /** Shows a message bubble next to a particular component.
  42186. This shows the bubble with its stem pointing at the given component.
  42187. For details about exactly how it decides where to position itself, see
  42188. BubbleComponent::updatePosition().
  42189. @param component the component that you want to point at
  42190. @param message the text to display
  42191. @param numMillisecondsBeforeRemoving how long to leave it on the screen before removing itself
  42192. from its parent compnent. If this is 0 or less, it
  42193. will stay there until manually removed.
  42194. @param removeWhenMouseClicked if this is true, the bubble will disappear as soon as a
  42195. mouse button is pressed (anywhere on the screen)
  42196. @param deleteSelfAfterUse if true, then the component will delete itself after
  42197. it becomes invisible
  42198. */
  42199. void showAt (Component* component,
  42200. const String& message,
  42201. int numMillisecondsBeforeRemoving,
  42202. bool removeWhenMouseClicked = true,
  42203. bool deleteSelfAfterUse = false);
  42204. /** @internal */
  42205. void getContentSize (int& w, int& h);
  42206. /** @internal */
  42207. void paintContent (Graphics& g, int w, int h);
  42208. /** @internal */
  42209. void timerCallback();
  42210. juce_UseDebuggingNewOperator
  42211. private:
  42212. int fadeOutLength, mouseClickCounter;
  42213. TextLayout textLayout;
  42214. int64 expiryTime;
  42215. bool deleteAfterUse;
  42216. void init (int numMillisecondsBeforeRemoving,
  42217. bool removeWhenMouseClicked,
  42218. bool deleteSelfAfterUse);
  42219. BubbleMessageComponent (const BubbleMessageComponent&);
  42220. BubbleMessageComponent& operator= (const BubbleMessageComponent&);
  42221. };
  42222. #endif // __JUCE_BUBBLEMESSAGECOMPONENT_JUCEHEADER__
  42223. /*** End of inlined file: juce_BubbleMessageComponent.h ***/
  42224. #endif
  42225. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  42226. /*** Start of inlined file: juce_ColourSelector.h ***/
  42227. #ifndef __JUCE_COLOURSELECTOR_JUCEHEADER__
  42228. #define __JUCE_COLOURSELECTOR_JUCEHEADER__
  42229. /**
  42230. A component that lets the user choose a colour.
  42231. This shows RGB sliders and a colourspace that the user can pick colours from.
  42232. This class is also a ChangeBroadcaster, so listeners can register to be told
  42233. when the colour changes.
  42234. */
  42235. class JUCE_API ColourSelector : public Component,
  42236. public ChangeBroadcaster,
  42237. protected SliderListener
  42238. {
  42239. public:
  42240. /** Options for the type of selector to show. These are passed into the constructor. */
  42241. enum ColourSelectorOptions
  42242. {
  42243. showAlphaChannel = 1 << 0, /**< if set, the colour's alpha channel can be changed as well as its RGB. */
  42244. showColourAtTop = 1 << 1, /**< if set, a swatch of the colour is shown at the top of the component. */
  42245. showSliders = 1 << 2, /**< if set, RGB sliders are shown at the bottom of the component. */
  42246. showColourspace = 1 << 3 /**< if set, a big HSV selector is shown. */
  42247. };
  42248. /** Creates a ColourSelector object.
  42249. The flags are a combination of values from the ColourSelectorOptions enum, specifying
  42250. which of the selector's features should be visible.
  42251. The edgeGap value specifies the amount of space to leave around the edge.
  42252. gapAroundColourSpaceComponent indicates how much of a gap to put around the
  42253. colourspace and hue selector components.
  42254. */
  42255. ColourSelector (int sectionsToShow = (showAlphaChannel | showColourAtTop | showSliders | showColourspace),
  42256. int edgeGap = 4,
  42257. int gapAroundColourSpaceComponent = 7);
  42258. /** Destructor. */
  42259. ~ColourSelector();
  42260. /** Returns the colour that the user has currently selected.
  42261. The ColourSelector class is also a ChangeBroadcaster, so listeners can
  42262. register to be told when the colour changes.
  42263. @see setCurrentColour
  42264. */
  42265. const Colour getCurrentColour() const;
  42266. /** Changes the colour that is currently being shown.
  42267. */
  42268. void setCurrentColour (const Colour& newColour);
  42269. /** Tells the selector how many preset colour swatches you want to have on the component.
  42270. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42271. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42272. their values.
  42273. */
  42274. virtual int getNumSwatches() const;
  42275. /** Called by the selector to find out the colour of one of the swatches.
  42276. Your subclass should return the colour of the swatch with the given index.
  42277. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42278. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42279. their values.
  42280. */
  42281. virtual const Colour getSwatchColour (int index) const;
  42282. /** Called by the selector when the user puts a new colour into one of the swatches.
  42283. Your subclass should change the colour of the swatch with the given index.
  42284. To enable swatches, you'll need to override getNumSwatches(), getSwatchColour(), and
  42285. setSwatchColour(), to return the number of colours you want, and to set and retrieve
  42286. their values.
  42287. */
  42288. virtual void setSwatchColour (int index, const Colour& newColour) const;
  42289. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  42290. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42291. methods.
  42292. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42293. */
  42294. enum ColourIds
  42295. {
  42296. backgroundColourId = 0x1007000, /**< the colour used to fill the component's background. */
  42297. labelTextColourId = 0x1007001 /**< the colour used for the labels next to the sliders. */
  42298. };
  42299. juce_UseDebuggingNewOperator
  42300. private:
  42301. class ColourSpaceView;
  42302. class HueSelectorComp;
  42303. class SwatchComponent;
  42304. friend class ColourSpaceView;
  42305. friend class HueSelectorComp;
  42306. Colour colour;
  42307. float h, s, v;
  42308. Slider* sliders[4];
  42309. ColourSpaceView* colourSpace;
  42310. HueSelectorComp* hueSelector;
  42311. OwnedArray <SwatchComponent> swatchComponents;
  42312. const int flags;
  42313. int edgeGap;
  42314. Rectangle<int> previewArea;
  42315. void setHue (float newH);
  42316. void setSV (float newS, float newV);
  42317. void updateHSV();
  42318. void update();
  42319. void sliderValueChanged (Slider*);
  42320. void paint (Graphics& g);
  42321. void resized();
  42322. ColourSelector (const ColourSelector&);
  42323. ColourSelector& operator= (const ColourSelector&);
  42324. // this constructor is here temporarily to prevent old code compiling, because the parameters
  42325. // have changed - if you get an error here, update your code to use the new constructor instead..
  42326. // (xxx - note to self: remember to remove this at some point in the future)
  42327. ColourSelector (bool);
  42328. };
  42329. #endif // __JUCE_COLOURSELECTOR_JUCEHEADER__
  42330. /*** End of inlined file: juce_ColourSelector.h ***/
  42331. #endif
  42332. #ifndef __JUCE_DROPSHADOWER_JUCEHEADER__
  42333. #endif
  42334. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42335. /*** Start of inlined file: juce_MagnifierComponent.h ***/
  42336. #ifndef __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42337. #define __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42338. /**
  42339. A component that contains another component, and can magnify or shrink it.
  42340. This component will continually update its size so that it fits the zoomed
  42341. version of the content component that you put inside it, so don't try to
  42342. change the size of this component directly - instead change that of the
  42343. content component.
  42344. To make it all work, the magnifier uses extremely cunning ComponentPeer tricks
  42345. to remap mouse events correctly. This means that the content component won't
  42346. appear to be a direct child of this component, and instead will think its
  42347. on the desktop.
  42348. */
  42349. class JUCE_API MagnifierComponent : public Component
  42350. {
  42351. public:
  42352. /** Creates a MagnifierComponent.
  42353. This component will continually update its size so that it fits the zoomed
  42354. version of the content component that you put inside it, so don't try to
  42355. change the size of this component directly - instead change that of the
  42356. content component.
  42357. @param contentComponent the component to add as the magnified one
  42358. @param deleteContentCompWhenNoLongerNeeded if true, the content component will
  42359. be deleted when this component is deleted. If false,
  42360. it's the caller's responsibility to delete it later.
  42361. */
  42362. MagnifierComponent (Component* contentComponent,
  42363. bool deleteContentCompWhenNoLongerNeeded);
  42364. /** Destructor. */
  42365. ~MagnifierComponent();
  42366. /** Returns the current content component. */
  42367. Component* getContentComponent() const { return content; }
  42368. /** Changes the zoom level.
  42369. The scale factor must be greater than zero. Values less than 1 will shrink the
  42370. image; values greater than 1 will multiply its size by this amount.
  42371. When this is called, this component will change its size to fit the full extent
  42372. of the newly zoomed content.
  42373. */
  42374. void setScaleFactor (double newScaleFactor);
  42375. /** Returns the current zoom factor. */
  42376. double getScaleFactor() const { return scaleFactor; }
  42377. /** Changes the quality setting used to rescale the graphics.
  42378. */
  42379. void setResamplingQuality (Graphics::ResamplingQuality newQuality);
  42380. juce_UseDebuggingNewOperator
  42381. /** @internal */
  42382. void childBoundsChanged (Component*);
  42383. private:
  42384. Component* content;
  42385. Component* holderComp;
  42386. double scaleFactor;
  42387. ComponentPeer* peer;
  42388. bool deleteContent;
  42389. Graphics::ResamplingQuality quality;
  42390. MouseInputSource mouseSource;
  42391. void paint (Graphics& g);
  42392. void mouseDown (const MouseEvent& e);
  42393. void mouseUp (const MouseEvent& e);
  42394. void mouseDrag (const MouseEvent& e);
  42395. void mouseMove (const MouseEvent& e);
  42396. void mouseEnter (const MouseEvent& e);
  42397. void mouseExit (const MouseEvent& e);
  42398. void mouseWheelMove (const MouseEvent& e, float, float);
  42399. void passOnMouseEventToPeer (const MouseEvent& e);
  42400. int scaleInt (int n) const;
  42401. MagnifierComponent (const MagnifierComponent&);
  42402. MagnifierComponent& operator= (const MagnifierComponent&);
  42403. };
  42404. #endif // __JUCE_MAGNIFIERCOMPONENT_JUCEHEADER__
  42405. /*** End of inlined file: juce_MagnifierComponent.h ***/
  42406. #endif
  42407. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42408. /*** Start of inlined file: juce_MidiKeyboardComponent.h ***/
  42409. #ifndef __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42410. #define __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42411. /**
  42412. A component that displays a piano keyboard, whose notes can be clicked on.
  42413. This component will mimic a physical midi keyboard, showing the current state of
  42414. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  42415. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  42416. Another feature is that the computer keyboard can also be used to play notes. By
  42417. default it maps the top two rows of a standard querty keyboard to the notes, but
  42418. these can be remapped if needed. It will only respond to keypresses when it has
  42419. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  42420. The component is also a ChangeBroadcaster, so if you want to be informed when the
  42421. keyboard is scrolled, you can register a ChangeListener for callbacks.
  42422. @see MidiKeyboardState
  42423. */
  42424. class JUCE_API MidiKeyboardComponent : public Component,
  42425. public MidiKeyboardStateListener,
  42426. public ChangeBroadcaster,
  42427. private Timer,
  42428. private AsyncUpdater
  42429. {
  42430. public:
  42431. /** The direction of the keyboard.
  42432. @see setOrientation
  42433. */
  42434. enum Orientation
  42435. {
  42436. horizontalKeyboard,
  42437. verticalKeyboardFacingLeft,
  42438. verticalKeyboardFacingRight,
  42439. };
  42440. /** Creates a MidiKeyboardComponent.
  42441. @param state the midi keyboard model that this component will represent
  42442. @param orientation whether the keyboard is horizonal or vertical
  42443. */
  42444. MidiKeyboardComponent (MidiKeyboardState& state,
  42445. Orientation orientation);
  42446. /** Destructor. */
  42447. ~MidiKeyboardComponent();
  42448. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  42449. on the component.
  42450. Values are 0 to 1.0, where 1.0 is the heaviest.
  42451. @see setMidiChannel
  42452. */
  42453. void setVelocity (float velocity, bool useMousePositionForVelocity);
  42454. /** Changes the midi channel number that will be used for events triggered by clicking
  42455. on the component.
  42456. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  42457. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  42458. Although this is the channel used for outgoing events, the component can display
  42459. incoming events from more than one channel - see setMidiChannelsToDisplay()
  42460. @see setVelocity
  42461. */
  42462. void setMidiChannel (int midiChannelNumber);
  42463. /** Returns the midi channel that the keyboard is using for midi messages.
  42464. @see setMidiChannel
  42465. */
  42466. int getMidiChannel() const throw() { return midiChannel; }
  42467. /** Sets a mask to indicate which incoming midi channels should be represented by
  42468. key movements.
  42469. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  42470. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  42471. in this mask, the on-screen keys will also go down.
  42472. By default, this mask is set to 0xffff (all channels displayed).
  42473. @see setMidiChannel
  42474. */
  42475. void setMidiChannelsToDisplay (int midiChannelMask);
  42476. /** Returns the current set of midi channels represented by the component.
  42477. This is the value that was set with setMidiChannelsToDisplay().
  42478. */
  42479. int getMidiChannelsToDisplay() const throw() { return midiInChannelMask; }
  42480. /** Changes the width used to draw the white keys. */
  42481. void setKeyWidth (float widthInPixels);
  42482. /** Returns the width that was set by setKeyWidth(). */
  42483. float getKeyWidth() const throw() { return keyWidth; }
  42484. /** Changes the keyboard's current direction. */
  42485. void setOrientation (Orientation newOrientation);
  42486. /** Returns the keyboard's current direction. */
  42487. const Orientation getOrientation() const throw() { return orientation; }
  42488. /** Sets the range of midi notes that the keyboard will be limited to.
  42489. By default the range is 0 to 127 (inclusive), but you can limit this if you
  42490. only want a restricted set of the keys to be shown.
  42491. Note that the values here are inclusive and must be between 0 and 127.
  42492. */
  42493. void setAvailableRange (int lowestNote,
  42494. int highestNote);
  42495. /** Returns the first note in the available range.
  42496. @see setAvailableRange
  42497. */
  42498. int getRangeStart() const throw() { return rangeStart; }
  42499. /** Returns the last note in the available range.
  42500. @see setAvailableRange
  42501. */
  42502. int getRangeEnd() const throw() { return rangeEnd; }
  42503. /** If the keyboard extends beyond the size of the component, this will scroll
  42504. it to show the given key at the start.
  42505. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  42506. base class to send a callback to any ChangeListeners that have been registered.
  42507. */
  42508. void setLowestVisibleKey (int noteNumber);
  42509. /** Returns the number of the first key shown in the component.
  42510. @see setLowestVisibleKey
  42511. */
  42512. int getLowestVisibleKey() const throw() { return firstKey; }
  42513. /** Returns the length of the black notes.
  42514. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  42515. */
  42516. int getBlackNoteLength() const throw() { return blackNoteLength; }
  42517. /** If set to true, then scroll buttons will appear at either end of the keyboard
  42518. if there are too many notes to fit them all in the component at once.
  42519. */
  42520. void setScrollButtonsVisible (bool canScroll);
  42521. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  42522. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  42523. methods.
  42524. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  42525. */
  42526. enum ColourIds
  42527. {
  42528. whiteNoteColourId = 0x1005000,
  42529. blackNoteColourId = 0x1005001,
  42530. keySeparatorLineColourId = 0x1005002,
  42531. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  42532. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  42533. textLabelColourId = 0x1005005,
  42534. upDownButtonBackgroundColourId = 0x1005006,
  42535. upDownButtonArrowColourId = 0x1005007
  42536. };
  42537. /** Returns the position within the component of the left-hand edge of a key.
  42538. Depending on the keyboard's orientation, this may be a horizontal or vertical
  42539. distance, in either direction.
  42540. */
  42541. int getKeyStartPosition (const int midiNoteNumber) const;
  42542. /** Deletes all key-mappings.
  42543. @see setKeyPressForNote
  42544. */
  42545. void clearKeyMappings();
  42546. /** Maps a key-press to a given note.
  42547. @param key the key that should trigger the note
  42548. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  42549. be. The actual midi note that gets played will be
  42550. this value + (12 * the current base octave). To change
  42551. the base octave, see setKeyPressBaseOctave()
  42552. */
  42553. void setKeyPressForNote (const KeyPress& key,
  42554. int midiNoteOffsetFromC);
  42555. /** Removes any key-mappings for a given note.
  42556. For a description of what the note number means, see setKeyPressForNote().
  42557. */
  42558. void removeKeyPressForNote (int midiNoteOffsetFromC);
  42559. /** Changes the base note above which key-press-triggered notes are played.
  42560. The set of key-mappings that trigger notes can be moved up and down to cover
  42561. the entire scale using this method.
  42562. The value passed in is an octave number between 0 and 10 (inclusive), and
  42563. indicates which C is the base note to which the key-mapped notes are
  42564. relative.
  42565. */
  42566. void setKeyPressBaseOctave (int newOctaveNumber);
  42567. /** This sets the octave number which is shown as the octave number for middle C.
  42568. This affects only the default implementation of getWhiteNoteText(), which
  42569. passes this octave number to MidiMessage::getMidiNoteName() in order to
  42570. get the note text. See MidiMessage::getMidiNoteName() for more info about
  42571. the parameter.
  42572. By default this value is set to 3.
  42573. @see getOctaveForMiddleC
  42574. */
  42575. void setOctaveForMiddleC (int octaveNumForMiddleC);
  42576. /** This returns the value set by setOctaveForMiddleC().
  42577. @see setOctaveForMiddleC
  42578. */
  42579. int getOctaveForMiddleC() const throw() { return octaveNumForMiddleC; }
  42580. /** @internal */
  42581. void paint (Graphics& g);
  42582. /** @internal */
  42583. void resized();
  42584. /** @internal */
  42585. void mouseMove (const MouseEvent& e);
  42586. /** @internal */
  42587. void mouseDrag (const MouseEvent& e);
  42588. /** @internal */
  42589. void mouseDown (const MouseEvent& e);
  42590. /** @internal */
  42591. void mouseUp (const MouseEvent& e);
  42592. /** @internal */
  42593. void mouseEnter (const MouseEvent& e);
  42594. /** @internal */
  42595. void mouseExit (const MouseEvent& e);
  42596. /** @internal */
  42597. void mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY);
  42598. /** @internal */
  42599. void timerCallback();
  42600. /** @internal */
  42601. bool keyStateChanged (bool isKeyDown);
  42602. /** @internal */
  42603. void focusLost (FocusChangeType cause);
  42604. /** @internal */
  42605. void handleNoteOn (MidiKeyboardState* source, int midiChannel, int midiNoteNumber, float velocity);
  42606. /** @internal */
  42607. void handleNoteOff (MidiKeyboardState* source, int midiChannel, int midiNoteNumber);
  42608. /** @internal */
  42609. void handleAsyncUpdate();
  42610. /** @internal */
  42611. void colourChanged();
  42612. juce_UseDebuggingNewOperator
  42613. protected:
  42614. friend class MidiKeyboardUpDownButton;
  42615. /** Draws a white note in the given rectangle.
  42616. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42617. currently pressed down.
  42618. When doing this, be sure to note the keyboard's orientation.
  42619. */
  42620. virtual void drawWhiteNote (int midiNoteNumber,
  42621. Graphics& g,
  42622. int x, int y, int w, int h,
  42623. bool isDown, bool isOver,
  42624. const Colour& lineColour,
  42625. const Colour& textColour);
  42626. /** Draws a black note in the given rectangle.
  42627. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  42628. currently pressed down.
  42629. When doing this, be sure to note the keyboard's orientation.
  42630. */
  42631. virtual void drawBlackNote (int midiNoteNumber,
  42632. Graphics& g,
  42633. int x, int y, int w, int h,
  42634. bool isDown, bool isOver,
  42635. const Colour& noteFillColour);
  42636. /** Allows text to be drawn on the white notes.
  42637. By default this is used to label the C in each octave, but could be used for other things.
  42638. @see setOctaveForMiddleC
  42639. */
  42640. virtual const String getWhiteNoteText (const int midiNoteNumber);
  42641. /** Draws the up and down buttons that change the base note. */
  42642. virtual void drawUpDownButton (Graphics& g, int w, int h,
  42643. const bool isMouseOver,
  42644. const bool isButtonPressed,
  42645. const bool movesOctavesUp);
  42646. /** Callback when the mouse is clicked on a key.
  42647. You could use this to do things like handle right-clicks on keys, etc.
  42648. Return true if you want the click to trigger the note, or false if you
  42649. want to handle it yourself and not have the note played.
  42650. @see mouseDraggedToKey
  42651. */
  42652. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  42653. /** Callback when the mouse is dragged from one key onto another.
  42654. @see mouseDownOnKey
  42655. */
  42656. virtual void mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  42657. /** Calculates the positon of a given midi-note.
  42658. This can be overridden to create layouts with custom key-widths.
  42659. @param midiNoteNumber the note to find
  42660. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  42661. @param x the x position of the left-hand edge of the key (this method
  42662. always works in terms of a horizontal keyboard)
  42663. @param w the width of the key
  42664. */
  42665. virtual void getKeyPosition (int midiNoteNumber, float keyWidth,
  42666. int& x, int& w) const;
  42667. private:
  42668. MidiKeyboardState& state;
  42669. int xOffset, blackNoteLength;
  42670. float keyWidth;
  42671. Orientation orientation;
  42672. int midiChannel, midiInChannelMask;
  42673. float velocity;
  42674. int noteUnderMouse, mouseDownNote;
  42675. BigInteger keysPressed, keysCurrentlyDrawnDown;
  42676. int rangeStart, rangeEnd, firstKey;
  42677. bool canScroll, mouseDragging, useMousePositionForVelocity;
  42678. Button* scrollDown;
  42679. Button* scrollUp;
  42680. Array <KeyPress> keyPresses;
  42681. Array <int> keyPressNotes;
  42682. int keyMappingOctave;
  42683. int octaveNumForMiddleC;
  42684. static const uint8 whiteNotes[];
  42685. static const uint8 blackNotes[];
  42686. void getKeyPos (int midiNoteNumber, int& x, int& w) const;
  42687. int xyToNote (const Point<int>& pos, float& mousePositionVelocity);
  42688. int remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const;
  42689. void resetAnyKeysInUse();
  42690. void updateNoteUnderMouse (const Point<int>& pos);
  42691. void repaintNote (const int midiNoteNumber);
  42692. MidiKeyboardComponent (const MidiKeyboardComponent&);
  42693. MidiKeyboardComponent& operator= (const MidiKeyboardComponent&);
  42694. };
  42695. #endif // __JUCE_MIDIKEYBOARDCOMPONENT_JUCEHEADER__
  42696. /*** End of inlined file: juce_MidiKeyboardComponent.h ***/
  42697. #endif
  42698. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42699. /*** Start of inlined file: juce_NSViewComponent.h ***/
  42700. #ifndef __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42701. #define __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42702. #if ! DOXYGEN
  42703. class NSViewComponentInternal;
  42704. #endif
  42705. #if JUCE_MAC || DOXYGEN
  42706. /**
  42707. A Mac-specific class that can create and embed an NSView inside itself.
  42708. To use it, create one of these, put it in place and make sure it's visible in a
  42709. window, then use setView() to assign an NSView to it. The view will then be
  42710. moved and resized to follow the movements of this component.
  42711. Of course, since the view is a native object, it'll obliterate any
  42712. juce components that may overlap this component, but that's life.
  42713. */
  42714. class JUCE_API NSViewComponent : public Component
  42715. {
  42716. public:
  42717. /** Create an initially-empty container. */
  42718. NSViewComponent();
  42719. /** Destructor. */
  42720. ~NSViewComponent();
  42721. /** Assigns an NSView to this peer.
  42722. The view will be retained and released by this component for as long as
  42723. it is needed. To remove the current view, just call setView (0).
  42724. Note: a void* is used here to avoid including the cocoa headers as
  42725. part of the juce.h, but the method expects an NSView*.
  42726. */
  42727. void setView (void* nsView);
  42728. /** Returns the current NSView.
  42729. Note: a void* is returned here to avoid including the cocoa headers as
  42730. a requirement of juce.h, so you should just cast the object to an NSView*.
  42731. */
  42732. void* getView() const;
  42733. /** @internal */
  42734. void paint (Graphics& g);
  42735. juce_UseDebuggingNewOperator
  42736. private:
  42737. friend class NSViewComponentInternal;
  42738. ScopedPointer <NSViewComponentInternal> info;
  42739. NSViewComponent (const NSViewComponent&);
  42740. NSViewComponent& operator= (const NSViewComponent&);
  42741. };
  42742. #endif
  42743. #endif // __JUCE_NSVIEWCOMPONENT_JUCEHEADER__
  42744. /*** End of inlined file: juce_NSViewComponent.h ***/
  42745. #endif
  42746. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42747. /*** Start of inlined file: juce_OpenGLComponent.h ***/
  42748. #ifndef __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42749. #define __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42750. // this is used to disable OpenGL, and is defined in juce_Config.h
  42751. #if JUCE_OPENGL || DOXYGEN
  42752. /**
  42753. Represents the various properties of an OpenGL bitmap format.
  42754. @see OpenGLComponent::setPixelFormat
  42755. */
  42756. class JUCE_API OpenGLPixelFormat
  42757. {
  42758. public:
  42759. /** Creates an OpenGLPixelFormat.
  42760. The default constructor just initialises the object as a simple 8-bit
  42761. RGBA format.
  42762. */
  42763. OpenGLPixelFormat (int bitsPerRGBComponent = 8,
  42764. int alphaBits = 8,
  42765. int depthBufferBits = 16,
  42766. int stencilBufferBits = 0);
  42767. OpenGLPixelFormat (const OpenGLPixelFormat&);
  42768. OpenGLPixelFormat& operator= (const OpenGLPixelFormat&);
  42769. bool operator== (const OpenGLPixelFormat&) const;
  42770. int redBits; /**< The number of bits per pixel to use for the red channel. */
  42771. int greenBits; /**< The number of bits per pixel to use for the green channel. */
  42772. int blueBits; /**< The number of bits per pixel to use for the blue channel. */
  42773. int alphaBits; /**< The number of bits per pixel to use for the alpha channel. */
  42774. int depthBufferBits; /**< The number of bits per pixel to use for a depth buffer. */
  42775. int stencilBufferBits; /**< The number of bits per pixel to use for a stencil buffer. */
  42776. int accumulationBufferRedBits; /**< The number of bits per pixel to use for an accumulation buffer's red channel. */
  42777. int accumulationBufferGreenBits; /**< The number of bits per pixel to use for an accumulation buffer's green channel. */
  42778. int accumulationBufferBlueBits; /**< The number of bits per pixel to use for an accumulation buffer's blue channel. */
  42779. int accumulationBufferAlphaBits; /**< The number of bits per pixel to use for an accumulation buffer's alpha channel. */
  42780. uint8 fullSceneAntiAliasingNumSamples; /**< The number of samples to use in full-scene anti-aliasing (if available). */
  42781. /** Returns a list of all the pixel formats that can be used in this system.
  42782. A reference component is needed in case there are multiple screens with different
  42783. capabilities - in which case, the one that the component is on will be used.
  42784. */
  42785. static void getAvailablePixelFormats (Component* component,
  42786. OwnedArray <OpenGLPixelFormat>& results);
  42787. juce_UseDebuggingNewOperator
  42788. };
  42789. /**
  42790. A base class for types of OpenGL context.
  42791. An OpenGLComponent will supply its own context for drawing in its window.
  42792. */
  42793. class JUCE_API OpenGLContext
  42794. {
  42795. public:
  42796. /** Destructor. */
  42797. virtual ~OpenGLContext();
  42798. /** Makes this context the currently active one. */
  42799. virtual bool makeActive() const throw() = 0;
  42800. /** If this context is currently active, it is disactivated. */
  42801. virtual bool makeInactive() const throw() = 0;
  42802. /** Returns true if this context is currently active. */
  42803. virtual bool isActive() const throw() = 0;
  42804. /** Swaps the buffers (if the context can do this). */
  42805. virtual void swapBuffers() = 0;
  42806. /** Sets whether the context checks the vertical sync before swapping.
  42807. The value is the number of frames to allow between buffer-swapping. This is
  42808. fairly system-dependent, but 0 turns off syncing, 1 makes it swap on frame-boundaries,
  42809. and greater numbers indicate that it should swap less often.
  42810. Returns true if it sets the value successfully.
  42811. */
  42812. virtual bool setSwapInterval (int numFramesPerSwap) = 0;
  42813. /** Returns the current swap-sync interval.
  42814. See setSwapInterval() for info about the value returned.
  42815. */
  42816. virtual int getSwapInterval() const = 0;
  42817. /** Returns the pixel format being used by this context. */
  42818. virtual const OpenGLPixelFormat getPixelFormat() const = 0;
  42819. /** For windowed contexts, this moves the context within the bounds of
  42820. its parent window.
  42821. */
  42822. virtual void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight) = 0;
  42823. /** For windowed contexts, this triggers a repaint of the window.
  42824. (Not relevent on all platforms).
  42825. */
  42826. virtual void repaint() = 0;
  42827. /** Returns an OS-dependent handle to the raw GL context.
  42828. On win32, this will be a HGLRC; on the Mac, an AGLContext; on Linux,
  42829. a GLXContext.
  42830. */
  42831. virtual void* getRawContext() const throw() = 0;
  42832. /** Deletes the context.
  42833. This must only be called on the message thread, or will deadlock.
  42834. On background threads, call getCurrentContext()->deleteContext(), but be careful not
  42835. to call any other OpenGL function afterwards.
  42836. This doesn't touch other resources, such as window handles, etc.
  42837. You'll probably never have to call this method directly.
  42838. */
  42839. virtual void deleteContext() = 0;
  42840. /** Returns the context that's currently in active use by the calling thread.
  42841. Returns 0 if there isn't an active context.
  42842. */
  42843. static OpenGLContext* getCurrentContext();
  42844. juce_UseDebuggingNewOperator
  42845. protected:
  42846. OpenGLContext() throw();
  42847. };
  42848. /**
  42849. A component that contains an OpenGL canvas.
  42850. Override this, add it to whatever component you want to, and use the renderOpenGL()
  42851. method to draw its contents.
  42852. */
  42853. class JUCE_API OpenGLComponent : public Component
  42854. {
  42855. public:
  42856. /** Used to select the type of openGL API to use, if more than one choice is available
  42857. on a particular platform.
  42858. */
  42859. enum OpenGLType
  42860. {
  42861. openGLDefault = 0,
  42862. #if JUCE_IPHONE
  42863. openGLES1, /**< On the iPhone, this selects openGL ES 1.0 */
  42864. openGLES2 /**< On the iPhone, this selects openGL ES 2.0 */
  42865. #endif
  42866. };
  42867. /** Creates an OpenGLComponent. */
  42868. OpenGLComponent (OpenGLType type = openGLDefault);
  42869. /** Destructor. */
  42870. ~OpenGLComponent();
  42871. /** Changes the pixel format used by this component.
  42872. @see OpenGLPixelFormat::getAvailablePixelFormats()
  42873. */
  42874. void setPixelFormat (const OpenGLPixelFormat& formatToUse);
  42875. /** Returns the pixel format that this component is currently using. */
  42876. const OpenGLPixelFormat getPixelFormat() const;
  42877. /** Specifies an OpenGL context which should be shared with the one that this
  42878. component is using.
  42879. This is an OpenGL feature that lets two contexts share their texture data.
  42880. Note that this pointer is stored by the component, and when the component
  42881. needs to recreate its internal context for some reason, the same context
  42882. will be used again to share lists. So if you pass a context in here,
  42883. don't delete the context while this component is still using it! You can
  42884. call shareWith (0) to stop this component from sharing with it.
  42885. */
  42886. void shareWith (OpenGLContext* contextToShareListsWith);
  42887. /** Returns the context that this component is sharing with.
  42888. @see shareWith
  42889. */
  42890. OpenGLContext* getShareContext() const throw() { return contextToShareListsWith; }
  42891. /** Flips the openGL buffers over. */
  42892. void swapBuffers();
  42893. /** This replaces the normal paint() callback - use it to draw your openGL stuff.
  42894. When this is called, makeCurrentContextActive() will already have been called
  42895. for you, so you just need to draw.
  42896. */
  42897. virtual void renderOpenGL() = 0;
  42898. /** This method is called when the component creates a new OpenGL context.
  42899. A new context may be created when the component is first used, or when it
  42900. is moved to a different window, or when the window is hidden and re-shown,
  42901. etc.
  42902. You can use this callback as an opportunity to set up things like textures
  42903. that your context needs.
  42904. New contexts are created on-demand by the makeCurrentContextActive() method - so
  42905. if the context is deleted, e.g. by changing the pixel format or window, no context
  42906. will be created until the next call to makeCurrentContextActive(), which will
  42907. synchronously create one and call this method. This means that if you're using
  42908. a non-GUI thread for rendering, you can make sure this method is be called by
  42909. your renderer thread.
  42910. When this callback happens, the context will already have been made current
  42911. using the makeCurrentContextActive() method, so there's no need to call it
  42912. again in your code.
  42913. */
  42914. virtual void newOpenGLContextCreated() = 0;
  42915. /** Returns the context that will draw into this component.
  42916. This may return 0 if the component is currently invisible or hasn't currently
  42917. got a context. The context object can be deleted and a new one created during
  42918. the lifetime of this component, and there may be times when it doesn't have one.
  42919. @see newOpenGLContextCreated()
  42920. */
  42921. OpenGLContext* getCurrentContext() const throw() { return context; }
  42922. /** Makes this component the current openGL context.
  42923. You might want to use this in things like your resize() method, before calling
  42924. GL commands.
  42925. If this returns false, then the context isn't active, so you should avoid
  42926. making any calls.
  42927. This call may actually create a context if one isn't currently initialised. If
  42928. it does this, it will also synchronously call the newOpenGLContextCreated()
  42929. method to let you initialise it as necessary.
  42930. @see OpenGLContext::makeActive
  42931. */
  42932. bool makeCurrentContextActive();
  42933. /** Stops the current component being the active OpenGL context.
  42934. This is the opposite of makeCurrentContextActive()
  42935. @see OpenGLContext::makeInactive
  42936. */
  42937. void makeCurrentContextInactive();
  42938. /** Returns true if this component is the active openGL context for the
  42939. current thread.
  42940. @see OpenGLContext::isActive
  42941. */
  42942. bool isActiveContext() const throw();
  42943. /** Calls the rendering callback, and swaps the buffers afterwards.
  42944. This is called automatically by paint() when the component needs to be rendered.
  42945. It can be overridden if you need to decouple the rendering from the paint callback
  42946. and render with a custom thread.
  42947. Returns true if the operation succeeded.
  42948. */
  42949. virtual bool renderAndSwapBuffers();
  42950. /** This returns a critical section that can be used to lock the current context.
  42951. Because the context that is used by this component can change, e.g. when the
  42952. component is shown or hidden, then if you're rendering to it on a background
  42953. thread, this allows you to lock the context for the duration of your rendering
  42954. routine.
  42955. */
  42956. CriticalSection& getContextLock() throw() { return contextLock; }
  42957. /** @internal */
  42958. void paint (Graphics& g);
  42959. /** Returns the native handle of an embedded heavyweight window, if there is one.
  42960. E.g. On windows, this will return the HWND of the sub-window containing
  42961. the opengl context, on the mac it'll be the NSOpenGLView.
  42962. */
  42963. void* getNativeWindowHandle() const;
  42964. /** Delete the context.
  42965. This can be called back on the same thread that created the context. */
  42966. void deleteContext();
  42967. juce_UseDebuggingNewOperator
  42968. private:
  42969. const OpenGLType type;
  42970. class OpenGLComponentWatcher;
  42971. friend class OpenGLComponentWatcher;
  42972. friend class ScopedPointer <OpenGLComponentWatcher>;
  42973. ScopedPointer <OpenGLComponentWatcher> componentWatcher;
  42974. ScopedPointer <OpenGLContext> context;
  42975. OpenGLContext* contextToShareListsWith;
  42976. CriticalSection contextLock;
  42977. OpenGLPixelFormat preferredPixelFormat;
  42978. bool needToUpdateViewport;
  42979. OpenGLContext* createContext();
  42980. void updateContextPosition();
  42981. void internalRepaint (int x, int y, int w, int h);
  42982. OpenGLComponent (const OpenGLComponent&);
  42983. OpenGLComponent& operator= (const OpenGLComponent&);
  42984. };
  42985. #endif
  42986. #endif // __JUCE_OPENGLCOMPONENT_JUCEHEADER__
  42987. /*** End of inlined file: juce_OpenGLComponent.h ***/
  42988. #endif
  42989. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42990. /*** Start of inlined file: juce_PreferencesPanel.h ***/
  42991. #ifndef __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42992. #define __JUCE_PREFERENCESPANEL_JUCEHEADER__
  42993. /**
  42994. A component with a set of buttons at the top for changing between pages of
  42995. preferences.
  42996. This is just a handy way of writing a Mac-style preferences panel where you
  42997. have a row of buttons along the top for the different preference categories,
  42998. each button having an icon above its name. Clicking these will show an
  42999. appropriate prefs page below it.
  43000. You can either put one of these inside your own component, or just use the
  43001. showInDialogBox() method to show it in a window and run it modally.
  43002. To use it, just add a set of named pages with the addSettingsPage() method,
  43003. and implement the createComponentForPage() method to create suitable components
  43004. for each of these pages.
  43005. */
  43006. class JUCE_API PreferencesPanel : public Component,
  43007. private ButtonListener
  43008. {
  43009. public:
  43010. /** Creates an empty panel.
  43011. Use addSettingsPage() to add some pages to it in your constructor.
  43012. */
  43013. PreferencesPanel();
  43014. /** Destructor. */
  43015. ~PreferencesPanel();
  43016. /** Creates a page using a set of drawables to define the page's icon.
  43017. Note that the other version of this method is much easier if you're using
  43018. an image instead of a custom drawable.
  43019. @param pageTitle the name of this preferences page - you'll need to
  43020. make sure your createComponentForPage() method creates
  43021. a suitable component when it is passed this name
  43022. @param normalIcon the drawable to display in the page's button normally
  43023. @param overIcon the drawable to display in the page's button when the mouse is over
  43024. @param downIcon the drawable to display in the page's button when the button is down
  43025. @see DrawableButton
  43026. */
  43027. void addSettingsPage (const String& pageTitle,
  43028. const Drawable* normalIcon,
  43029. const Drawable* overIcon,
  43030. const Drawable* downIcon);
  43031. /** Creates a page using a set of drawables to define the page's icon.
  43032. The other version of this method gives you more control over the icon, but this
  43033. one is much easier if you're just loading it from a file.
  43034. @param pageTitle the name of this preferences page - you'll need to
  43035. make sure your createComponentForPage() method creates
  43036. a suitable component when it is passed this name
  43037. @param imageData a block of data containing an image file, e.g. a jpeg, png or gif.
  43038. For this to look good, you'll probably want to use a nice
  43039. transparent png file.
  43040. @param imageDataSize the size of the image data, in bytes
  43041. */
  43042. void addSettingsPage (const String& pageTitle,
  43043. const void* imageData,
  43044. int imageDataSize);
  43045. /** Utility method to display this panel in a DialogWindow.
  43046. Calling this will create a DialogWindow containing this panel with the
  43047. given size and title, and will run it modally, returning when the user
  43048. closes the dialog box.
  43049. */
  43050. void showInDialogBox (const String& dialogtitle,
  43051. int dialogWidth,
  43052. int dialogHeight,
  43053. const Colour& backgroundColour = Colours::white);
  43054. /** Subclasses must override this to return a component for each preferences page.
  43055. The subclass should return a pointer to a new component representing the named
  43056. page, which the panel will then display.
  43057. The panel will delete the component later when the user goes to another page
  43058. or deletes the panel.
  43059. */
  43060. virtual Component* createComponentForPage (const String& pageName) = 0;
  43061. /** Changes the current page being displayed. */
  43062. void setCurrentPage (const String& pageName);
  43063. /** @internal */
  43064. void resized();
  43065. /** @internal */
  43066. void paint (Graphics& g);
  43067. /** @internal */
  43068. void buttonClicked (Button* button);
  43069. juce_UseDebuggingNewOperator
  43070. private:
  43071. String currentPageName;
  43072. ScopedPointer <Component> currentPage;
  43073. int buttonSize;
  43074. PreferencesPanel (const PreferencesPanel&);
  43075. PreferencesPanel& operator= (const PreferencesPanel&);
  43076. };
  43077. #endif // __JUCE_PREFERENCESPANEL_JUCEHEADER__
  43078. /*** End of inlined file: juce_PreferencesPanel.h ***/
  43079. #endif
  43080. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43081. /*** Start of inlined file: juce_QuickTimeMovieComponent.h ***/
  43082. #ifndef __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43083. #define __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43084. // (NB: This stuff mustn't go inside the "#if QUICKTIME" block, or it'll break the
  43085. // amalgamated build)
  43086. #if JUCE_WINDOWS
  43087. typedef ActiveXControlComponent QTCompBaseClass;
  43088. #elif JUCE_MAC
  43089. typedef NSViewComponent QTCompBaseClass;
  43090. #endif
  43091. // this is used to disable QuickTime, and is defined in juce_Config.h
  43092. #if JUCE_QUICKTIME || DOXYGEN
  43093. /**
  43094. A window that can play back a QuickTime movie.
  43095. */
  43096. class JUCE_API QuickTimeMovieComponent : public QTCompBaseClass
  43097. {
  43098. public:
  43099. /** Creates a QuickTimeMovieComponent, initially blank.
  43100. Use the loadMovie() method to load a movie once you've added the
  43101. component to a window, (or put it on the desktop as a heavyweight window).
  43102. Loading a movie when the component isn't visible can cause problems, as
  43103. QuickTime needs a window handle to initialise properly.
  43104. */
  43105. QuickTimeMovieComponent();
  43106. /** Destructor. */
  43107. ~QuickTimeMovieComponent();
  43108. /** Returns true if QT is installed and working on this machine.
  43109. */
  43110. static bool isQuickTimeAvailable() throw();
  43111. /** Tries to load a QuickTime movie from a file into the player.
  43112. It's best to call this function once you've added the component to a window,
  43113. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43114. component isn't visible can cause problems, because QuickTime needs a window
  43115. handle to do its stuff.
  43116. @param movieFile the .mov file to open
  43117. @param isControllerVisible whether to show a controller bar at the bottom
  43118. @returns true if the movie opens successfully
  43119. */
  43120. bool loadMovie (const File& movieFile,
  43121. bool isControllerVisible);
  43122. /** Tries to load a QuickTime movie from a URL into the player.
  43123. It's best to call this function once you've added the component to a window,
  43124. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43125. component isn't visible can cause problems, because QuickTime needs a window
  43126. handle to do its stuff.
  43127. @param movieURL the .mov file to open
  43128. @param isControllerVisible whether to show a controller bar at the bottom
  43129. @returns true if the movie opens successfully
  43130. */
  43131. bool loadMovie (const URL& movieURL,
  43132. bool isControllerVisible);
  43133. /** Tries to load a QuickTime movie from a stream into the player.
  43134. It's best to call this function once you've added the component to a window,
  43135. (or put it on the desktop as a heavyweight window). Loading a movie when the
  43136. component isn't visible can cause problems, because QuickTime needs a window
  43137. handle to do its stuff.
  43138. @param movieStream a stream containing a .mov file. The component may try
  43139. to read the whole stream before playing, rather than
  43140. streaming from it.
  43141. @param isControllerVisible whether to show a controller bar at the bottom
  43142. @returns true if the movie opens successfully
  43143. */
  43144. bool loadMovie (InputStream* movieStream,
  43145. bool isControllerVisible);
  43146. /** Closes the movie, if one is open. */
  43147. void closeMovie();
  43148. /** Returns the movie file that is currently open.
  43149. If there isn't one, this returns File::nonexistent
  43150. */
  43151. const File getCurrentMovieFile() const;
  43152. /** Returns true if there's currently a movie open. */
  43153. bool isMovieOpen() const;
  43154. /** Returns the length of the movie, in seconds. */
  43155. double getMovieDuration() const;
  43156. /** Returns the movie's natural size, in pixels.
  43157. You can use this to resize the component to show the movie at its preferred
  43158. scale.
  43159. If no movie is loaded, the size returned will be 0 x 0.
  43160. */
  43161. void getMovieNormalSize (int& width, int& height) const;
  43162. /** This will position the component within a given area, keeping its aspect
  43163. ratio correct according to the movie's normal size.
  43164. The component will be made as large as it can go within the space, and will
  43165. be aligned according to the justification value if this means there are gaps at
  43166. the top or sides.
  43167. */
  43168. void setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  43169. const RectanglePlacement& placement);
  43170. /** Starts the movie playing. */
  43171. void play();
  43172. /** Stops the movie playing. */
  43173. void stop();
  43174. /** Returns true if the movie is currently playing. */
  43175. bool isPlaying() const;
  43176. /** Moves the movie's position back to the start. */
  43177. void goToStart();
  43178. /** Sets the movie's position to a given time. */
  43179. void setPosition (double seconds);
  43180. /** Returns the current play position of the movie. */
  43181. double getPosition() const;
  43182. /** Changes the movie playback rate.
  43183. A value of 1 is normal speed, greater values play it proportionately faster,
  43184. smaller values play it slower.
  43185. */
  43186. void setSpeed (float newSpeed);
  43187. /** Changes the movie's playback volume.
  43188. @param newVolume the volume in the range 0 (silent) to 1.0 (full)
  43189. */
  43190. void setMovieVolume (float newVolume);
  43191. /** Returns the movie's playback volume.
  43192. @returns the volume in the range 0 (silent) to 1.0 (full)
  43193. */
  43194. float getMovieVolume() const;
  43195. /** Tells the movie whether it should loop. */
  43196. void setLooping (bool shouldLoop);
  43197. /** Returns true if the movie is currently looping.
  43198. @see setLooping
  43199. */
  43200. bool isLooping() const;
  43201. /** True if the native QuickTime controller bar is shown in the window.
  43202. @see loadMovie
  43203. */
  43204. bool isControllerVisible() const;
  43205. /** @internal */
  43206. void paint (Graphics& g);
  43207. juce_UseDebuggingNewOperator
  43208. private:
  43209. File movieFile;
  43210. bool movieLoaded, controllerVisible, looping;
  43211. #if JUCE_WINDOWS
  43212. void parentHierarchyChanged();
  43213. void visibilityChanged();
  43214. void createControlIfNeeded();
  43215. bool isControlCreated() const;
  43216. class Pimpl;
  43217. friend class ScopedPointer <Pimpl>;
  43218. ScopedPointer <Pimpl> pimpl;
  43219. #else
  43220. void* movie;
  43221. #endif
  43222. QuickTimeMovieComponent (const QuickTimeMovieComponent&);
  43223. QuickTimeMovieComponent& operator= (const QuickTimeMovieComponent&);
  43224. };
  43225. #endif
  43226. #endif // __JUCE_QUICKTIMEMOVIECOMPONENT_JUCEHEADER__
  43227. /*** End of inlined file: juce_QuickTimeMovieComponent.h ***/
  43228. #endif
  43229. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43230. /*** Start of inlined file: juce_SystemTrayIconComponent.h ***/
  43231. #ifndef __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43232. #define __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43233. #if JUCE_WINDOWS || JUCE_LINUX || DOXYGEN
  43234. /**
  43235. On Windows only, this component sits in the taskbar tray as a small icon.
  43236. To use it, just create one of these components, but don't attempt to make it
  43237. visible, add it to a parent, or put it on the desktop.
  43238. You can then call setIconImage() to create an icon for it in the taskbar.
  43239. To change the icon's tooltip, you can use setIconTooltip().
  43240. To respond to mouse-events, you can override the normal mouseDown(),
  43241. mouseUp(), mouseDoubleClick() and mouseMove() methods, and although the x, y
  43242. position will not be valid, you can use this to respond to clicks. Traditionally
  43243. you'd use a left-click to show your application's window, and a right-click
  43244. to show a pop-up menu.
  43245. */
  43246. class JUCE_API SystemTrayIconComponent : public Component
  43247. {
  43248. public:
  43249. SystemTrayIconComponent();
  43250. /** Destructor. */
  43251. ~SystemTrayIconComponent();
  43252. /** Changes the image shown in the taskbar.
  43253. */
  43254. void setIconImage (const Image& newImage);
  43255. /** Changes the tooltip that Windows shows above the icon. */
  43256. void setIconTooltip (const String& tooltip);
  43257. #if JUCE_LINUX
  43258. /** @internal */
  43259. void paint (Graphics& g);
  43260. #endif
  43261. juce_UseDebuggingNewOperator
  43262. private:
  43263. SystemTrayIconComponent (const SystemTrayIconComponent&);
  43264. SystemTrayIconComponent& operator= (const SystemTrayIconComponent&);
  43265. };
  43266. #endif
  43267. #endif // __JUCE_SYSTEMTRAYICONCOMPONENT_JUCEHEADER__
  43268. /*** End of inlined file: juce_SystemTrayIconComponent.h ***/
  43269. #endif
  43270. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43271. /*** Start of inlined file: juce_WebBrowserComponent.h ***/
  43272. #ifndef __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43273. #define __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43274. #if JUCE_WEB_BROWSER || DOXYGEN
  43275. #if ! DOXYGEN
  43276. class WebBrowserComponentInternal;
  43277. #endif
  43278. /**
  43279. A component that displays an embedded web browser.
  43280. The browser itself will be platform-dependent. On the Mac, probably Safari, on
  43281. Windows, probably IE.
  43282. */
  43283. class JUCE_API WebBrowserComponent : public Component
  43284. {
  43285. public:
  43286. /** Creates a WebBrowserComponent.
  43287. Once it's created and visible, send the browser to a URL using goToURL().
  43288. @param unloadPageWhenBrowserIsHidden if this is true, then when the browser
  43289. component is taken offscreen, it'll clear the current page
  43290. and replace it with a blank page - this can be handy to stop
  43291. the browser using resources in the background when it's not
  43292. actually being used.
  43293. */
  43294. explicit WebBrowserComponent (bool unloadPageWhenBrowserIsHidden = true);
  43295. /** Destructor. */
  43296. ~WebBrowserComponent();
  43297. /** Sends the browser to a particular URL.
  43298. @param url the URL to go to.
  43299. @param headers an optional set of parameters to put in the HTTP header. If
  43300. you supply this, it should be a set of string in the form
  43301. "HeaderKey: HeaderValue"
  43302. @param postData an optional block of data that will be attached to the HTTP
  43303. POST request
  43304. */
  43305. void goToURL (const String& url,
  43306. const StringArray* headers = 0,
  43307. const MemoryBlock* postData = 0);
  43308. /** Stops the current page loading.
  43309. */
  43310. void stop();
  43311. /** Sends the browser back one page.
  43312. */
  43313. void goBack();
  43314. /** Sends the browser forward one page.
  43315. */
  43316. void goForward();
  43317. /** Refreshes the browser.
  43318. */
  43319. void refresh();
  43320. /** This callback is called when the browser is about to navigate
  43321. to a new location.
  43322. You can override this method to perform some action when the user
  43323. tries to go to a particular URL. To allow the operation to carry on,
  43324. return true, or return false to stop the navigation happening.
  43325. */
  43326. virtual bool pageAboutToLoad (const String& newURL);
  43327. /** @internal */
  43328. void paint (Graphics& g);
  43329. /** @internal */
  43330. void resized();
  43331. /** @internal */
  43332. void parentHierarchyChanged();
  43333. /** @internal */
  43334. void visibilityChanged();
  43335. juce_UseDebuggingNewOperator
  43336. private:
  43337. WebBrowserComponentInternal* browser;
  43338. bool blankPageShown, unloadPageWhenBrowserIsHidden;
  43339. String lastURL;
  43340. StringArray lastHeaders;
  43341. MemoryBlock lastPostData;
  43342. void reloadLastURL();
  43343. void checkWindowAssociation();
  43344. WebBrowserComponent (const WebBrowserComponent&);
  43345. WebBrowserComponent& operator= (const WebBrowserComponent&);
  43346. };
  43347. #endif
  43348. #endif // __JUCE_WEBBROWSERCOMPONENT_JUCEHEADER__
  43349. /*** End of inlined file: juce_WebBrowserComponent.h ***/
  43350. #endif
  43351. #ifndef __JUCE_ALERTWINDOW_JUCEHEADER__
  43352. #endif
  43353. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  43354. /*** Start of inlined file: juce_CallOutBox.h ***/
  43355. #ifndef __JUCE_CALLOUTBOX_JUCEHEADER__
  43356. #define __JUCE_CALLOUTBOX_JUCEHEADER__
  43357. /**
  43358. A box with a small arrow that can be used as a temporary pop-up window to show
  43359. extra controls when a button or other component is clicked.
  43360. Using one of these is similar to having a popup menu attached to a button or
  43361. other component - but it looks fancier, and has an arrow that can indicate the
  43362. object that it applies to.
  43363. Normally, you'd create one of these on the stack and run it modally, e.g.
  43364. @code
  43365. void mouseUp (const MouseEvent& e)
  43366. {
  43367. MyContentComponent content;
  43368. content.setSize (300, 300);
  43369. CallOutBox callOut (content, *this, 0);
  43370. callOut.runModalLoop();
  43371. }
  43372. @endcode
  43373. The call-out will resize and position itself when the content changes size.
  43374. */
  43375. class JUCE_API CallOutBox : public Component
  43376. {
  43377. public:
  43378. /** Creates a CallOutBox.
  43379. @param contentComponent the component to display inside the call-out. This should
  43380. already have a size set (although the call-out will also
  43381. update itself when the component's size is changed later).
  43382. Obviously this component must not be deleted until the
  43383. call-out box has been deleted.
  43384. @param componentToPointTo the component that the call-out's arrow should point towards
  43385. @param parentComponent if non-zero, this is the component to add the call-out to. If
  43386. this is zero, the call-out will be added to the desktop.
  43387. */
  43388. CallOutBox (Component& contentComponent,
  43389. Component& componentToPointTo,
  43390. Component* parentComponent);
  43391. /** Destructor. */
  43392. ~CallOutBox();
  43393. /** Changes the length of the arrow. */
  43394. void setArrowSize (float newSize);
  43395. /** Updates the position and size of the box.
  43396. You shouldn't normally need to call this, unless you need more precise control over the
  43397. layout.
  43398. @param newAreaToPointTo the rectangle to make the box's arrow point to
  43399. @param newAreaToFitIn the area within which the box's position should be constrained
  43400. */
  43401. void updatePosition (const Rectangle<int>& newAreaToPointTo,
  43402. const Rectangle<int>& newAreaToFitIn);
  43403. /** @internal */
  43404. void paint (Graphics& g);
  43405. /** @internal */
  43406. void resized();
  43407. /** @internal */
  43408. void moved();
  43409. /** @internal */
  43410. void childBoundsChanged (Component*);
  43411. /** @internal */
  43412. bool hitTest (int x, int y);
  43413. /** @internal */
  43414. void inputAttemptWhenModal();
  43415. /** @internal */
  43416. bool keyPressed (const KeyPress& key);
  43417. /** @internal */
  43418. void handleCommandMessage (int commandId);
  43419. juce_UseDebuggingNewOperator
  43420. private:
  43421. int borderSpace;
  43422. float arrowSize;
  43423. Component& content;
  43424. Path outline;
  43425. Point<float> targetPoint;
  43426. Rectangle<int> availableArea, targetArea;
  43427. Image background;
  43428. void refreshPath();
  43429. void drawCallOutBoxBackground (Graphics& g, const Path& outline, int width, int height);
  43430. CallOutBox (const CallOutBox&);
  43431. CallOutBox& operator= (const CallOutBox&);
  43432. };
  43433. #endif // __JUCE_CALLOUTBOX_JUCEHEADER__
  43434. /*** End of inlined file: juce_CallOutBox.h ***/
  43435. #endif
  43436. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  43437. /*** Start of inlined file: juce_ComponentPeer.h ***/
  43438. #ifndef __JUCE_COMPONENTPEER_JUCEHEADER__
  43439. #define __JUCE_COMPONENTPEER_JUCEHEADER__
  43440. class ComponentBoundsConstrainer;
  43441. /**
  43442. The base class for window objects that wrap a component as a real operating
  43443. system object.
  43444. This is an abstract base class - the platform specific code contains default
  43445. implementations of it that create and manage windows.
  43446. @see Component::createNewPeer
  43447. */
  43448. class JUCE_API ComponentPeer
  43449. {
  43450. public:
  43451. /** A combination of these flags is passed to the ComponentPeer constructor. */
  43452. enum StyleFlags
  43453. {
  43454. windowAppearsOnTaskbar = (1 << 0), /**< Indicates that the window should have a corresponding
  43455. entry on the taskbar (ignored on MacOSX) */
  43456. windowIsTemporary = (1 << 1), /**< Indicates that the window is a temporary popup, like a menu,
  43457. tooltip, etc. */
  43458. windowIgnoresMouseClicks = (1 << 2), /**< Indicates that the window should let mouse clicks pass
  43459. through it (may not be possible on some platforms). */
  43460. windowHasTitleBar = (1 << 3), /**< Indicates that the window should have a normal OS-specific
  43461. title bar and frame\. if not specified, the window will be
  43462. borderless. */
  43463. windowIsResizable = (1 << 4), /**< Indicates that the window should have a resizable border. */
  43464. windowHasMinimiseButton = (1 << 5), /**< Indicates that if the window has a title bar, it should have a
  43465. minimise button on it. */
  43466. windowHasMaximiseButton = (1 << 6), /**< Indicates that if the window has a title bar, it should have a
  43467. maximise button on it. */
  43468. windowHasCloseButton = (1 << 7), /**< Indicates that if the window has a title bar, it should have a
  43469. close button on it. */
  43470. windowHasDropShadow = (1 << 8), /**< Indicates that the window should have a drop-shadow (this may
  43471. not be possible on all platforms). */
  43472. windowRepaintedExplictly = (1 << 9), /**< Not intended for public use - this tells a window not to
  43473. do its own repainting, but only to repaint when the
  43474. performAnyPendingRepaintsNow() method is called. */
  43475. windowIgnoresKeyPresses = (1 << 10), /**< Tells the window not to catch any keypresses. This can
  43476. be used for things like plugin windows, to stop them interfering
  43477. with the host's shortcut keys */
  43478. windowIsSemiTransparent = (1 << 31) /**< Not intended for public use - makes a window transparent. */
  43479. };
  43480. /** Creates a peer.
  43481. The component is the one that we intend to represent, and the style flags are
  43482. a combination of the values in the StyleFlags enum
  43483. */
  43484. ComponentPeer (Component* component, int styleFlags);
  43485. /** Destructor. */
  43486. virtual ~ComponentPeer();
  43487. /** Returns the component being represented by this peer. */
  43488. Component* getComponent() const throw() { return component; }
  43489. /** Returns the set of style flags that were set when the window was created.
  43490. @see Component::addToDesktop
  43491. */
  43492. int getStyleFlags() const throw() { return styleFlags; }
  43493. /** Returns the raw handle to whatever kind of window is being used.
  43494. On windows, this is probably a HWND, on the mac, it's likely to be a WindowRef,
  43495. but rememeber there's no guarantees what you'll get back.
  43496. */
  43497. virtual void* getNativeHandle() const = 0;
  43498. /** Shows or hides the window. */
  43499. virtual void setVisible (bool shouldBeVisible) = 0;
  43500. /** Changes the title of the window. */
  43501. virtual void setTitle (const String& title) = 0;
  43502. /** Moves the window without changing its size.
  43503. If the native window is contained in another window, then the co-ordinates are
  43504. relative to the parent window's origin, not the screen origin.
  43505. This should result in a callback to handleMovedOrResized().
  43506. */
  43507. virtual void setPosition (int x, int y) = 0;
  43508. /** Resizes the window without changing its position.
  43509. This should result in a callback to handleMovedOrResized().
  43510. */
  43511. virtual void setSize (int w, int h) = 0;
  43512. /** Moves and resizes the window.
  43513. If the native window is contained in another window, then the co-ordinates are
  43514. relative to the parent window's origin, not the screen origin.
  43515. This should result in a callback to handleMovedOrResized().
  43516. */
  43517. virtual void setBounds (int x, int y, int w, int h, bool isNowFullScreen) = 0;
  43518. /** Returns the current position and size of the window.
  43519. If the native window is contained in another window, then the co-ordinates are
  43520. relative to the parent window's origin, not the screen origin.
  43521. */
  43522. virtual const Rectangle<int> getBounds() const = 0;
  43523. /** Returns the x-position of this window, relative to the screen's origin. */
  43524. virtual const Point<int> getScreenPosition() const = 0;
  43525. /** Converts a position relative to the top-left of this component to screen co-ordinates. */
  43526. virtual const Point<int> relativePositionToGlobal (const Point<int>& relativePosition) = 0;
  43527. /** Converts a screen co-ordinate to a position relative to the top-left of this component. */
  43528. virtual const Point<int> globalPositionToRelative (const Point<int>& screenPosition) = 0;
  43529. /** Minimises the window. */
  43530. virtual void setMinimised (bool shouldBeMinimised) = 0;
  43531. /** True if the window is currently minimised. */
  43532. virtual bool isMinimised() const = 0;
  43533. /** Enable/disable fullscreen mode for the window. */
  43534. virtual void setFullScreen (bool shouldBeFullScreen) = 0;
  43535. /** True if the window is currently full-screen. */
  43536. virtual bool isFullScreen() const = 0;
  43537. /** Sets the size to restore to if fullscreen mode is turned off. */
  43538. void setNonFullScreenBounds (const Rectangle<int>& newBounds) throw();
  43539. /** Returns the size to restore to if fullscreen mode is turned off. */
  43540. const Rectangle<int>& getNonFullScreenBounds() const throw();
  43541. /** Attempts to change the icon associated with this window.
  43542. */
  43543. virtual void setIcon (const Image& newIcon) = 0;
  43544. /** Sets a constrainer to use if the peer can resize itself.
  43545. The constrainer won't be deleted by this object, so the caller must manage its lifetime.
  43546. */
  43547. void setConstrainer (ComponentBoundsConstrainer* newConstrainer) throw();
  43548. /** Returns the current constrainer, if one has been set. */
  43549. ComponentBoundsConstrainer* getConstrainer() const throw() { return constrainer; }
  43550. /** Checks if a point is in the window.
  43551. Coordinates are relative to the top-left of this window. If trueIfInAChildWindow
  43552. is false, then this returns false if the point is actually inside a child of this
  43553. window.
  43554. */
  43555. virtual bool contains (const Point<int>& position, bool trueIfInAChildWindow) const = 0;
  43556. /** Returns the size of the window frame that's around this window.
  43557. Whether or not the window has a normal window frame depends on the flags
  43558. that were set when the window was created by Component::addToDesktop()
  43559. */
  43560. virtual const BorderSize getFrameSize() const = 0;
  43561. /** This is called when the window's bounds change.
  43562. A peer implementation must call this when the window is moved and resized, so that
  43563. this method can pass the message on to the component.
  43564. */
  43565. void handleMovedOrResized();
  43566. /** This is called if the screen resolution changes.
  43567. A peer implementation must call this if the monitor arrangement changes or the available
  43568. screen size changes.
  43569. */
  43570. void handleScreenSizeChange();
  43571. /** This is called to repaint the component into the given context. */
  43572. void handlePaint (LowLevelGraphicsContext& contextToPaintTo);
  43573. /** Sets this window to either be always-on-top or normal.
  43574. Some kinds of window might not be able to do this, so should return false.
  43575. */
  43576. virtual bool setAlwaysOnTop (bool alwaysOnTop) = 0;
  43577. /** Brings the window to the top, optionally also giving it focus. */
  43578. virtual void toFront (bool makeActive) = 0;
  43579. /** Moves the window to be just behind another one. */
  43580. virtual void toBehind (ComponentPeer* other) = 0;
  43581. /** Called when the window is brought to the front, either by the OS or by a call
  43582. to toFront().
  43583. */
  43584. void handleBroughtToFront();
  43585. /** True if the window has the keyboard focus. */
  43586. virtual bool isFocused() const = 0;
  43587. /** Tries to give the window keyboard focus. */
  43588. virtual void grabFocus() = 0;
  43589. /** Tells the window that text input may be required at the given position.
  43590. This may cause things like a virtual on-screen keyboard to appear, depending
  43591. on the OS.
  43592. */
  43593. virtual void textInputRequired (const Point<int>& position) = 0;
  43594. /** Called when the window gains keyboard focus. */
  43595. void handleFocusGain();
  43596. /** Called when the window loses keyboard focus. */
  43597. void handleFocusLoss();
  43598. Component* getLastFocusedSubcomponent() const throw();
  43599. /** Called when a key is pressed.
  43600. For keycode info, see the KeyPress class.
  43601. Returns true if the keystroke was used.
  43602. */
  43603. bool handleKeyPress (int keyCode,
  43604. juce_wchar textCharacter);
  43605. /** Called whenever a key is pressed or released.
  43606. Returns true if the keystroke was used.
  43607. */
  43608. bool handleKeyUpOrDown (bool isKeyDown);
  43609. /** Called whenever a modifier key is pressed or released. */
  43610. void handleModifierKeysChange();
  43611. /** Returns the currently focused TextInputTarget, or null if none is found. */
  43612. TextInputTarget* findCurrentTextInputTarget();
  43613. /** Invalidates a region of the window to be repainted asynchronously. */
  43614. virtual void repaint (const Rectangle<int>& area) = 0;
  43615. /** This can be called (from the message thread) to cause the immediate redrawing
  43616. of any areas of this window that need repainting.
  43617. You shouldn't ever really need to use this, it's mainly for special purposes
  43618. like supporting audio plugins where the host's event loop is out of our control.
  43619. */
  43620. virtual void performAnyPendingRepaintsNow() = 0;
  43621. void handleMouseEvent (int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, int64 time);
  43622. void handleMouseWheel (int touchIndex, const Point<int>& positionWithinPeer, int64 time, float x, float y);
  43623. void handleUserClosingWindow();
  43624. void handleFileDragMove (const StringArray& files, const Point<int>& position);
  43625. void handleFileDragExit (const StringArray& files);
  43626. void handleFileDragDrop (const StringArray& files, const Point<int>& position);
  43627. /** Resets the masking region.
  43628. The subclass should call this every time it's about to call the handlePaint
  43629. method.
  43630. @see addMaskedRegion
  43631. */
  43632. void clearMaskedRegion();
  43633. /** Adds a rectangle to the set of areas not to paint over.
  43634. A component can call this on its peer during its paint() method, to signal
  43635. that the painting code should ignore a given region. The reason
  43636. for this is to stop embedded windows (such as OpenGL) getting painted over.
  43637. The masked region is cleared each time before a paint happens, so a component
  43638. will have to make sure it calls this every time it's painted.
  43639. */
  43640. void addMaskedRegion (int x, int y, int w, int h);
  43641. /** Returns the number of currently-active peers.
  43642. @see getPeer
  43643. */
  43644. static int getNumPeers() throw();
  43645. /** Returns one of the currently-active peers.
  43646. @see getNumPeers
  43647. */
  43648. static ComponentPeer* getPeer (int index) throw();
  43649. /** Checks if this peer object is valid.
  43650. @see getNumPeers
  43651. */
  43652. static bool isValidPeer (const ComponentPeer* peer) throw();
  43653. static void bringModalComponentToFront();
  43654. virtual const StringArray getAvailableRenderingEngines() throw();
  43655. virtual int getCurrentRenderingEngine() throw();
  43656. virtual void setCurrentRenderingEngine (int index) throw();
  43657. juce_UseDebuggingNewOperator
  43658. protected:
  43659. Component* const component;
  43660. const int styleFlags;
  43661. RectangleList maskedRegion;
  43662. Rectangle<int> lastNonFullscreenBounds;
  43663. uint32 lastPaintTime;
  43664. ComponentBoundsConstrainer* constrainer;
  43665. static void updateCurrentModifiers() throw();
  43666. private:
  43667. Component::SafePointer<Component> lastFocusedComponent, dragAndDropTargetComponent;
  43668. Component* lastDragAndDropCompUnderMouse;
  43669. bool fakeMouseMessageSent : 1, isWindowMinimised : 1;
  43670. friend class Component;
  43671. static ComponentPeer* getPeerFor (const Component* component) throw();
  43672. void setLastDragDropTarget (Component* comp);
  43673. ComponentPeer (const ComponentPeer&);
  43674. ComponentPeer& operator= (const ComponentPeer&);
  43675. };
  43676. #endif // __JUCE_COMPONENTPEER_JUCEHEADER__
  43677. /*** End of inlined file: juce_ComponentPeer.h ***/
  43678. #endif
  43679. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43680. /*** Start of inlined file: juce_DialogWindow.h ***/
  43681. #ifndef __JUCE_DIALOGWINDOW_JUCEHEADER__
  43682. #define __JUCE_DIALOGWINDOW_JUCEHEADER__
  43683. /**
  43684. A dialog-box style window.
  43685. This class is a convenient way of creating a DocumentWindow with a close button
  43686. that can be triggered by pressing the escape key.
  43687. Any of the methods available to a DocumentWindow or ResizableWindow are also
  43688. available to this, so it can be made resizable, have a menu bar, etc.
  43689. To add items to the box, see the ResizableWindow::setContentComponent() method.
  43690. Don't add components directly to this class - always put them in a content component!
  43691. You'll need to override the DocumentWindow::closeButtonPressed() method to handle
  43692. the user clicking the close button - for more info, see the DocumentWindow
  43693. help.
  43694. @see DocumentWindow, ResizableWindow
  43695. */
  43696. class JUCE_API DialogWindow : public DocumentWindow
  43697. {
  43698. public:
  43699. /** Creates a DialogWindow.
  43700. @param name the name to give the component - this is also
  43701. the title shown at the top of the window. To change
  43702. this later, use setName()
  43703. @param backgroundColour the colour to use for filling the window's background.
  43704. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43705. close button to be triggered
  43706. @param addToDesktop if true, the window will be automatically added to the
  43707. desktop; if false, you can use it as a child component
  43708. */
  43709. DialogWindow (const String& name,
  43710. const Colour& backgroundColour,
  43711. bool escapeKeyTriggersCloseButton,
  43712. bool addToDesktop = true);
  43713. /** Destructor.
  43714. If a content component has been set with setContentComponent(), it
  43715. will be deleted.
  43716. */
  43717. ~DialogWindow();
  43718. /** Easy way of quickly showing a dialog box containing a given component.
  43719. This will open and display a DialogWindow containing a given component, returning
  43720. when the user clicks its close button.
  43721. It returns the value that was returned by the dialog box's runModalLoop() call.
  43722. To close the dialog programatically, you should call exitModalState (returnValue) on
  43723. the DialogWindow that is created. To find a pointer to this window from your
  43724. contentComponent, you can do something like this:
  43725. @code
  43726. Dialogwindow* dw = contentComponent->findParentComponentOfClass ((DialogWindow*) 0);
  43727. if (dw != 0)
  43728. dw->exitModalState (1234);
  43729. @endcode
  43730. @param dialogTitle the dialog box's title
  43731. @param contentComponent the content component for the dialog box. Make sure
  43732. that this has been set to the size you want it to
  43733. be before calling this method. The component won't
  43734. be deleted by this call, so you can re-use it or delete
  43735. it afterwards
  43736. @param componentToCentreAround if this is non-zero, it indicates a component that
  43737. you'd like to show this dialog box in front of. See the
  43738. DocumentWindow::centreAroundComponent() method for more
  43739. info on this parameter
  43740. @param backgroundColour a colour to use for the dialog box's background colour
  43741. @param escapeKeyTriggersCloseButton if true, then pressing the escape key will cause the
  43742. close button to be triggered
  43743. @param shouldBeResizable if true, the dialog window has either a resizable border, or
  43744. a corner resizer
  43745. @param useBottomRightCornerResizer if shouldBeResizable is true, this indicates whether
  43746. to use a border or corner resizer component. See ResizableWindow::setResizable()
  43747. */
  43748. static int showModalDialog (const String& dialogTitle,
  43749. Component* contentComponent,
  43750. Component* componentToCentreAround,
  43751. const Colour& backgroundColour,
  43752. bool escapeKeyTriggersCloseButton,
  43753. bool shouldBeResizable = false,
  43754. bool useBottomRightCornerResizer = false);
  43755. juce_UseDebuggingNewOperator
  43756. protected:
  43757. /** @internal */
  43758. void resized();
  43759. private:
  43760. bool escapeKeyTriggersCloseButton;
  43761. DialogWindow (const DialogWindow&);
  43762. DialogWindow& operator= (const DialogWindow&);
  43763. };
  43764. #endif // __JUCE_DIALOGWINDOW_JUCEHEADER__
  43765. /*** End of inlined file: juce_DialogWindow.h ***/
  43766. #endif
  43767. #ifndef __JUCE_DOCUMENTWINDOW_JUCEHEADER__
  43768. #endif
  43769. #ifndef __JUCE_RESIZABLEWINDOW_JUCEHEADER__
  43770. #endif
  43771. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43772. /*** Start of inlined file: juce_SplashScreen.h ***/
  43773. #ifndef __JUCE_SPLASHSCREEN_JUCEHEADER__
  43774. #define __JUCE_SPLASHSCREEN_JUCEHEADER__
  43775. /** A component for showing a splash screen while your app starts up.
  43776. This will automatically position itself, and delete itself when the app has
  43777. finished initialising (it uses the JUCEApplication::isInitialising() to detect
  43778. this).
  43779. To use it, just create one of these in your JUCEApplication::initialise() method,
  43780. call its show() method and let the object delete itself later.
  43781. E.g. @code
  43782. void MyApp::initialise (const String& commandLine)
  43783. {
  43784. SplashScreen* splash = new SplashScreen();
  43785. splash->show ("welcome to my app",
  43786. ImageCache::getFromFile (File ("/foobar/splash.jpg")),
  43787. 4000, false);
  43788. .. no need to delete the splash screen - it'll do that itself.
  43789. }
  43790. @endcode
  43791. */
  43792. class JUCE_API SplashScreen : public Component,
  43793. public Timer,
  43794. private DeletedAtShutdown
  43795. {
  43796. public:
  43797. /** Creates a SplashScreen object.
  43798. After creating one of these (or your subclass of it), call one of the show()
  43799. methods to display it.
  43800. */
  43801. SplashScreen();
  43802. /** Destructor. */
  43803. ~SplashScreen();
  43804. /** Creates a SplashScreen object that will display an image.
  43805. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43806. screen. This method will also dispatch any pending messages to make sure that when
  43807. it returns, the splash screen has been completely drawn, and your initialisation
  43808. code can carry on.
  43809. @param title the name to give the component
  43810. @param backgroundImage an image to draw on the component. The component's size
  43811. will be set to the size of this image, and if the image is
  43812. semi-transparent, the component will be made semi-transparent
  43813. too. This image will be deleted (or released from the ImageCache
  43814. if that's how it was created) by the splash screen object when
  43815. it is itself deleted.
  43816. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43817. should stay visible for. If the initialisation takes longer than
  43818. this time, the splash screen will wait for it to finish before
  43819. disappearing, but if initialisation is very quick, this lets
  43820. you make sure that people get a good look at your splash.
  43821. @param useDropShadow if true, the window will have a drop shadow
  43822. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43823. the mouse (anywhere)
  43824. */
  43825. void show (const String& title,
  43826. const Image& backgroundImage,
  43827. int minimumTimeToDisplayFor,
  43828. bool useDropShadow,
  43829. bool removeOnMouseClick = true);
  43830. /** Creates a SplashScreen object with a specified size.
  43831. For a custom splash screen, you can use this method to display it at a certain size
  43832. and then override the paint() method yourself to do whatever's necessary.
  43833. As soon as this is called, the SplashScreen will be displayed in the centre of the
  43834. screen. This method will also dispatch any pending messages to make sure that when
  43835. it returns, the splash screen has been completely drawn, and your initialisation
  43836. code can carry on.
  43837. @param title the name to give the component
  43838. @param width the width to use
  43839. @param height the height to use
  43840. @param minimumTimeToDisplayFor how long (in milliseconds) the splash screen
  43841. should stay visible for. If the initialisation takes longer than
  43842. this time, the splash screen will wait for it to finish before
  43843. disappearing, but if initialisation is very quick, this lets
  43844. you make sure that people get a good look at your splash.
  43845. @param useDropShadow if true, the window will have a drop shadow
  43846. @param removeOnMouseClick if true, the window will go away as soon as the user clicks
  43847. the mouse (anywhere)
  43848. */
  43849. void show (const String& title,
  43850. int width,
  43851. int height,
  43852. int minimumTimeToDisplayFor,
  43853. bool useDropShadow,
  43854. bool removeOnMouseClick = true);
  43855. /** @internal */
  43856. void paint (Graphics& g);
  43857. /** @internal */
  43858. void timerCallback();
  43859. juce_UseDebuggingNewOperator
  43860. private:
  43861. Image backgroundImage;
  43862. Time earliestTimeToDelete;
  43863. int originalClickCounter;
  43864. SplashScreen (const SplashScreen&);
  43865. SplashScreen& operator= (const SplashScreen&);
  43866. };
  43867. #endif // __JUCE_SPLASHSCREEN_JUCEHEADER__
  43868. /*** End of inlined file: juce_SplashScreen.h ***/
  43869. #endif
  43870. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43871. /*** Start of inlined file: juce_ThreadWithProgressWindow.h ***/
  43872. #ifndef __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43873. #define __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43874. /**
  43875. A thread that automatically pops up a modal dialog box with a progress bar
  43876. and cancel button while it's busy running.
  43877. These are handy for performing some sort of task while giving the user feedback
  43878. about how long there is to go, etc.
  43879. E.g. @code
  43880. class MyTask : public ThreadWithProgressWindow
  43881. {
  43882. public:
  43883. MyTask() : ThreadWithProgressWindow ("busy...", true, true)
  43884. {
  43885. }
  43886. ~MyTask()
  43887. {
  43888. }
  43889. void run()
  43890. {
  43891. for (int i = 0; i < thingsToDo; ++i)
  43892. {
  43893. // must check this as often as possible, because this is
  43894. // how we know if the user's pressed 'cancel'
  43895. if (threadShouldExit())
  43896. break;
  43897. // this will update the progress bar on the dialog box
  43898. setProgress (i / (double) thingsToDo);
  43899. // ... do the business here...
  43900. }
  43901. }
  43902. };
  43903. void doTheTask()
  43904. {
  43905. MyTask m;
  43906. if (m.runThread())
  43907. {
  43908. // thread finished normally..
  43909. }
  43910. else
  43911. {
  43912. // user pressed the cancel button..
  43913. }
  43914. }
  43915. @endcode
  43916. @see Thread, AlertWindow
  43917. */
  43918. class JUCE_API ThreadWithProgressWindow : public Thread,
  43919. private Timer
  43920. {
  43921. public:
  43922. /** Creates the thread.
  43923. Initially, the dialog box won't be visible, it'll only appear when the
  43924. runThread() method is called.
  43925. @param windowTitle the title to go at the top of the dialog box
  43926. @param hasProgressBar whether the dialog box should have a progress bar (see
  43927. setProgress() )
  43928. @param hasCancelButton whether the dialog box should have a cancel button
  43929. @param timeOutMsWhenCancelling when 'cancel' is pressed, this is how long to wait for
  43930. the thread to stop before killing it forcibly (see
  43931. Thread::stopThread() )
  43932. @param cancelButtonText the text that should be shown in the cancel button
  43933. (if it has one)
  43934. */
  43935. ThreadWithProgressWindow (const String& windowTitle,
  43936. bool hasProgressBar,
  43937. bool hasCancelButton,
  43938. int timeOutMsWhenCancelling = 10000,
  43939. const String& cancelButtonText = "Cancel");
  43940. /** Destructor. */
  43941. ~ThreadWithProgressWindow();
  43942. /** Starts the thread and waits for it to finish.
  43943. This will start the thread, make the dialog box appear, and wait until either
  43944. the thread finishes normally, or until the cancel button is pressed.
  43945. Before returning, the dialog box will be hidden.
  43946. @param threadPriority the priority to use when starting the thread - see
  43947. Thread::startThread() for values
  43948. @returns true if the thread finished normally; false if the user pressed cancel
  43949. */
  43950. bool runThread (int threadPriority = 5);
  43951. /** The thread should call this periodically to update the position of the progress bar.
  43952. @param newProgress the progress, from 0.0 to 1.0
  43953. @see setStatusMessage
  43954. */
  43955. void setProgress (double newProgress);
  43956. /** The thread can call this to change the message that's displayed in the dialog box.
  43957. */
  43958. void setStatusMessage (const String& newStatusMessage);
  43959. /** Returns the AlertWindow that is being used.
  43960. */
  43961. AlertWindow* getAlertWindow() const throw() { return alertWindow; }
  43962. juce_UseDebuggingNewOperator
  43963. private:
  43964. void timerCallback();
  43965. double progress;
  43966. ScopedPointer <AlertWindow> alertWindow;
  43967. String message;
  43968. CriticalSection messageLock;
  43969. const int timeOutMsWhenCancelling;
  43970. ThreadWithProgressWindow (const ThreadWithProgressWindow&);
  43971. ThreadWithProgressWindow& operator= (const ThreadWithProgressWindow&);
  43972. };
  43973. #endif // __JUCE_THREADWITHPROGRESSWINDOW_JUCEHEADER__
  43974. /*** End of inlined file: juce_ThreadWithProgressWindow.h ***/
  43975. #endif
  43976. #ifndef __JUCE_TOOLTIPWINDOW_JUCEHEADER__
  43977. #endif
  43978. #ifndef __JUCE_TOPLEVELWINDOW_JUCEHEADER__
  43979. #endif
  43980. #ifndef __JUCE_COLOUR_JUCEHEADER__
  43981. #endif
  43982. #ifndef __JUCE_COLOURGRADIENT_JUCEHEADER__
  43983. #endif
  43984. #ifndef __JUCE_COLOURS_JUCEHEADER__
  43985. #endif
  43986. #ifndef __JUCE_PIXELFORMATS_JUCEHEADER__
  43987. #endif
  43988. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43989. /*** Start of inlined file: juce_EdgeTable.h ***/
  43990. #ifndef __JUCE_EDGETABLE_JUCEHEADER__
  43991. #define __JUCE_EDGETABLE_JUCEHEADER__
  43992. class Path;
  43993. class Image;
  43994. /**
  43995. A table of horizontal scan-line segments - used for rasterising Paths.
  43996. @see Path, Graphics
  43997. */
  43998. class JUCE_API EdgeTable
  43999. {
  44000. public:
  44001. /** Creates an edge table containing a path.
  44002. A table is created with a fixed vertical range, and only sections of the path
  44003. which lie within this range will be added to the table.
  44004. @param clipLimits only the region of the path that lies within this area will be added
  44005. @param pathToAdd the path to add to the table
  44006. @param transform a transform to apply to the path being added
  44007. */
  44008. EdgeTable (const Rectangle<int>& clipLimits,
  44009. const Path& pathToAdd,
  44010. const AffineTransform& transform);
  44011. /** Creates an edge table containing a rectangle.
  44012. */
  44013. EdgeTable (const Rectangle<int>& rectangleToAdd);
  44014. /** Creates an edge table containing a rectangle list.
  44015. */
  44016. EdgeTable (const RectangleList& rectanglesToAdd);
  44017. /** Creates an edge table containing a rectangle.
  44018. */
  44019. EdgeTable (const Rectangle<float>& rectangleToAdd);
  44020. /** Creates a copy of another edge table. */
  44021. EdgeTable (const EdgeTable& other);
  44022. /** Copies from another edge table. */
  44023. EdgeTable& operator= (const EdgeTable& other);
  44024. /** Destructor. */
  44025. ~EdgeTable();
  44026. void clipToRectangle (const Rectangle<int>& r) throw();
  44027. void excludeRectangle (const Rectangle<int>& r) throw();
  44028. void clipToEdgeTable (const EdgeTable& other);
  44029. void clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw();
  44030. bool isEmpty() throw();
  44031. const Rectangle<int>& getMaximumBounds() const throw() { return bounds; }
  44032. void translate (float dx, int dy) throw();
  44033. /** Reduces the amount of space the table has allocated.
  44034. This will shrink the table down to use as little memory as possible - useful for
  44035. read-only tables that get stored and re-used for rendering.
  44036. */
  44037. void optimiseTable() throw();
  44038. /** Iterates the lines in the table, for rendering.
  44039. This function will iterate each line in the table, and call a user-defined class
  44040. to render each pixel or continuous line of pixels that the table contains.
  44041. @param iterationCallback this templated class must contain the following methods:
  44042. @code
  44043. inline void setEdgeTableYPos (int y);
  44044. inline void handleEdgeTablePixel (int x, int alphaLevel) const;
  44045. inline void handleEdgeTablePixelFull (int x) const;
  44046. inline void handleEdgeTableLine (int x, int width, int alphaLevel) const;
  44047. inline void handleEdgeTableLineFull (int x, int width) const;
  44048. @endcode
  44049. (these don't necessarily have to be 'const', but it might help it go faster)
  44050. */
  44051. template <class EdgeTableIterationCallback>
  44052. void iterate (EdgeTableIterationCallback& iterationCallback) const throw()
  44053. {
  44054. const int* lineStart = table;
  44055. for (int y = 0; y < bounds.getHeight(); ++y)
  44056. {
  44057. const int* line = lineStart;
  44058. lineStart += lineStrideElements;
  44059. int numPoints = line[0];
  44060. if (--numPoints > 0)
  44061. {
  44062. int x = *++line;
  44063. jassert ((x >> 8) >= bounds.getX() && (x >> 8) < bounds.getRight());
  44064. int levelAccumulator = 0;
  44065. iterationCallback.setEdgeTableYPos (bounds.getY() + y);
  44066. while (--numPoints >= 0)
  44067. {
  44068. const int level = *++line;
  44069. jassert (((unsigned int) level) < (unsigned int) 256);
  44070. const int endX = *++line;
  44071. jassert (endX >= x);
  44072. const int endOfRun = (endX >> 8);
  44073. if (endOfRun == (x >> 8))
  44074. {
  44075. // small segment within the same pixel, so just save it for the next
  44076. // time round..
  44077. levelAccumulator += (endX - x) * level;
  44078. }
  44079. else
  44080. {
  44081. // plot the fist pixel of this segment, including any accumulated
  44082. // levels from smaller segments that haven't been drawn yet
  44083. levelAccumulator += (0xff - (x & 0xff)) * level;
  44084. levelAccumulator >>= 8;
  44085. x >>= 8;
  44086. if (levelAccumulator > 0)
  44087. {
  44088. if (levelAccumulator >> 8)
  44089. iterationCallback.handleEdgeTablePixelFull (x);
  44090. else
  44091. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  44092. }
  44093. // if there's a run of similar pixels, do it all in one go..
  44094. if (level > 0)
  44095. {
  44096. jassert (endOfRun <= bounds.getRight());
  44097. const int numPix = endOfRun - ++x;
  44098. if (numPix > 0)
  44099. iterationCallback.handleEdgeTableLine (x, numPix, level);
  44100. }
  44101. // save the bit at the end to be drawn next time round the loop.
  44102. levelAccumulator = (endX & 0xff) * level;
  44103. }
  44104. x = endX;
  44105. }
  44106. levelAccumulator >>= 8;
  44107. if (levelAccumulator > 0)
  44108. {
  44109. x >>= 8;
  44110. jassert (x >= bounds.getX() && x < bounds.getRight());
  44111. if (levelAccumulator >> 8)
  44112. iterationCallback.handleEdgeTablePixelFull (x);
  44113. else
  44114. iterationCallback.handleEdgeTablePixel (x, levelAccumulator);
  44115. }
  44116. }
  44117. }
  44118. }
  44119. juce_UseDebuggingNewOperator
  44120. private:
  44121. // table line format: number of points; point0 x, point0 levelDelta, point1 x, point1 levelDelta, etc
  44122. HeapBlock<int> table;
  44123. Rectangle<int> bounds;
  44124. int maxEdgesPerLine, lineStrideElements;
  44125. bool needToCheckEmptinesss;
  44126. void addEdgePoint (int x, int y, int winding) throw();
  44127. void remapTableForNumEdges (int newNumEdgesPerLine) throw();
  44128. void intersectWithEdgeTableLine (int y, const int* otherLine) throw();
  44129. void clipEdgeTableLineToRange (int* line, int x1, int x2) throw();
  44130. void sanitiseLevels (bool useNonZeroWinding) throw();
  44131. static void copyEdgeTableData (int* dest, int destLineStride, const int* src, int srcLineStride, int numLines) throw();
  44132. };
  44133. #endif // __JUCE_EDGETABLE_JUCEHEADER__
  44134. /*** End of inlined file: juce_EdgeTable.h ***/
  44135. #endif
  44136. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  44137. /*** Start of inlined file: juce_FillType.h ***/
  44138. #ifndef __JUCE_FILLTYPE_JUCEHEADER__
  44139. #define __JUCE_FILLTYPE_JUCEHEADER__
  44140. /**
  44141. Represents a colour or fill pattern to use for rendering paths.
  44142. This is used by the Graphics and DrawablePath classes as a way to encapsulate
  44143. a brush type. It can either be a solid colour, a gradient, or a tiled image.
  44144. @see Graphics::setFillType, DrawablePath::setFill
  44145. */
  44146. class JUCE_API FillType
  44147. {
  44148. public:
  44149. /** Creates a default fill type, of solid black. */
  44150. FillType() throw();
  44151. /** Creates a fill type of a solid colour.
  44152. @see setColour
  44153. */
  44154. FillType (const Colour& colour) throw();
  44155. /** Creates a gradient fill type.
  44156. @see setGradient
  44157. */
  44158. FillType (const ColourGradient& gradient);
  44159. /** Creates a tiled image fill type. The transform allows you to set the scaling, offset
  44160. and rotation of the pattern.
  44161. @see setTiledImage
  44162. */
  44163. FillType (const Image& image, const AffineTransform& transform) throw();
  44164. /** Creates a copy of another FillType. */
  44165. FillType (const FillType& other);
  44166. /** Makes a copy of another FillType. */
  44167. FillType& operator= (const FillType& other);
  44168. /** Destructor. */
  44169. ~FillType() throw();
  44170. /** Returns true if this is a solid colour fill, and not a gradient or image. */
  44171. bool isColour() const throw() { return gradient == 0 && image.isNull(); }
  44172. /** Returns true if this is a gradient fill. */
  44173. bool isGradient() const throw() { return gradient != 0; }
  44174. /** Returns true if this is a tiled image pattern fill. */
  44175. bool isTiledImage() const throw() { return image.isValid(); }
  44176. /** Turns this object into a solid colour fill.
  44177. If the object was an image or gradient, those fields will no longer be valid. */
  44178. void setColour (const Colour& newColour) throw();
  44179. /** Turns this object into a gradient fill. */
  44180. void setGradient (const ColourGradient& newGradient);
  44181. /** Turns this object into a tiled image fill type. The transform allows you to set
  44182. the scaling, offset and rotation of the pattern.
  44183. */
  44184. void setTiledImage (const Image& image, const AffineTransform& transform) throw();
  44185. /** Changes the opacity that should be used.
  44186. If the fill is a solid colour, this just changes the opacity of that colour. For
  44187. gradients and image tiles, it changes the opacity that will be used for them.
  44188. */
  44189. void setOpacity (float newOpacity) throw();
  44190. /** Returns the current opacity to be applied to the colour, gradient, or image.
  44191. @see setOpacity
  44192. */
  44193. float getOpacity() const throw() { return colour.getFloatAlpha(); }
  44194. /** Returns true if this fill type is completely transparent. */
  44195. bool isInvisible() const throw();
  44196. bool operator== (const FillType& other) const;
  44197. bool operator!= (const FillType& other) const;
  44198. /** The solid colour being used.
  44199. If the fill type is not a solid colour, the alpha channel of this colour indicates
  44200. the opacity that should be used for the fill, and the RGB channels are ignored.
  44201. */
  44202. Colour colour;
  44203. /** Returns the gradient that should be used for filling.
  44204. This will be zero if the object is some other type of fill.
  44205. If a gradient is active, the overall opacity with which it should be applied
  44206. is indicated by the alpha channel of the colour variable.
  44207. */
  44208. ScopedPointer <ColourGradient> gradient;
  44209. /** The image that should be used for tiling.
  44210. If an image fill is active, the overall opacity with which it should be applied
  44211. is indicated by the alpha channel of the colour variable.
  44212. */
  44213. Image image;
  44214. /** The transform that should be applied to the image or gradient that's being drawn.
  44215. */
  44216. AffineTransform transform;
  44217. juce_UseDebuggingNewOperator
  44218. };
  44219. #endif // __JUCE_FILLTYPE_JUCEHEADER__
  44220. /*** End of inlined file: juce_FillType.h ***/
  44221. #endif
  44222. #ifndef __JUCE_GRAPHICS_JUCEHEADER__
  44223. #endif
  44224. #ifndef __JUCE_JUSTIFICATION_JUCEHEADER__
  44225. #endif
  44226. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44227. /*** Start of inlined file: juce_LowLevelGraphicsContext.h ***/
  44228. #ifndef __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44229. #define __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44230. /**
  44231. Interface class for graphics context objects, used internally by the Graphics class.
  44232. Users are not supposed to create instances of this class directly - do your drawing
  44233. via the Graphics object instead.
  44234. It's a base class for different types of graphics context, that may perform software-based
  44235. or OS-accelerated rendering.
  44236. E.g. the LowLevelGraphicsSoftwareRenderer renders onto an image in memory, but other
  44237. subclasses could render directly to a windows HDC, a Quartz context, or an OpenGL
  44238. context.
  44239. */
  44240. class JUCE_API LowLevelGraphicsContext
  44241. {
  44242. protected:
  44243. LowLevelGraphicsContext();
  44244. public:
  44245. virtual ~LowLevelGraphicsContext();
  44246. /** Returns true if this device is vector-based, e.g. a printer. */
  44247. virtual bool isVectorDevice() const = 0;
  44248. /** Moves the origin to a new position.
  44249. The co-ords are relative to the current origin, and indicate the new position
  44250. of (0, 0).
  44251. */
  44252. virtual void setOrigin (int x, int y) = 0;
  44253. virtual bool clipToRectangle (const Rectangle<int>& r) = 0;
  44254. virtual bool clipToRectangleList (const RectangleList& clipRegion) = 0;
  44255. virtual void excludeClipRectangle (const Rectangle<int>& r) = 0;
  44256. virtual void clipToPath (const Path& path, const AffineTransform& transform) = 0;
  44257. virtual void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform) = 0;
  44258. virtual bool clipRegionIntersects (const Rectangle<int>& r) = 0;
  44259. virtual const Rectangle<int> getClipBounds() const = 0;
  44260. virtual bool isClipEmpty() const = 0;
  44261. virtual void saveState() = 0;
  44262. virtual void restoreState() = 0;
  44263. virtual void setFill (const FillType& fillType) = 0;
  44264. virtual void setOpacity (float newOpacity) = 0;
  44265. virtual void setInterpolationQuality (Graphics::ResamplingQuality quality) = 0;
  44266. virtual void fillRect (const Rectangle<int>& r, bool replaceExistingContents) = 0;
  44267. virtual void fillPath (const Path& path, const AffineTransform& transform) = 0;
  44268. virtual void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  44269. const AffineTransform& transform, bool fillEntireClipAsTiles) = 0;
  44270. virtual void drawLine (const Line <float>& line) = 0;
  44271. virtual void drawVerticalLine (int x, float top, float bottom) = 0;
  44272. virtual void drawHorizontalLine (int y, float left, float right) = 0;
  44273. virtual void setFont (const Font& newFont) = 0;
  44274. virtual const Font getFont() = 0;
  44275. virtual void drawGlyph (int glyphNumber, const AffineTransform& transform) = 0;
  44276. };
  44277. #endif // __JUCE_LOWLEVELGRAPHICSCONTEXT_JUCEHEADER__
  44278. /*** End of inlined file: juce_LowLevelGraphicsContext.h ***/
  44279. #endif
  44280. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44281. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  44282. #ifndef __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44283. #define __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44284. /**
  44285. An implementation of LowLevelGraphicsContext that turns the drawing operations
  44286. into a PostScript document.
  44287. */
  44288. class JUCE_API LowLevelGraphicsPostScriptRenderer : public LowLevelGraphicsContext
  44289. {
  44290. public:
  44291. LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  44292. const String& documentTitle,
  44293. int totalWidth,
  44294. int totalHeight);
  44295. ~LowLevelGraphicsPostScriptRenderer();
  44296. bool isVectorDevice() const;
  44297. void setOrigin (int x, int y);
  44298. bool clipToRectangle (const Rectangle<int>& r);
  44299. bool clipToRectangleList (const RectangleList& clipRegion);
  44300. void excludeClipRectangle (const Rectangle<int>& r);
  44301. void clipToPath (const Path& path, const AffineTransform& transform);
  44302. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  44303. void saveState();
  44304. void restoreState();
  44305. bool clipRegionIntersects (const Rectangle<int>& r);
  44306. const Rectangle<int> getClipBounds() const;
  44307. bool isClipEmpty() const;
  44308. void setFill (const FillType& fillType);
  44309. void setOpacity (float opacity);
  44310. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  44311. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  44312. void fillPath (const Path& path, const AffineTransform& transform);
  44313. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  44314. const AffineTransform& transform, bool fillEntireClipAsTiles);
  44315. void drawLine (const Line <float>& line);
  44316. void drawVerticalLine (int x, float top, float bottom);
  44317. void drawHorizontalLine (int x, float top, float bottom);
  44318. const Font getFont();
  44319. void setFont (const Font& newFont);
  44320. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  44321. juce_UseDebuggingNewOperator
  44322. protected:
  44323. OutputStream& out;
  44324. int totalWidth, totalHeight;
  44325. bool needToClip;
  44326. Colour lastColour;
  44327. struct SavedState
  44328. {
  44329. SavedState();
  44330. ~SavedState();
  44331. RectangleList clip;
  44332. int xOffset, yOffset;
  44333. FillType fillType;
  44334. Font font;
  44335. private:
  44336. SavedState& operator= (const SavedState&);
  44337. };
  44338. OwnedArray <SavedState> stateStack;
  44339. void writeClip();
  44340. void writeColour (const Colour& colour);
  44341. void writePath (const Path& path) const;
  44342. void writeXY (float x, float y) const;
  44343. void writeTransform (const AffineTransform& trans) const;
  44344. void writeImage (const Image& im, int sx, int sy, int maxW, int maxH) const;
  44345. LowLevelGraphicsPostScriptRenderer (const LowLevelGraphicsPostScriptRenderer& other);
  44346. LowLevelGraphicsPostScriptRenderer& operator= (const LowLevelGraphicsPostScriptRenderer&);
  44347. };
  44348. #endif // __JUCE_LOWLEVELGRAPHICSPOSTSCRIPTRENDERER_JUCEHEADER__
  44349. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.h ***/
  44350. #endif
  44351. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44352. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  44353. #ifndef __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44354. #define __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44355. /**
  44356. A lowest-common-denominator implementation of LowLevelGraphicsContext that does all
  44357. its rendering in memory.
  44358. User code is not supposed to create instances of this class directly - do all your
  44359. rendering via the Graphics class instead.
  44360. */
  44361. class JUCE_API LowLevelGraphicsSoftwareRenderer : public LowLevelGraphicsContext
  44362. {
  44363. public:
  44364. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn);
  44365. LowLevelGraphicsSoftwareRenderer (const Image& imageToRenderOn, int xOffset, int yOffset, const RectangleList& initialClip);
  44366. ~LowLevelGraphicsSoftwareRenderer();
  44367. bool isVectorDevice() const;
  44368. void setOrigin (int x, int y);
  44369. bool clipToRectangle (const Rectangle<int>& r);
  44370. bool clipToRectangleList (const RectangleList& clipRegion);
  44371. void excludeClipRectangle (const Rectangle<int>& r);
  44372. void clipToPath (const Path& path, const AffineTransform& transform);
  44373. void clipToImageAlpha (const Image& sourceImage, const Rectangle<int>& srcClip, const AffineTransform& transform);
  44374. bool clipRegionIntersects (const Rectangle<int>& r);
  44375. const Rectangle<int> getClipBounds() const;
  44376. bool isClipEmpty() const;
  44377. void saveState();
  44378. void restoreState();
  44379. void setFill (const FillType& fillType);
  44380. void setOpacity (float opacity);
  44381. void setInterpolationQuality (Graphics::ResamplingQuality quality);
  44382. void fillRect (const Rectangle<int>& r, bool replaceExistingContents);
  44383. void fillPath (const Path& path, const AffineTransform& transform);
  44384. void drawImage (const Image& sourceImage, const Rectangle<int>& srcClip,
  44385. const AffineTransform& transform, bool fillEntireClipAsTiles);
  44386. void drawLine (const Line <float>& line);
  44387. void drawVerticalLine (int x, float top, float bottom);
  44388. void drawHorizontalLine (int x, float top, float bottom);
  44389. void setFont (const Font& newFont);
  44390. const Font getFont();
  44391. void drawGlyph (int glyphNumber, float x, float y);
  44392. void drawGlyph (int glyphNumber, const AffineTransform& transform);
  44393. juce_UseDebuggingNewOperator
  44394. protected:
  44395. Image image;
  44396. class GlyphCache;
  44397. class CachedGlyph;
  44398. class SavedState;
  44399. friend class ScopedPointer <SavedState>;
  44400. friend class OwnedArray <SavedState>;
  44401. friend class OwnedArray <CachedGlyph>;
  44402. ScopedPointer <SavedState> currentState;
  44403. OwnedArray <SavedState> stateStack;
  44404. LowLevelGraphicsSoftwareRenderer (const LowLevelGraphicsSoftwareRenderer& other);
  44405. LowLevelGraphicsSoftwareRenderer& operator= (const LowLevelGraphicsSoftwareRenderer&);
  44406. };
  44407. #endif // __JUCE_LOWLEVELGRAPHICSSOFTWARERENDERER_JUCEHEADER__
  44408. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.h ***/
  44409. #endif
  44410. #ifndef __JUCE_RECTANGLEPLACEMENT_JUCEHEADER__
  44411. #endif
  44412. #ifndef __JUCE_DRAWABLE_JUCEHEADER__
  44413. #endif
  44414. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44415. /*** Start of inlined file: juce_DrawableComposite.h ***/
  44416. #ifndef __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44417. #define __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44418. /**
  44419. A drawable object which acts as a container for a set of other Drawables.
  44420. @see Drawable
  44421. */
  44422. class JUCE_API DrawableComposite : public Drawable,
  44423. public RelativeCoordinate::NamedCoordinateFinder
  44424. {
  44425. public:
  44426. /** Creates a composite Drawable. */
  44427. DrawableComposite();
  44428. /** Creates a copy of a DrawableComposite. */
  44429. DrawableComposite (const DrawableComposite& other);
  44430. /** Destructor. */
  44431. ~DrawableComposite();
  44432. /** Adds a new sub-drawable to this one.
  44433. This passes in a Drawable pointer for this object to look after. To add a copy
  44434. of a drawable, use the form of this method that takes a Drawable reference instead.
  44435. @param drawable the object to add - this will be deleted automatically
  44436. when no longer needed, so the caller mustn't keep any
  44437. pointers to it.
  44438. @param index where to insert it in the list of drawables. 0 is the back,
  44439. -1 is the front, or any value from 0 and getNumDrawables()
  44440. can be used
  44441. @see removeDrawable
  44442. */
  44443. void insertDrawable (Drawable* drawable, int index = -1);
  44444. /** Adds a new sub-drawable to this one.
  44445. This takes a copy of a Drawable and adds it to this object. To pass in a Drawable
  44446. for this object to look after, use the form of this method that takes a Drawable
  44447. pointer instead.
  44448. @param drawable the object to add - an internal copy will be made of this object
  44449. @param index where to insert it in the list of drawables. 0 is the back,
  44450. -1 is the front, or any value from 0 and getNumDrawables()
  44451. can be used
  44452. @see removeDrawable
  44453. */
  44454. void insertDrawable (const Drawable& drawable, int index = -1);
  44455. /** Deletes one of the Drawable objects.
  44456. @param index the index of the drawable to delete, between 0
  44457. and (getNumDrawables() - 1).
  44458. @param deleteDrawable if this is true, the drawable that is removed will also
  44459. be deleted. If false, it'll just be removed.
  44460. @see insertDrawable, getNumDrawables
  44461. */
  44462. void removeDrawable (int index, bool deleteDrawable = true);
  44463. /** Returns the number of drawables contained inside this one.
  44464. @see getDrawable
  44465. */
  44466. int getNumDrawables() const throw() { return drawables.size(); }
  44467. /** Returns one of the drawables that are contained in this one.
  44468. Each drawable also has a transform associated with it - you can use getDrawableTransform()
  44469. to find it.
  44470. The pointer returned is managed by this object and will be deleted when no longer
  44471. needed, so be careful what you do with it.
  44472. @see getNumDrawables
  44473. */
  44474. Drawable* getDrawable (int index) const throw() { return drawables [index]; }
  44475. /** Looks for a child drawable with the specified name. */
  44476. Drawable* getDrawableWithName (const String& name) const throw();
  44477. /** Brings one of the Drawables to the front.
  44478. @param index the index of the drawable to move, between 0
  44479. and (getNumDrawables() - 1).
  44480. @see insertDrawable, getNumDrawables
  44481. */
  44482. void bringToFront (int index);
  44483. /** Changes the main content area.
  44484. The content area is actually defined by the markers named "left", "right", "top" and
  44485. "bottom", but this method is a shortcut that sets them all at once.
  44486. @see contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44487. */
  44488. const RelativeRectangle getContentArea() const;
  44489. /** Returns the main content rectangle.
  44490. The content area is actually defined by the markers named "left", "right", "top" and
  44491. "bottom", but this method is a shortcut that returns them all at once.
  44492. @see setBoundingBox, contentLeftMarkerName, contentRightMarkerName, contentTopMarkerName, contentBottomMarkerName
  44493. */
  44494. void setContentArea (const RelativeRectangle& newArea);
  44495. /** Sets the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44496. @see setContentArea
  44497. */
  44498. void setBoundingBox (const RelativeParallelogram& newBoundingBox);
  44499. /** Returns the parallelogram that defines the target position of the content rectangle when the drawable is rendered.
  44500. @see setBoundingBox
  44501. */
  44502. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44503. /** Changes the bounding box transform to match the content area, so that any sub-items will
  44504. be drawn at their untransformed positions.
  44505. */
  44506. void resetBoundingBoxToContentArea();
  44507. /** Resets the content area and the bounding transform to fit around the area occupied
  44508. by the child components (ignoring any markers).
  44509. */
  44510. void resetContentAreaAndBoundingBoxToFitChildren();
  44511. /** Represents a named marker position.
  44512. @see DrawableComposite::getMarker
  44513. */
  44514. struct Marker
  44515. {
  44516. Marker (const Marker&);
  44517. Marker (const String& name, const RelativeCoordinate& position);
  44518. bool operator!= (const Marker&) const throw();
  44519. String name;
  44520. RelativeCoordinate position;
  44521. };
  44522. int getNumMarkers (bool xAxis) const throw();
  44523. const Marker* getMarker (bool xAxis, int index) const throw();
  44524. void setMarker (const String& name, bool xAxis, const RelativeCoordinate& position);
  44525. void removeMarker (bool xAxis, int index);
  44526. /** The name of the marker that defines the left edge of the content area. */
  44527. static const char* const contentLeftMarkerName;
  44528. /** The name of the marker that defines the right edge of the content area. */
  44529. static const char* const contentRightMarkerName;
  44530. /** The name of the marker that defines the top edge of the content area. */
  44531. static const char* const contentTopMarkerName;
  44532. /** The name of the marker that defines the bottom edge of the content area. */
  44533. static const char* const contentBottomMarkerName;
  44534. /** @internal */
  44535. void render (const Drawable::RenderingContext& context) const;
  44536. /** @internal */
  44537. const Rectangle<float> getBounds() const;
  44538. /** @internal */
  44539. bool hitTest (float x, float y) const;
  44540. /** @internal */
  44541. Drawable* createCopy() const;
  44542. /** @internal */
  44543. void invalidatePoints();
  44544. /** @internal */
  44545. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44546. /** @internal */
  44547. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44548. /** @internal */
  44549. static const Identifier valueTreeType;
  44550. /** @internal */
  44551. const Identifier getValueTreeType() const { return valueTreeType; }
  44552. /** @internal */
  44553. const RelativeCoordinate findNamedCoordinate (const String& objectName, const String& edge) const;
  44554. /** Internally-used class for wrapping a DrawableComposite's state into a ValueTree. */
  44555. class ValueTreeWrapper : public ValueTreeWrapperBase
  44556. {
  44557. public:
  44558. ValueTreeWrapper (const ValueTree& state);
  44559. int getNumDrawables() const;
  44560. ValueTree getDrawableState (int index) const;
  44561. ValueTree getDrawableWithId (const String& objectId, bool recursive) const;
  44562. int indexOfDrawable (const ValueTree& item) const;
  44563. void addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager);
  44564. void moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager);
  44565. void removeDrawable (const ValueTree& child, UndoManager* undoManager);
  44566. const RelativeParallelogram getBoundingBox() const;
  44567. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44568. void resetBoundingBoxToContentArea (UndoManager* undoManager);
  44569. const RelativeRectangle getContentArea() const;
  44570. void setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager);
  44571. int getNumMarkers (bool xAxis) const;
  44572. const ValueTree getMarkerState (bool xAxis, int index) const;
  44573. const ValueTree getMarkerState (bool xAxis, const String& name) const;
  44574. bool containsMarker (bool xAxis, const ValueTree& state) const;
  44575. const Marker getMarker (bool xAxis, const ValueTree& state) const;
  44576. void setMarker (bool xAxis, const Marker& marker, UndoManager* undoManager);
  44577. void removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager);
  44578. static const Identifier nameProperty, posProperty;
  44579. private:
  44580. static const Identifier topLeft, topRight, bottomLeft, childGroupTag, markerGroupTagX,
  44581. markerGroupTagY, markerTag;
  44582. ValueTree getChildList() const;
  44583. ValueTree getChildListCreating (UndoManager* undoManager);
  44584. ValueTree getMarkerList (bool xAxis) const;
  44585. ValueTree getMarkerListCreating (bool xAxis, UndoManager* undoManager);
  44586. };
  44587. juce_UseDebuggingNewOperator
  44588. private:
  44589. OwnedArray <Drawable> drawables;
  44590. RelativeParallelogram bounds;
  44591. OwnedArray <Marker> markersX, markersY;
  44592. const Rectangle<float> getUntransformedBounds (bool includeMarkers) const;
  44593. const AffineTransform calculateTransform() const;
  44594. DrawableComposite& operator= (const DrawableComposite&);
  44595. };
  44596. #endif // __JUCE_DRAWABLECOMPOSITE_JUCEHEADER__
  44597. /*** End of inlined file: juce_DrawableComposite.h ***/
  44598. #endif
  44599. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44600. /*** Start of inlined file: juce_DrawableImage.h ***/
  44601. #ifndef __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44602. #define __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44603. /**
  44604. A drawable object which is a bitmap image.
  44605. @see Drawable
  44606. */
  44607. class JUCE_API DrawableImage : public Drawable
  44608. {
  44609. public:
  44610. DrawableImage();
  44611. DrawableImage (const DrawableImage& other);
  44612. /** Destructor. */
  44613. ~DrawableImage();
  44614. /** Sets the image that this drawable will render. */
  44615. void setImage (const Image& imageToUse);
  44616. /** Returns the current image. */
  44617. const Image getImage() const { return image; }
  44618. /** Sets the opacity to use when drawing the image. */
  44619. void setOpacity (float newOpacity);
  44620. /** Returns the image's opacity. */
  44621. float getOpacity() const throw() { return opacity; }
  44622. /** Sets a colour to draw over the image's alpha channel.
  44623. By default this is transparent so isn't drawn, but if you set a non-transparent
  44624. colour here, then it will be overlaid on the image, using the image's alpha
  44625. channel as a mask.
  44626. This is handy for doing things like darkening or lightening an image by overlaying
  44627. it with semi-transparent black or white.
  44628. */
  44629. void setOverlayColour (const Colour& newOverlayColour);
  44630. /** Returns the overlay colour. */
  44631. const Colour& getOverlayColour() const throw() { return overlayColour; }
  44632. /** Sets the bounding box within which the image should be displayed. */
  44633. void setBoundingBox (const RelativeParallelogram& newBounds);
  44634. /** Returns the position to which the image's top-left corner should be remapped in the target
  44635. coordinate space when rendering this object.
  44636. @see setTransform
  44637. */
  44638. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44639. /** @internal */
  44640. void render (const Drawable::RenderingContext& context) const;
  44641. /** @internal */
  44642. const Rectangle<float> getBounds() const;
  44643. /** @internal */
  44644. bool hitTest (float x, float y) const;
  44645. /** @internal */
  44646. Drawable* createCopy() const;
  44647. /** @internal */
  44648. void invalidatePoints();
  44649. /** @internal */
  44650. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44651. /** @internal */
  44652. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44653. /** @internal */
  44654. static const Identifier valueTreeType;
  44655. /** @internal */
  44656. const Identifier getValueTreeType() const { return valueTreeType; }
  44657. /** Internally-used class for wrapping a DrawableImage's state into a ValueTree. */
  44658. class ValueTreeWrapper : public ValueTreeWrapperBase
  44659. {
  44660. public:
  44661. ValueTreeWrapper (const ValueTree& state);
  44662. const var getImageIdentifier() const;
  44663. void setImageIdentifier (const var& newIdentifier, UndoManager* undoManager);
  44664. Value getImageIdentifierValue (UndoManager* undoManager);
  44665. float getOpacity() const;
  44666. void setOpacity (float newOpacity, UndoManager* undoManager);
  44667. Value getOpacityValue (UndoManager* undoManager);
  44668. const Colour getOverlayColour() const;
  44669. void setOverlayColour (const Colour& newColour, UndoManager* undoManager);
  44670. Value getOverlayColourValue (UndoManager* undoManager);
  44671. const RelativeParallelogram getBoundingBox() const;
  44672. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44673. static const Identifier opacity, overlay, image, topLeft, topRight, bottomLeft;
  44674. };
  44675. juce_UseDebuggingNewOperator
  44676. private:
  44677. Image image;
  44678. float opacity;
  44679. Colour overlayColour;
  44680. RelativeParallelogram bounds;
  44681. const AffineTransform calculateTransform() const;
  44682. DrawableImage& operator= (const DrawableImage&);
  44683. };
  44684. #endif // __JUCE_DRAWABLEIMAGE_JUCEHEADER__
  44685. /*** End of inlined file: juce_DrawableImage.h ***/
  44686. #endif
  44687. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44688. /*** Start of inlined file: juce_DrawablePath.h ***/
  44689. #ifndef __JUCE_DRAWABLEPATH_JUCEHEADER__
  44690. #define __JUCE_DRAWABLEPATH_JUCEHEADER__
  44691. /**
  44692. A drawable object which renders a filled or outlined shape.
  44693. @see Drawable
  44694. */
  44695. class JUCE_API DrawablePath : public Drawable
  44696. {
  44697. public:
  44698. /** Creates a DrawablePath. */
  44699. DrawablePath();
  44700. DrawablePath (const DrawablePath& other);
  44701. /** Destructor. */
  44702. ~DrawablePath();
  44703. /** Changes the path that will be drawn.
  44704. @see setFillColour, setStrokeType
  44705. */
  44706. void setPath (const Path& newPath);
  44707. /** Sets a fill type for the path.
  44708. This colour is used to fill the path - if you don't want the path to be
  44709. filled (e.g. if you're just drawing an outline), set this to a transparent
  44710. colour.
  44711. @see setPath, setStrokeFill
  44712. */
  44713. void setFill (const FillType& newFill);
  44714. /** Returns the current fill type.
  44715. @see setFill
  44716. */
  44717. const FillType& getFill() const throw() { return mainFill; }
  44718. /** Sets the fill type with which the outline will be drawn.
  44719. @see setFill
  44720. */
  44721. void setStrokeFill (const FillType& newStrokeFill);
  44722. /** Returns the current stroke fill.
  44723. @see setStrokeFill
  44724. */
  44725. const FillType& getStrokeFill() const throw() { return strokeFill; }
  44726. /** Changes the properties of the outline that will be drawn around the path.
  44727. If the stroke has 0 thickness, no stroke will be drawn.
  44728. @see setStrokeThickness, setStrokeColour
  44729. */
  44730. void setStrokeType (const PathStrokeType& newStrokeType);
  44731. /** Changes the stroke thickness.
  44732. This is a shortcut for calling setStrokeType.
  44733. */
  44734. void setStrokeThickness (float newThickness);
  44735. /** Returns the current outline style. */
  44736. const PathStrokeType& getStrokeType() const throw() { return strokeType; }
  44737. /** Returns the current path. */
  44738. const Path& getPath() const;
  44739. /** Returns the current path for the outline. */
  44740. const Path& getStrokePath() const;
  44741. /** @internal */
  44742. void render (const Drawable::RenderingContext& context) const;
  44743. /** @internal */
  44744. const Rectangle<float> getBounds() const;
  44745. /** @internal */
  44746. bool hitTest (float x, float y) const;
  44747. /** @internal */
  44748. Drawable* createCopy() const;
  44749. /** @internal */
  44750. void invalidatePoints();
  44751. /** @internal */
  44752. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44753. /** @internal */
  44754. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44755. /** @internal */
  44756. static const Identifier valueTreeType;
  44757. /** @internal */
  44758. const Identifier getValueTreeType() const { return valueTreeType; }
  44759. /** Internally-used class for wrapping a DrawablePath's state into a ValueTree. */
  44760. class ValueTreeWrapper : public ValueTreeWrapperBase
  44761. {
  44762. public:
  44763. ValueTreeWrapper (const ValueTree& state);
  44764. const FillType getMainFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44765. ImageProvider* imageProvider) const;
  44766. ValueTree getMainFillState();
  44767. void setMainFill (const FillType& newFill, const RelativePoint* gradientPoint1,
  44768. const RelativePoint* gradientPoint2, const RelativePoint* gradientPoint3,
  44769. ImageProvider* imageProvider, UndoManager* undoManager);
  44770. const FillType getStrokeFill (RelativeCoordinate::NamedCoordinateFinder* nameFinder,
  44771. ImageProvider* imageProvider) const;
  44772. ValueTree getStrokeFillState();
  44773. void setStrokeFill (const FillType& newFill, const RelativePoint* gradientPoint1,
  44774. const RelativePoint* gradientPoint2, const RelativePoint* gradientPoint3,
  44775. ImageProvider* imageProvider, UndoManager* undoManager);
  44776. const PathStrokeType getStrokeType() const;
  44777. void setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager);
  44778. bool usesNonZeroWinding() const;
  44779. void setUsesNonZeroWinding (bool b, UndoManager* undoManager);
  44780. class Element
  44781. {
  44782. public:
  44783. explicit Element (const ValueTree& state);
  44784. ~Element();
  44785. const Identifier getType() const throw() { return state.getType(); }
  44786. int getNumControlPoints() const throw();
  44787. const RelativePoint getControlPoint (int index) const;
  44788. Value getControlPointValue (int index, UndoManager* undoManager) const;
  44789. const RelativePoint getStartPoint() const;
  44790. const RelativePoint getEndPoint() const;
  44791. void setControlPoint (int index, const RelativePoint& point, UndoManager* undoManager);
  44792. float getLength (RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  44793. ValueTreeWrapper getParent() const;
  44794. Element getPreviousElement() const;
  44795. const String getModeOfEndPoint() const;
  44796. void setModeOfEndPoint (const String& newMode, UndoManager* undoManager);
  44797. void convertToLine (UndoManager* undoManager);
  44798. void convertToCubic (RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager);
  44799. void convertToPathBreak (UndoManager* undoManager);
  44800. ValueTree insertPoint (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder, UndoManager* undoManager);
  44801. void removePoint (UndoManager* undoManager);
  44802. float findProportionAlongLine (const Point<float>& targetPoint, RelativeCoordinate::NamedCoordinateFinder* nameFinder) const;
  44803. static const Identifier mode, startSubPathElement, closeSubPathElement,
  44804. lineToElement, quadraticToElement, cubicToElement;
  44805. static const char* cornerMode;
  44806. static const char* roundedMode;
  44807. static const char* symmetricMode;
  44808. ValueTree state;
  44809. };
  44810. ValueTree getPathState();
  44811. static const Identifier fill, stroke, path, jointStyle, capStyle, strokeWidth,
  44812. nonZeroWinding, point1, point2, point3;
  44813. };
  44814. juce_UseDebuggingNewOperator
  44815. private:
  44816. FillType mainFill, strokeFill;
  44817. PathStrokeType strokeType;
  44818. ScopedPointer<RelativePointPath> relativePath;
  44819. mutable Path path, stroke;
  44820. mutable bool pathNeedsUpdating, strokeNeedsUpdating;
  44821. void updatePath() const;
  44822. void updateStroke() const;
  44823. bool isStrokeVisible() const throw();
  44824. DrawablePath& operator= (const DrawablePath&);
  44825. };
  44826. #endif // __JUCE_DRAWABLEPATH_JUCEHEADER__
  44827. /*** End of inlined file: juce_DrawablePath.h ***/
  44828. #endif
  44829. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44830. /*** Start of inlined file: juce_DrawableText.h ***/
  44831. #ifndef __JUCE_DRAWABLETEXT_JUCEHEADER__
  44832. #define __JUCE_DRAWABLETEXT_JUCEHEADER__
  44833. /**
  44834. A drawable object which renders a line of text.
  44835. @see Drawable
  44836. */
  44837. class JUCE_API DrawableText : public Drawable
  44838. {
  44839. public:
  44840. /** Creates a DrawableText object. */
  44841. DrawableText();
  44842. DrawableText (const DrawableText& other);
  44843. /** Destructor. */
  44844. ~DrawableText();
  44845. /** Sets the text to display.*/
  44846. void setText (const String& newText);
  44847. /** Sets the colour of the text. */
  44848. void setColour (const Colour& newColour);
  44849. /** Returns the current text colour. */
  44850. const Colour& getColour() const throw() { return colour; }
  44851. /** Sets the font to use.
  44852. Note that the font height and horizontal scale are actually based upon the position
  44853. of the fontSizeAndScaleAnchor parameter to setBounds(). If applySizeAndScale is true, then
  44854. the height and scale control point will be moved to match the dimensions of the font supplied;
  44855. if it is false, then the new font's height and scale are ignored.
  44856. */
  44857. void setFont (const Font& newFont, bool applySizeAndScale);
  44858. /** Changes the justification of the text within the bounding box. */
  44859. void setJustification (const Justification& newJustification);
  44860. /** Returns the parallelogram that defines the text bounding box. */
  44861. const RelativeParallelogram& getBoundingBox() const throw() { return bounds; }
  44862. /** Sets the bounding box that contains the text. */
  44863. void setBoundingBox (const RelativeParallelogram& newBounds);
  44864. /** Returns the point within the bounds that defines the font's size and scale. */
  44865. const RelativePoint& getFontSizeControlPoint() const throw() { return fontSizeControlPoint; }
  44866. /** Sets the control point that defines the font's height and horizontal scale.
  44867. This position is a point within the bounding box parallelogram, whose Y position (relative
  44868. to the parallelogram's origin and possibly distorted shape) specifies the font's height,
  44869. and its X defines the font's horizontal scale.
  44870. */
  44871. void setFontSizeControlPoint (const RelativePoint& newPoint);
  44872. /** @internal */
  44873. void render (const Drawable::RenderingContext& context) const;
  44874. /** @internal */
  44875. const Rectangle<float> getBounds() const;
  44876. /** @internal */
  44877. bool hitTest (float x, float y) const;
  44878. /** @internal */
  44879. Drawable* createCopy() const;
  44880. /** @internal */
  44881. void invalidatePoints();
  44882. /** @internal */
  44883. const Rectangle<float> refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider);
  44884. /** @internal */
  44885. const ValueTree createValueTree (ImageProvider* imageProvider) const;
  44886. /** @internal */
  44887. static const Identifier valueTreeType;
  44888. /** @internal */
  44889. const Identifier getValueTreeType() const { return valueTreeType; }
  44890. /** Internally-used class for wrapping a DrawableText's state into a ValueTree. */
  44891. class ValueTreeWrapper : public ValueTreeWrapperBase
  44892. {
  44893. public:
  44894. ValueTreeWrapper (const ValueTree& state);
  44895. const String getText() const;
  44896. void setText (const String& newText, UndoManager* undoManager);
  44897. Value getTextValue (UndoManager* undoManager);
  44898. const Colour getColour() const;
  44899. void setColour (const Colour& newColour, UndoManager* undoManager);
  44900. const Justification getJustification() const;
  44901. void setJustification (const Justification& newJustification, UndoManager* undoManager);
  44902. const Font getFont() const;
  44903. void setFont (const Font& newFont, UndoManager* undoManager);
  44904. Value getFontValue (UndoManager* undoManager);
  44905. const RelativeParallelogram getBoundingBox() const;
  44906. void setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager);
  44907. const RelativePoint getFontSizeControlPoint() const;
  44908. void setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager);
  44909. static const Identifier text, colour, font, justification, topLeft, topRight, bottomLeft, fontSizeAnchor;
  44910. };
  44911. juce_UseDebuggingNewOperator
  44912. private:
  44913. RelativeParallelogram bounds;
  44914. RelativePoint fontSizeControlPoint;
  44915. Font font;
  44916. String text;
  44917. Colour colour;
  44918. Justification justification;
  44919. DrawableText& operator= (const DrawableText&);
  44920. };
  44921. #endif // __JUCE_DRAWABLETEXT_JUCEHEADER__
  44922. /*** End of inlined file: juce_DrawableText.h ***/
  44923. #endif
  44924. #ifndef __JUCE_DROPSHADOWEFFECT_JUCEHEADER__
  44925. #endif
  44926. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44927. /*** Start of inlined file: juce_GlowEffect.h ***/
  44928. #ifndef __JUCE_GLOWEFFECT_JUCEHEADER__
  44929. #define __JUCE_GLOWEFFECT_JUCEHEADER__
  44930. /**
  44931. A component effect that adds a coloured blur around the component's contents.
  44932. (This will only work on non-opaque components).
  44933. @see Component::setComponentEffect, DropShadowEffect
  44934. */
  44935. class JUCE_API GlowEffect : public ImageEffectFilter
  44936. {
  44937. public:
  44938. /** Creates a default 'glow' effect.
  44939. To customise its appearance, use the setGlowProperties() method.
  44940. */
  44941. GlowEffect();
  44942. /** Destructor. */
  44943. ~GlowEffect();
  44944. /** Sets the glow's radius and colour.
  44945. The radius is how large the blur should be, and the colour is
  44946. used to render it (for a less intense glow, lower the colour's
  44947. opacity).
  44948. */
  44949. void setGlowProperties (float newRadius,
  44950. const Colour& newColour);
  44951. /** @internal */
  44952. void applyEffect (Image& sourceImage, Graphics& destContext);
  44953. juce_UseDebuggingNewOperator
  44954. private:
  44955. float radius;
  44956. Colour colour;
  44957. };
  44958. #endif // __JUCE_GLOWEFFECT_JUCEHEADER__
  44959. /*** End of inlined file: juce_GlowEffect.h ***/
  44960. #endif
  44961. #ifndef __JUCE_IMAGEEFFECTFILTER_JUCEHEADER__
  44962. #endif
  44963. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44964. /*** Start of inlined file: juce_ReduceOpacityEffect.h ***/
  44965. #ifndef __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44966. #define __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44967. /**
  44968. An effect filter that reduces the image's opacity.
  44969. This can be used to make a component (and its child components) more
  44970. transparent.
  44971. @see Component::setComponentEffect
  44972. */
  44973. class JUCE_API ReduceOpacityEffect : public ImageEffectFilter
  44974. {
  44975. public:
  44976. /** Creates the effect object.
  44977. The opacity of the component to which the effect is applied will be
  44978. scaled by the given factor (in the range 0 to 1.0f).
  44979. */
  44980. ReduceOpacityEffect (float opacity = 1.0f);
  44981. /** Destructor. */
  44982. ~ReduceOpacityEffect();
  44983. /** Sets how much to scale the component's opacity.
  44984. @param newOpacity should be between 0 and 1.0f
  44985. */
  44986. void setOpacity (float newOpacity);
  44987. /** @internal */
  44988. void applyEffect (Image& sourceImage, Graphics& destContext);
  44989. juce_UseDebuggingNewOperator
  44990. private:
  44991. float opacity;
  44992. };
  44993. #endif // __JUCE_REDUCEOPACITYEFFECT_JUCEHEADER__
  44994. /*** End of inlined file: juce_ReduceOpacityEffect.h ***/
  44995. #endif
  44996. #ifndef __JUCE_FONT_JUCEHEADER__
  44997. #endif
  44998. #ifndef __JUCE_GLYPHARRANGEMENT_JUCEHEADER__
  44999. #endif
  45000. #ifndef __JUCE_TEXTLAYOUT_JUCEHEADER__
  45001. #endif
  45002. #ifndef __JUCE_TYPEFACE_JUCEHEADER__
  45003. #endif
  45004. #ifndef __JUCE_AFFINETRANSFORM_JUCEHEADER__
  45005. #endif
  45006. #ifndef __JUCE_BORDERSIZE_JUCEHEADER__
  45007. #endif
  45008. #ifndef __JUCE_LINE_JUCEHEADER__
  45009. #endif
  45010. #ifndef __JUCE_PATH_JUCEHEADER__
  45011. #endif
  45012. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  45013. /*** Start of inlined file: juce_PathIterator.h ***/
  45014. #ifndef __JUCE_PATHITERATOR_JUCEHEADER__
  45015. #define __JUCE_PATHITERATOR_JUCEHEADER__
  45016. /**
  45017. Flattens a Path object into a series of straight-line sections.
  45018. Use one of these to iterate through a Path object, and it will convert
  45019. all the curves into line sections so it's easy to render or perform
  45020. geometric operations on.
  45021. @see Path
  45022. */
  45023. class JUCE_API PathFlatteningIterator
  45024. {
  45025. public:
  45026. /** Creates a PathFlatteningIterator.
  45027. After creation, use the next() method to initialise the fields in the
  45028. object with the first line's position.
  45029. @param path the path to iterate along
  45030. @param transform a transform to apply to each point in the path being iterated
  45031. @param tolerence the amount by which the curves are allowed to deviate from the
  45032. lines into which they are being broken down - a higher tolerence
  45033. is a bit faster, but less smooth.
  45034. */
  45035. PathFlatteningIterator (const Path& path,
  45036. const AffineTransform& transform = AffineTransform::identity,
  45037. float tolerence = 6.0f);
  45038. /** Destructor. */
  45039. ~PathFlatteningIterator();
  45040. /** Fetches the next line segment from the path.
  45041. This will update the member variables x1, y1, x2, y2, subPathIndex and closesSubPath
  45042. so that they describe the new line segment.
  45043. @returns false when there are no more lines to fetch.
  45044. */
  45045. bool next();
  45046. float x1; /**< The x position of the start of the current line segment. */
  45047. float y1; /**< The y position of the start of the current line segment. */
  45048. float x2; /**< The x position of the end of the current line segment. */
  45049. float y2; /**< The y position of the end of the current line segment. */
  45050. /** Indicates whether the current line segment is closing a sub-path.
  45051. If the current line is the one that connects the end of a sub-path
  45052. back to the start again, this will be true.
  45053. */
  45054. bool closesSubPath;
  45055. /** The index of the current line within the current sub-path.
  45056. E.g. you can use this to see whether the line is the first one in the
  45057. subpath by seeing if it's 0.
  45058. */
  45059. int subPathIndex;
  45060. /** Returns true if the current segment is the last in the current sub-path. */
  45061. bool isLastInSubpath() const throw() { return stackPos == stackBase.getData()
  45062. && (index >= path.numElements || points [index] == Path::moveMarker); }
  45063. juce_UseDebuggingNewOperator
  45064. private:
  45065. const Path& path;
  45066. const AffineTransform transform;
  45067. float* points;
  45068. float tolerence, subPathCloseX, subPathCloseY;
  45069. const bool isIdentityTransform;
  45070. HeapBlock <float> stackBase;
  45071. float* stackPos;
  45072. size_t index, stackSize;
  45073. PathFlatteningIterator (const PathFlatteningIterator&);
  45074. PathFlatteningIterator& operator= (const PathFlatteningIterator&);
  45075. };
  45076. #endif // __JUCE_PATHITERATOR_JUCEHEADER__
  45077. /*** End of inlined file: juce_PathIterator.h ***/
  45078. #endif
  45079. #ifndef __JUCE_PATHSTROKETYPE_JUCEHEADER__
  45080. #endif
  45081. #ifndef __JUCE_POINT_JUCEHEADER__
  45082. #endif
  45083. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45084. /*** Start of inlined file: juce_PositionedRectangle.h ***/
  45085. #ifndef __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45086. #define __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45087. /**
  45088. A rectangle whose co-ordinates can be defined in terms of absolute or
  45089. proportional distances.
  45090. Designed mainly for storing component positions, this gives you a lot of
  45091. control over how each co-ordinate is stored, either as an absolute position,
  45092. or as a proportion of the size of a parent rectangle.
  45093. It also allows you to define the anchor points by which the rectangle is
  45094. positioned, so for example you could specify that the top right of the
  45095. rectangle should be an absolute distance from its parent's bottom-right corner.
  45096. This object can be stored as a string, which takes the form "x y w h", including
  45097. symbols like '%' and letters to indicate the anchor point. See its toString()
  45098. method for more info.
  45099. Example usage:
  45100. @code
  45101. class MyComponent
  45102. {
  45103. void resized()
  45104. {
  45105. // this will set the child component's x to be 20% of our width, its y
  45106. // to be 30, its width to be 150, and its height to be 50% of our
  45107. // height..
  45108. const PositionedRectangle pos1 ("20% 30 150 50%");
  45109. pos1.applyToComponent (*myChildComponent1);
  45110. // this will inset the child component with a gap of 10 pixels
  45111. // around each of its edges..
  45112. const PositionedRectangle pos2 ("10 10 20M 20M");
  45113. pos2.applyToComponent (*myChildComponent2);
  45114. }
  45115. };
  45116. @endcode
  45117. */
  45118. class JUCE_API PositionedRectangle
  45119. {
  45120. public:
  45121. /** Creates an empty rectangle with all co-ordinates set to zero.
  45122. The default anchor point is top-left; the default
  45123. */
  45124. PositionedRectangle() throw();
  45125. /** Initialises a PositionedRectangle from a saved string version.
  45126. The string must be in the format generated by toString().
  45127. */
  45128. PositionedRectangle (const String& stringVersion) throw();
  45129. /** Creates a copy of another PositionedRectangle. */
  45130. PositionedRectangle (const PositionedRectangle& other) throw();
  45131. /** Copies another PositionedRectangle. */
  45132. PositionedRectangle& operator= (const PositionedRectangle& other) throw();
  45133. /** Destructor. */
  45134. ~PositionedRectangle() throw();
  45135. /** Returns a string version of this position, from which it can later be
  45136. re-generated.
  45137. The format is four co-ordinates, "x y w h".
  45138. - If a co-ordinate is absolute, it is stored as an integer, e.g. "100".
  45139. - If a co-ordinate is proportional to its parent's width or height, it is stored
  45140. as a percentage, e.g. "80%".
  45141. - If the X or Y co-ordinate is relative to the parent's right or bottom edge, the
  45142. number has "R" appended to it, e.g. "100R" means a distance of 100 pixels from
  45143. the parent's right-hand edge.
  45144. - If the X or Y co-ordinate is relative to the parent's centre, the number has "C"
  45145. appended to it, e.g. "-50C" would be 50 pixels left of the parent's centre.
  45146. - If the X or Y co-ordinate should be anchored at the component's right or bottom
  45147. edge, then it has "r" appended to it. So "-50Rr" would mean that this component's
  45148. right-hand edge should be 50 pixels left of the parent's right-hand edge.
  45149. - If the X or Y co-ordinate should be anchored at the component's centre, then it
  45150. has "c" appended to it. So "-50Rc" would mean that this component's
  45151. centre should be 50 pixels left of the parent's right-hand edge. "40%c" means that
  45152. this component's centre should be placed 40% across the parent's width.
  45153. - If it's a width or height that should use the parentSizeMinusAbsolute mode, then
  45154. the number has "M" appended to it.
  45155. To reload a stored string, use the constructor that takes a string parameter.
  45156. */
  45157. const String toString() const throw();
  45158. /** Calculates the absolute position, given the size of the space that
  45159. it should go in.
  45160. This will work out any proportional distances and sizes relative to the
  45161. target rectangle, and will return the absolute position.
  45162. @see applyToComponent
  45163. */
  45164. const Rectangle<int> getRectangle (const Rectangle<int>& targetSpaceToBeRelativeTo) const throw();
  45165. /** Same as getRectangle(), but returning the values as doubles rather than ints.
  45166. */
  45167. void getRectangleDouble (const Rectangle<int>& targetSpaceToBeRelativeTo,
  45168. double& x,
  45169. double& y,
  45170. double& width,
  45171. double& height) const throw();
  45172. /** This sets the bounds of the given component to this position.
  45173. This is equivalent to writing:
  45174. @code
  45175. comp.setBounds (getRectangle (Rectangle<int> (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  45176. @endcode
  45177. @see getRectangle, updateFromComponent
  45178. */
  45179. void applyToComponent (Component& comp) const throw();
  45180. /** Updates this object's co-ordinates to match the given rectangle.
  45181. This will set all co-ordinates based on the given rectangle, re-calculating
  45182. any proportional distances, and using the current anchor points.
  45183. So for example if the x co-ordinate mode is currently proportional, this will
  45184. re-calculate x based on the rectangle's relative position within the target
  45185. rectangle's width.
  45186. If the target rectangle's width or height are zero then it may not be possible
  45187. to re-calculate some proportional co-ordinates. In this case, those co-ordinates
  45188. will not be changed.
  45189. */
  45190. void updateFrom (const Rectangle<int>& newPosition,
  45191. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45192. /** Same functionality as updateFrom(), but taking doubles instead of ints.
  45193. */
  45194. void updateFromDouble (double x, double y, double width, double height,
  45195. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45196. /** Updates this object's co-ordinates to match the bounds of this component.
  45197. This is equivalent to calling updateFrom() with the component's bounds and
  45198. it parent size.
  45199. If the component doesn't currently have a parent, then proportional co-ordinates
  45200. might not be updated because it would need to know the parent's size to do the
  45201. maths for this.
  45202. */
  45203. void updateFromComponent (const Component& comp) throw();
  45204. /** Specifies the point within the rectangle, relative to which it should be positioned. */
  45205. enum AnchorPoint
  45206. {
  45207. anchorAtLeftOrTop = 1 << 0, /**< The x or y co-ordinate specifies where the left or top edge of the rectangle should be. */
  45208. anchorAtRightOrBottom = 1 << 1, /**< The x or y co-ordinate specifies where the right or bottom edge of the rectangle should be. */
  45209. anchorAtCentre = 1 << 2 /**< The x or y co-ordinate specifies where the centre of the rectangle should be. */
  45210. };
  45211. /** Specifies how an x or y co-ordinate should be interpreted. */
  45212. enum PositionMode
  45213. {
  45214. absoluteFromParentTopLeft = 1 << 3, /**< The x or y co-ordinate specifies an absolute distance from the parent's top or left edge. */
  45215. absoluteFromParentBottomRight = 1 << 4, /**< The x or y co-ordinate specifies an absolute distance from the parent's bottom or right edge. */
  45216. absoluteFromParentCentre = 1 << 5, /**< The x or y co-ordinate specifies an absolute distance from the parent's centre. */
  45217. 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. */
  45218. };
  45219. /** Specifies how the width or height should be interpreted. */
  45220. enum SizeMode
  45221. {
  45222. absoluteSize = 1 << 0, /**< The width or height specifies an absolute size. */
  45223. parentSizeMinusAbsolute = 1 << 1, /**< The width or height is an amount that should be subtracted from the parent's width or height. */
  45224. proportionalSize = 1 << 2, /**< The width or height specifies a proportion of the parent's width or height. */
  45225. };
  45226. /** Sets all options for all co-ordinates.
  45227. This requires a reference rectangle to be specified, because if you're changing any
  45228. of the modes from proportional to absolute or vice-versa, then it'll need to convert
  45229. the co-ordinates, and will need to know the parent size so it can calculate this.
  45230. */
  45231. void setModes (const AnchorPoint xAnchorMode,
  45232. const PositionMode xPositionMode,
  45233. const AnchorPoint yAnchorMode,
  45234. const PositionMode yPositionMode,
  45235. const SizeMode widthMode,
  45236. const SizeMode heightMode,
  45237. const Rectangle<int>& targetSpaceToBeRelativeTo) throw();
  45238. /** Returns the anchoring mode for the x co-ordinate.
  45239. To change any of the modes, use setModes().
  45240. */
  45241. AnchorPoint getAnchorPointX() const throw();
  45242. /** Returns the positioning mode for the x co-ordinate.
  45243. To change any of the modes, use setModes().
  45244. */
  45245. PositionMode getPositionModeX() const throw();
  45246. /** Returns the raw x co-ordinate.
  45247. If the x position mode is absolute, then this will be the absolute value. If it's
  45248. proportional, then this will be a fractional proportion, where 1.0 means the full
  45249. width of the parent space.
  45250. */
  45251. double getX() const throw() { return x; }
  45252. /** Sets the raw value of the x co-ordinate.
  45253. See getX() for the meaning of this value.
  45254. */
  45255. void setX (const double newX) throw() { x = newX; }
  45256. /** Returns the anchoring mode for the y co-ordinate.
  45257. To change any of the modes, use setModes().
  45258. */
  45259. AnchorPoint getAnchorPointY() const throw();
  45260. /** Returns the positioning mode for the y co-ordinate.
  45261. To change any of the modes, use setModes().
  45262. */
  45263. PositionMode getPositionModeY() const throw();
  45264. /** Returns the raw y co-ordinate.
  45265. If the y position mode is absolute, then this will be the absolute value. If it's
  45266. proportional, then this will be a fractional proportion, where 1.0 means the full
  45267. height of the parent space.
  45268. */
  45269. double getY() const throw() { return y; }
  45270. /** Sets the raw value of the y co-ordinate.
  45271. See getY() for the meaning of this value.
  45272. */
  45273. void setY (const double newY) throw() { y = newY; }
  45274. /** Returns the mode used to calculate the width.
  45275. To change any of the modes, use setModes().
  45276. */
  45277. SizeMode getWidthMode() const throw();
  45278. /** Returns the raw width value.
  45279. If the width mode is absolute, then this will be the absolute value. If the mode is
  45280. proportional, then this will be a fractional proportion, where 1.0 means the full
  45281. width of the parent space.
  45282. */
  45283. double getWidth() const throw() { return w; }
  45284. /** Sets the raw width value.
  45285. See getWidth() for the details about what this value means.
  45286. */
  45287. void setWidth (const double newWidth) throw() { w = newWidth; }
  45288. /** Returns the mode used to calculate the height.
  45289. To change any of the modes, use setModes().
  45290. */
  45291. SizeMode getHeightMode() const throw();
  45292. /** Returns the raw height value.
  45293. If the height mode is absolute, then this will be the absolute value. If the mode is
  45294. proportional, then this will be a fractional proportion, where 1.0 means the full
  45295. height of the parent space.
  45296. */
  45297. double getHeight() const throw() { return h; }
  45298. /** Sets the raw height value.
  45299. See getHeight() for the details about what this value means.
  45300. */
  45301. void setHeight (const double newHeight) throw() { h = newHeight; }
  45302. /** If the size and position are constance, and wouldn't be affected by changes
  45303. in the parent's size, then this will return true.
  45304. */
  45305. bool isPositionAbsolute() const throw();
  45306. /** Compares two objects. */
  45307. bool operator== (const PositionedRectangle& other) const throw();
  45308. /** Compares two objects. */
  45309. bool operator!= (const PositionedRectangle& other) const throw();
  45310. juce_UseDebuggingNewOperator
  45311. private:
  45312. double x, y, w, h;
  45313. uint8 xMode, yMode, wMode, hMode;
  45314. void addPosDescription (String& result, uint8 mode, double value) const throw();
  45315. void addSizeDescription (String& result, uint8 mode, double value) const throw();
  45316. void decodePosString (const String& s, uint8& mode, double& value) throw();
  45317. void decodeSizeString (const String& s, uint8& mode, double& value) throw();
  45318. void applyPosAndSize (double& xOut, double& wOut, double x, double w,
  45319. uint8 xMode, uint8 wMode,
  45320. int parentPos, int parentSize) const throw();
  45321. void updatePosAndSize (double& xOut, double& wOut, double x, double w,
  45322. uint8 xMode, uint8 wMode,
  45323. int parentPos, int parentSize) const throw();
  45324. };
  45325. #endif // __JUCE_POSITIONEDRECTANGLE_JUCEHEADER__
  45326. /*** End of inlined file: juce_PositionedRectangle.h ***/
  45327. #endif
  45328. #ifndef __JUCE_RECTANGLE_JUCEHEADER__
  45329. #endif
  45330. #ifndef __JUCE_RECTANGLELIST_JUCEHEADER__
  45331. #endif
  45332. #ifndef __JUCE_RELATIVECOORDINATE_JUCEHEADER__
  45333. #endif
  45334. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  45335. /*** Start of inlined file: juce_CameraDevice.h ***/
  45336. #ifndef __JUCE_CAMERADEVICE_JUCEHEADER__
  45337. #define __JUCE_CAMERADEVICE_JUCEHEADER__
  45338. #if JUCE_USE_CAMERA || DOXYGEN
  45339. /**
  45340. Receives callbacks with images from a CameraDevice.
  45341. @see CameraDevice::addListener
  45342. */
  45343. class CameraImageListener
  45344. {
  45345. public:
  45346. CameraImageListener() {}
  45347. virtual ~CameraImageListener() {}
  45348. /** This method is called when a new image arrives.
  45349. This may be called by any thread, so be careful about thread-safety,
  45350. and make sure that you process the data as quickly as possible to
  45351. avoid glitching!
  45352. */
  45353. virtual void imageReceived (const Image& image) = 0;
  45354. };
  45355. /**
  45356. Controls any camera capture devices that might be available.
  45357. Use getAvailableDevices() to list the devices that are attached to the
  45358. system, then call openDevice to open one for use. Once you have a CameraDevice
  45359. object, you can get a viewer component from it, and use its methods to
  45360. stream to a file or capture still-frames.
  45361. */
  45362. class JUCE_API CameraDevice
  45363. {
  45364. public:
  45365. /** Destructor. */
  45366. virtual ~CameraDevice();
  45367. /** Returns a list of the available cameras on this machine.
  45368. You can open one of these devices by calling openDevice().
  45369. */
  45370. static const StringArray getAvailableDevices();
  45371. /** Opens a camera device.
  45372. The index parameter indicates which of the items returned by getAvailableDevices()
  45373. to open.
  45374. The size constraints allow the method to choose between different resolutions if
  45375. the camera supports this. If the resolution cam't be specified (e.g. on the Mac)
  45376. then these will be ignored.
  45377. */
  45378. static CameraDevice* openDevice (int deviceIndex,
  45379. int minWidth = 128, int minHeight = 64,
  45380. int maxWidth = 1024, int maxHeight = 768);
  45381. /** Returns the name of this device */
  45382. const String getName() const { return name; }
  45383. /** Creates a component that can be used to display a preview of the
  45384. video from this camera.
  45385. */
  45386. Component* createViewerComponent();
  45387. /** Starts recording video to the specified file.
  45388. You should use getFileExtension() to find out the correct extension to
  45389. use for your filename.
  45390. If the file exists, it will be deleted before the recording starts.
  45391. This method may not start recording instantly, so if you need to know the
  45392. exact time at which the file begins, you can call getTimeOfFirstRecordedFrame()
  45393. after the recording has finished.
  45394. The quality parameter can be 0, 1, or 2, to indicate low, medium, or high. It may
  45395. or may not be used, depending on the driver.
  45396. */
  45397. void startRecordingToFile (const File& file, int quality = 2);
  45398. /** Stops recording, after a call to startRecordingToFile().
  45399. */
  45400. void stopRecording();
  45401. /** Returns the file extension that should be used for the files
  45402. that you pass to startRecordingToFile().
  45403. This may be platform-specific, e.g. ".mov" or ".avi".
  45404. */
  45405. static const String getFileExtension();
  45406. /** After calling stopRecording(), this method can be called to return the timestamp
  45407. of the first frame that was written to the file.
  45408. */
  45409. const Time getTimeOfFirstRecordedFrame() const;
  45410. /** Adds a listener to receive images from the camera.
  45411. Be very careful not to delete the listener without first removing it by calling
  45412. removeListener().
  45413. */
  45414. void addListener (CameraImageListener* listenerToAdd);
  45415. /** Removes a listener that was previously added with addListener().
  45416. */
  45417. void removeListener (CameraImageListener* listenerToRemove);
  45418. juce_UseDebuggingNewOperator
  45419. protected:
  45420. /** @internal */
  45421. CameraDevice (const String& name, int index);
  45422. private:
  45423. void* internal;
  45424. bool isRecording;
  45425. String name;
  45426. CameraDevice (const CameraDevice&);
  45427. CameraDevice& operator= (const CameraDevice&);
  45428. };
  45429. #endif
  45430. #endif // __JUCE_CAMERADEVICE_JUCEHEADER__
  45431. /*** End of inlined file: juce_CameraDevice.h ***/
  45432. #endif
  45433. #ifndef __JUCE_IMAGE_JUCEHEADER__
  45434. #endif
  45435. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  45436. /*** Start of inlined file: juce_ImageCache.h ***/
  45437. #ifndef __JUCE_IMAGECACHE_JUCEHEADER__
  45438. #define __JUCE_IMAGECACHE_JUCEHEADER__
  45439. /**
  45440. A global cache of images that have been loaded from files or memory.
  45441. If you're loading an image and may need to use the image in more than one
  45442. place, this is used to allow the same image to be shared rather than loading
  45443. multiple copies into memory.
  45444. Another advantage is that after images are released, they will be kept in
  45445. memory for a few seconds before it is actually deleted, so if you're repeatedly
  45446. loading/deleting the same image, it'll reduce the chances of having to reload it
  45447. each time.
  45448. @see Image, ImageFileFormat
  45449. */
  45450. class JUCE_API ImageCache
  45451. {
  45452. public:
  45453. /** Loads an image from a file, (or just returns the image if it's already cached).
  45454. If the cache already contains an image that was loaded from this file,
  45455. that image will be returned. Otherwise, this method will try to load the
  45456. file, add it to the cache, and return it.
  45457. Remember that the image returned is shared, so drawing into it might
  45458. affect other things that are using it! If you want to draw on it, first
  45459. call Image::duplicateIfShared()
  45460. @param file the file to try to load
  45461. @returns the image, or null if it there was an error loading it
  45462. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  45463. */
  45464. static const Image getFromFile (const File& file);
  45465. /** Loads an image from an in-memory image file, (or just returns the image if it's already cached).
  45466. If the cache already contains an image that was loaded from this block of memory,
  45467. that image will be returned. Otherwise, this method will try to load the
  45468. file, add it to the cache, and return it.
  45469. Remember that the image returned is shared, so drawing into it might
  45470. affect other things that are using it! If you want to draw on it, first
  45471. call Image::duplicateIfShared()
  45472. @param imageData the block of memory containing the image data
  45473. @param dataSize the data size in bytes
  45474. @returns the image, or an invalid image if it there was an error loading it
  45475. @see getFromMemory, getFromCache, ImageFileFormat::loadFrom
  45476. */
  45477. static const Image getFromMemory (const void* imageData, int dataSize);
  45478. /** Checks the cache for an image with a particular hashcode.
  45479. If there's an image in the cache with this hashcode, it will be returned,
  45480. otherwise it will return an invalid image.
  45481. @param hashCode the hash code that was associated with the image by addImageToCache()
  45482. @see addImageToCache
  45483. */
  45484. static const Image getFromHashCode (int64 hashCode);
  45485. /** Adds an image to the cache with a user-defined hash-code.
  45486. The image passed-in will be referenced (not copied) by the cache, so it's probably
  45487. a good idea not to draw into it after adding it, otherwise this will affect all
  45488. instances of it that may be in use.
  45489. @param image the image to add
  45490. @param hashCode the hash-code to associate with it
  45491. @see getFromHashCode
  45492. */
  45493. static void addImageToCache (const Image& image, int64 hashCode);
  45494. /** Changes the amount of time before an unused image will be removed from the cache.
  45495. By default this is about 5 seconds.
  45496. */
  45497. static void setCacheTimeout (int millisecs);
  45498. juce_UseDebuggingNewOperator
  45499. private:
  45500. class Pimpl;
  45501. ImageCache();
  45502. ImageCache (const ImageCache&);
  45503. ImageCache& operator= (const ImageCache&);
  45504. ~ImageCache();
  45505. };
  45506. #endif // __JUCE_IMAGECACHE_JUCEHEADER__
  45507. /*** End of inlined file: juce_ImageCache.h ***/
  45508. #endif
  45509. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45510. /*** Start of inlined file: juce_ImageConvolutionKernel.h ***/
  45511. #ifndef __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45512. #define __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45513. /**
  45514. Represents a filter kernel to use in convoluting an image.
  45515. @see Image::applyConvolution
  45516. */
  45517. class JUCE_API ImageConvolutionKernel
  45518. {
  45519. public:
  45520. /** Creates an empty convulution kernel.
  45521. @param size the length of each dimension of the kernel, so e.g. if the size
  45522. is 5, it will create a 5x5 kernel
  45523. */
  45524. ImageConvolutionKernel (int size);
  45525. /** Destructor. */
  45526. ~ImageConvolutionKernel();
  45527. /** Resets all values in the kernel to zero. */
  45528. void clear();
  45529. /** Returns one of the kernel values. */
  45530. float getKernelValue (int x, int y) const throw();
  45531. /** Sets the value of a specific cell in the kernel.
  45532. The x and y parameters must be in the range 0 < x < getKernelSize().
  45533. @see setOverallSum
  45534. */
  45535. void setKernelValue (int x, int y, float value) throw();
  45536. /** Rescales all values in the kernel to make the total add up to a fixed value.
  45537. This will multiply all values in the kernel by (desiredTotalSum / currentTotalSum).
  45538. */
  45539. void setOverallSum (float desiredTotalSum);
  45540. /** Multiplies all values in the kernel by a value. */
  45541. void rescaleAllValues (float multiplier);
  45542. /** Intialises the kernel for a gaussian blur.
  45543. @param blurRadius this may be larger or smaller than the kernel's actual
  45544. size but this will obviously be wasteful or clip at the
  45545. edges. Ideally the kernel should be just larger than
  45546. (blurRadius * 2).
  45547. */
  45548. void createGaussianBlur (float blurRadius);
  45549. /** Returns the size of the kernel.
  45550. E.g. if it's a 3x3 kernel, this returns 3.
  45551. */
  45552. int getKernelSize() const { return size; }
  45553. /** Applies the kernel to an image.
  45554. @param destImage the image that will receive the resultant convoluted pixels.
  45555. @param sourceImage the source image to read from - this can be the same image as
  45556. the destination, but if different, it must be exactly the same
  45557. size and format.
  45558. @param destinationArea the region of the image to apply the filter to
  45559. */
  45560. void applyToImage (Image& destImage,
  45561. const Image& sourceImage,
  45562. const Rectangle<int>& destinationArea) const;
  45563. juce_UseDebuggingNewOperator
  45564. private:
  45565. HeapBlock <float> values;
  45566. const int size;
  45567. // no reason not to implement these one day..
  45568. ImageConvolutionKernel (const ImageConvolutionKernel&);
  45569. ImageConvolutionKernel& operator= (const ImageConvolutionKernel&);
  45570. };
  45571. #endif // __JUCE_IMAGECONVOLUTIONKERNEL_JUCEHEADER__
  45572. /*** End of inlined file: juce_ImageConvolutionKernel.h ***/
  45573. #endif
  45574. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45575. /*** Start of inlined file: juce_ImageFileFormat.h ***/
  45576. #ifndef __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45577. #define __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45578. /**
  45579. Base-class for codecs that can read and write image file formats such
  45580. as PNG, JPEG, etc.
  45581. This class also contains static methods to make it easy to load images
  45582. from files, streams or from memory.
  45583. @see Image, ImageCache
  45584. */
  45585. class JUCE_API ImageFileFormat
  45586. {
  45587. protected:
  45588. /** Creates an ImageFormat. */
  45589. ImageFileFormat() {}
  45590. public:
  45591. /** Destructor. */
  45592. virtual ~ImageFileFormat() {}
  45593. /** Returns a description of this file format.
  45594. E.g. "JPEG", "PNG"
  45595. */
  45596. virtual const String getFormatName() = 0;
  45597. /** Returns true if the given stream seems to contain data that this format
  45598. understands.
  45599. The format class should only read the first few bytes of the stream and sniff
  45600. for header bytes that it understands.
  45601. @see decodeImage
  45602. */
  45603. virtual bool canUnderstand (InputStream& input) = 0;
  45604. /** Tries to decode and return an image from the given stream.
  45605. This will be called for an image format after calling its canUnderStand() method
  45606. to see if it can handle the stream.
  45607. @param input the stream to read the data from. The stream will be positioned
  45608. at the start of the image data (but this may not necessarily
  45609. be position 0)
  45610. @returns the image that was decoded, or an invalid image if it fails.
  45611. @see loadFrom
  45612. */
  45613. virtual const Image decodeImage (InputStream& input) = 0;
  45614. /** Attempts to write an image to a stream.
  45615. To specify extra information like encoding quality, there will be appropriate parameters
  45616. in the subclasses of the specific file types.
  45617. @returns true if it nothing went wrong.
  45618. */
  45619. virtual bool writeImageToStream (const Image& sourceImage,
  45620. OutputStream& destStream) = 0;
  45621. /** Tries the built-in decoders to see if it can find one to read this stream.
  45622. There are currently built-in decoders for PNG, JPEG and GIF formats.
  45623. The object that is returned should not be deleted by the caller.
  45624. @see canUnderstand, decodeImage, loadFrom
  45625. */
  45626. static ImageFileFormat* findImageFormatForStream (InputStream& input);
  45627. /** Tries to load an image from a stream.
  45628. This will use the findImageFormatForStream() method to locate a suitable
  45629. codec, and use that to load the image.
  45630. @returns the image that was decoded, or an invalid image if it fails.
  45631. */
  45632. static const Image loadFrom (InputStream& input);
  45633. /** Tries to load an image from a file.
  45634. This will use the findImageFormatForStream() method to locate a suitable
  45635. codec, and use that to load the image.
  45636. @returns the image that was decoded, or an invalid image if it fails.
  45637. */
  45638. static const Image loadFrom (const File& file);
  45639. /** Tries to load an image from a block of raw image data.
  45640. This will use the findImageFormatForStream() method to locate a suitable
  45641. codec, and use that to load the image.
  45642. @returns the image that was decoded, or an invalid image if it fails.
  45643. */
  45644. static const Image loadFrom (const void* rawData,
  45645. const int numBytesOfData);
  45646. };
  45647. /**
  45648. A type of ImageFileFormat for reading and writing PNG files.
  45649. @see ImageFileFormat, JPEGImageFormat
  45650. */
  45651. class JUCE_API PNGImageFormat : public ImageFileFormat
  45652. {
  45653. public:
  45654. PNGImageFormat();
  45655. ~PNGImageFormat();
  45656. const String getFormatName();
  45657. bool canUnderstand (InputStream& input);
  45658. const Image decodeImage (InputStream& input);
  45659. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45660. };
  45661. /**
  45662. A type of ImageFileFormat for reading and writing JPEG files.
  45663. @see ImageFileFormat, PNGImageFormat
  45664. */
  45665. class JUCE_API JPEGImageFormat : public ImageFileFormat
  45666. {
  45667. public:
  45668. JPEGImageFormat();
  45669. ~JPEGImageFormat();
  45670. /** Specifies the quality to be used when writing a JPEG file.
  45671. @param newQuality a value 0 to 1.0, where 0 is low quality, 1.0 is best, or
  45672. any negative value is "default" quality
  45673. */
  45674. void setQuality (const float newQuality);
  45675. const String getFormatName();
  45676. bool canUnderstand (InputStream& input);
  45677. const Image decodeImage (InputStream& input);
  45678. bool writeImageToStream (const Image& sourceImage, OutputStream& destStream);
  45679. private:
  45680. float quality;
  45681. };
  45682. #endif // __JUCE_IMAGEFILEFORMAT_JUCEHEADER__
  45683. /*** End of inlined file: juce_ImageFileFormat.h ***/
  45684. #endif
  45685. #ifndef __JUCE_DELETEDATSHUTDOWN_JUCEHEADER__
  45686. #endif
  45687. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45688. /*** Start of inlined file: juce_FileBasedDocument.h ***/
  45689. #ifndef __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45690. #define __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45691. /**
  45692. A class to take care of the logic involved with the loading/saving of some kind
  45693. of document.
  45694. There's quite a lot of tedious logic involved in writing all the load/save/save-as
  45695. functions you need for documents that get saved to a file, so this class attempts
  45696. to abstract most of the boring stuff.
  45697. Your subclass should just implement all the pure virtual methods, and you can
  45698. then use the higher-level public methods to do the load/save dialogs, to warn the user
  45699. about overwriting files, etc.
  45700. The document object keeps track of whether it has changed since it was last saved or
  45701. loaded, so when you change something, call its changed() method. This will set a
  45702. flag so it knows it needs saving, and will also broadcast a change message using the
  45703. ChangeBroadcaster base class.
  45704. @see ChangeBroadcaster
  45705. */
  45706. class JUCE_API FileBasedDocument : public ChangeBroadcaster
  45707. {
  45708. public:
  45709. /** Creates a FileBasedDocument.
  45710. @param fileExtension the extension to use when loading/saving files, e.g. ".doc"
  45711. @param fileWildCard the wildcard to use in file dialogs, e.g. "*.doc"
  45712. @param openFileDialogTitle the title to show on an open-file dialog, e.g. "Choose a file to open.."
  45713. @param saveFileDialogTitle the title to show on an save-file dialog, e.g. "Choose a file to save as.."
  45714. */
  45715. FileBasedDocument (const String& fileExtension,
  45716. const String& fileWildCard,
  45717. const String& openFileDialogTitle,
  45718. const String& saveFileDialogTitle);
  45719. /** Destructor. */
  45720. virtual ~FileBasedDocument();
  45721. /** Returns true if the changed() method has been called since the file was
  45722. last saved or loaded.
  45723. @see resetChangedFlag, changed
  45724. */
  45725. bool hasChangedSinceSaved() const { return changedSinceSave; }
  45726. /** Called to indicate that the document has changed and needs saving.
  45727. This method will also trigger a change message to be sent out using the
  45728. ChangeBroadcaster base class.
  45729. After calling the method, the hasChangedSinceSaved() method will return true, until
  45730. it is reset either by saving to a file or using the resetChangedFlag() method.
  45731. @see hasChangedSinceSaved, resetChangedFlag
  45732. */
  45733. virtual void changed();
  45734. /** Sets the state of the 'changed' flag.
  45735. The 'changed' flag is set to true when the changed() method is called - use this method
  45736. to reset it or to set it without also broadcasting a change message.
  45737. @see changed, hasChangedSinceSaved
  45738. */
  45739. void setChangedFlag (bool hasChanged);
  45740. /** Tries to open a file.
  45741. If the file opens correctly, the document's file (see the getFile() method) is set
  45742. to this new one; if it fails, the document's file is left unchanged, and optionally
  45743. a message box is shown telling the user there was an error.
  45744. @returns true if the new file loaded successfully
  45745. @see loadDocument, loadFromUserSpecifiedFile
  45746. */
  45747. bool loadFrom (const File& fileToLoadFrom,
  45748. bool showMessageOnFailure);
  45749. /** Asks the user for a file and tries to load it.
  45750. This will pop up a dialog box using the title, file extension and
  45751. wildcard specified in the document's constructor, and asks the user
  45752. for a file. If they pick one, the loadFrom() method is used to
  45753. try to load it, optionally showing a message if it fails.
  45754. @returns true if a file was loaded; false if the user cancelled or if they
  45755. picked a file which failed to load correctly
  45756. @see loadFrom
  45757. */
  45758. bool loadFromUserSpecifiedFile (bool showMessageOnFailure);
  45759. /** A set of possible outcomes of one of the save() methods
  45760. */
  45761. enum SaveResult
  45762. {
  45763. savedOk = 0, /**< indicates that a file was saved successfully. */
  45764. userCancelledSave, /**< indicates that the user aborted the save operation. */
  45765. failedToWriteToFile /**< indicates that it tried to write to a file but this failed. */
  45766. };
  45767. /** Tries to save the document to the last file it was saved or loaded from.
  45768. This will always try to write to the file, even if the document isn't flagged as
  45769. having changed.
  45770. @param askUserForFileIfNotSpecified if there's no file currently specified and this is
  45771. true, it will prompt the user to pick a file, as if
  45772. saveAsInteractive() was called.
  45773. @param showMessageOnFailure if true it will show a warning message when if the
  45774. save operation fails
  45775. @see saveIfNeededAndUserAgrees, saveAs, saveAsInteractive
  45776. */
  45777. SaveResult save (bool askUserForFileIfNotSpecified,
  45778. bool showMessageOnFailure);
  45779. /** If the file needs saving, it'll ask the user if that's what they want to do, and save
  45780. it if they say yes.
  45781. If you've got a document open and want to close it (e.g. to quit the app), this is the
  45782. method to call.
  45783. If the document doesn't need saving it'll return the value savedOk so
  45784. you can go ahead and delete the document.
  45785. If it does need saving it'll prompt the user, and if they say "discard changes" it'll
  45786. return savedOk, so again, you can safely delete the document.
  45787. If the user clicks "cancel", it'll return userCancelledSave, so if you can abort the
  45788. close-document operation.
  45789. And if they click "save changes", it'll try to save and either return savedOk, or
  45790. failedToWriteToFile if there was a problem.
  45791. @see save, saveAs, saveAsInteractive
  45792. */
  45793. SaveResult saveIfNeededAndUserAgrees();
  45794. /** Tries to save the document to a specified file.
  45795. If this succeeds, it'll also change the document's internal file (as returned by
  45796. the getFile() method). If it fails, the file will be left unchanged.
  45797. @param newFile the file to try to write to
  45798. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45799. the user first if they want to overwrite it
  45800. @param askUserForFileIfNotSpecified if the file is non-existent and this is true, it'll
  45801. use the saveAsInteractive() method to ask the user for a
  45802. filename
  45803. @param showMessageOnFailure if true and the write operation fails, it'll show
  45804. a message box to warn the user
  45805. @see saveIfNeededAndUserAgrees, save, saveAsInteractive
  45806. */
  45807. SaveResult saveAs (const File& newFile,
  45808. bool warnAboutOverwritingExistingFiles,
  45809. bool askUserForFileIfNotSpecified,
  45810. bool showMessageOnFailure);
  45811. /** Prompts the user for a filename and tries to save to it.
  45812. This will pop up a dialog box using the title, file extension and
  45813. wildcard specified in the document's constructor, and asks the user
  45814. for a file. If they pick one, the saveAs() method is used to try to save
  45815. to this file.
  45816. @param warnAboutOverwritingExistingFiles if true and the file exists, it'll ask
  45817. the user first if they want to overwrite it
  45818. @see saveIfNeededAndUserAgrees, save, saveAs
  45819. */
  45820. SaveResult saveAsInteractive (bool warnAboutOverwritingExistingFiles);
  45821. /** Returns the file that this document was last successfully saved or loaded from.
  45822. When the document object is created, this will be set to File::nonexistent.
  45823. It is changed when one of the load or save methods is used, or when setFile()
  45824. is used to explicitly set it.
  45825. */
  45826. const File getFile() const { return documentFile; }
  45827. /** Sets the file that this document thinks it was loaded from.
  45828. This won't actually load anything - it just changes the file stored internally.
  45829. @see getFile
  45830. */
  45831. void setFile (const File& newFile);
  45832. protected:
  45833. /** Overload this to return the title of the document.
  45834. This is used in message boxes, filenames and file choosers, so it should be
  45835. something sensible.
  45836. */
  45837. virtual const String getDocumentTitle() = 0;
  45838. /** This method should try to load your document from the given file.
  45839. If it fails, it should return an error message. If it succeeds, it should return
  45840. an empty string.
  45841. */
  45842. virtual const String loadDocument (const File& file) = 0;
  45843. /** This method should try to write your document to the given file.
  45844. If it fails, it should return an error message. If it succeeds, it should return
  45845. an empty string.
  45846. */
  45847. virtual const String saveDocument (const File& file) = 0;
  45848. /** This is used for dialog boxes to make them open at the last folder you
  45849. were using.
  45850. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45851. the last document that was used - you might want to store this value
  45852. in a static variable, or even in your application's properties. It should
  45853. be a global setting rather than a property of this object.
  45854. This method works very well in conjunction with a RecentlyOpenedFilesList
  45855. object to manage your recent-files list.
  45856. As a default value, it's ok to return File::nonexistent, and the document
  45857. object will use a sensible one instead.
  45858. @see RecentlyOpenedFilesList
  45859. */
  45860. virtual const File getLastDocumentOpened() = 0;
  45861. /** This is used for dialog boxes to make them open at the last folder you
  45862. were using.
  45863. getLastDocumentOpened() and setLastDocumentOpened() are used to store
  45864. the last document that was used - you might want to store this value
  45865. in a static variable, or even in your application's properties. It should
  45866. be a global setting rather than a property of this object.
  45867. This method works very well in conjunction with a RecentlyOpenedFilesList
  45868. object to manage your recent-files list.
  45869. @see RecentlyOpenedFilesList
  45870. */
  45871. virtual void setLastDocumentOpened (const File& file) = 0;
  45872. public:
  45873. juce_UseDebuggingNewOperator
  45874. private:
  45875. File documentFile;
  45876. bool changedSinceSave;
  45877. String fileExtension, fileWildcard, openFileDialogTitle, saveFileDialogTitle;
  45878. FileBasedDocument (const FileBasedDocument&);
  45879. FileBasedDocument& operator= (const FileBasedDocument&);
  45880. };
  45881. #endif // __JUCE_FILEBASEDDOCUMENT_JUCEHEADER__
  45882. /*** End of inlined file: juce_FileBasedDocument.h ***/
  45883. #endif
  45884. #ifndef __JUCE_PROPERTIESFILE_JUCEHEADER__
  45885. #endif
  45886. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45887. /*** Start of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45888. #ifndef __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45889. #define __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45890. /**
  45891. Manages a set of files for use as a list of recently-opened documents.
  45892. This is a handy class for holding your list of recently-opened documents, with
  45893. helpful methods for things like purging any non-existent files, automatically
  45894. adding them to a menu, and making persistence easy.
  45895. @see File, FileBasedDocument
  45896. */
  45897. class JUCE_API RecentlyOpenedFilesList
  45898. {
  45899. public:
  45900. /** Creates an empty list.
  45901. */
  45902. RecentlyOpenedFilesList();
  45903. /** Destructor. */
  45904. ~RecentlyOpenedFilesList();
  45905. /** Sets a limit for the number of files that will be stored in the list.
  45906. When addFile() is called, then if there is no more space in the list, the
  45907. least-recently added file will be dropped.
  45908. @see getMaxNumberOfItems
  45909. */
  45910. void setMaxNumberOfItems (int newMaxNumber);
  45911. /** Returns the number of items that this list will store.
  45912. @see setMaxNumberOfItems
  45913. */
  45914. int getMaxNumberOfItems() const throw() { return maxNumberOfItems; }
  45915. /** Returns the number of files in the list.
  45916. The most recently added file is always at index 0.
  45917. */
  45918. int getNumFiles() const;
  45919. /** Returns one of the files in the list.
  45920. The most recently added file is always at index 0.
  45921. */
  45922. const File getFile (int index) const;
  45923. /** Returns an array of all the absolute pathnames in the list.
  45924. */
  45925. const StringArray& getAllFilenames() const throw() { return files; }
  45926. /** Clears all the files from the list. */
  45927. void clear();
  45928. /** Adds a file to the list.
  45929. The file will be added at index 0. If this file is already in the list, it will
  45930. be moved up to index 0, but a file can only appear once in the list.
  45931. If the list already contains the maximum number of items that is permitted, the
  45932. least-recently added file will be dropped from the end.
  45933. */
  45934. void addFile (const File& file);
  45935. /** Checks each of the files in the list, removing any that don't exist.
  45936. You might want to call this after reloading a list of files, or before putting them
  45937. on a menu.
  45938. */
  45939. void removeNonExistentFiles();
  45940. /** Adds entries to a menu, representing each of the files in the list.
  45941. This is handy for creating an "open recent file..." menu in your app. The
  45942. menu items are numbered consecutively starting with the baseItemId value,
  45943. and can either be added as complete pathnames, or just the last part of the
  45944. filename.
  45945. If dontAddNonExistentFiles is true, then each file will be checked and only those
  45946. that exist will be added.
  45947. If filesToAvoid is non-zero, then it is considered to be a zero-terminated array of
  45948. pointers to file objects. Any files that appear in this list will not be added to the
  45949. menu - the reason for this is that you might have a number of files already open, so
  45950. might not want these to be shown in the menu.
  45951. It returns the number of items that were added.
  45952. */
  45953. int createPopupMenuItems (PopupMenu& menuToAddItemsTo,
  45954. int baseItemId,
  45955. bool showFullPaths,
  45956. bool dontAddNonExistentFiles,
  45957. const File** filesToAvoid = 0);
  45958. /** Returns a string that encapsulates all the files in the list.
  45959. The string that is returned can later be passed into restoreFromString() in
  45960. order to recreate the list. This is handy for persisting your list, e.g. in
  45961. a PropertiesFile object.
  45962. @see restoreFromString
  45963. */
  45964. const String toString() const;
  45965. /** Restores the list from a previously stringified version of the list.
  45966. Pass in a stringified version created with toString() in order to persist/restore
  45967. your list.
  45968. @see toString
  45969. */
  45970. void restoreFromString (const String& stringifiedVersion);
  45971. juce_UseDebuggingNewOperator
  45972. private:
  45973. StringArray files;
  45974. int maxNumberOfItems;
  45975. };
  45976. #endif // __JUCE_RECENTLYOPENEDFILESLIST_JUCEHEADER__
  45977. /*** End of inlined file: juce_RecentlyOpenedFilesList.h ***/
  45978. #endif
  45979. #ifndef __JUCE_SELECTEDITEMSET_JUCEHEADER__
  45980. #endif
  45981. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45982. /*** Start of inlined file: juce_SystemClipboard.h ***/
  45983. #ifndef __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45984. #define __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  45985. /**
  45986. Handles reading/writing to the system's clipboard.
  45987. */
  45988. class JUCE_API SystemClipboard
  45989. {
  45990. public:
  45991. /** Copies a string of text onto the clipboard */
  45992. static void copyTextToClipboard (const String& text);
  45993. /** Gets the current clipboard's contents.
  45994. Obviously this might have come from another app, so could contain
  45995. anything..
  45996. */
  45997. static const String getTextFromClipboard();
  45998. };
  45999. #endif // __JUCE_SYSTEMCLIPBOARD_JUCEHEADER__
  46000. /*** End of inlined file: juce_SystemClipboard.h ***/
  46001. #endif
  46002. #ifndef __JUCE_UNDOABLEACTION_JUCEHEADER__
  46003. #endif
  46004. #ifndef __JUCE_UNDOMANAGER_JUCEHEADER__
  46005. #endif
  46006. #endif
  46007. /*** End of inlined file: juce_app_includes.h ***/
  46008. #endif
  46009. #if JUCE_MSVC
  46010. #pragma warning (pop)
  46011. #pragma pack (pop)
  46012. #endif
  46013. END_JUCE_NAMESPACE
  46014. #ifndef DONT_SET_USING_JUCE_NAMESPACE
  46015. #ifdef JUCE_NAMESPACE
  46016. // this will obviously save a lot of typing, but can be disabled by
  46017. // defining DONT_SET_USING_JUCE_NAMESPACE, in case there are conflicts.
  46018. using namespace JUCE_NAMESPACE;
  46019. /* On the Mac, these symbols are defined in the Mac libraries, so
  46020. these macros make it easier to reference them without writing out
  46021. the namespace every time.
  46022. If you run into difficulties where these macros interfere with the contents
  46023. of 3rd party header files, you may need to use the juce_WithoutMacros.h file - see
  46024. the comments in that file for more information.
  46025. */
  46026. #if (JUCE_MAC || JUCE_IPHONE) && ! JUCE_DONT_DEFINE_MACROS
  46027. #define Component JUCE_NAMESPACE::Component
  46028. #define MemoryBlock JUCE_NAMESPACE::MemoryBlock
  46029. #define Point JUCE_NAMESPACE::Point
  46030. #define Button JUCE_NAMESPACE::Button
  46031. #endif
  46032. /* "Rectangle" is defined in some of the newer windows header files, so this makes
  46033. it easier to use the juce version explicitly.
  46034. If you run into difficulties where this macro interferes with other 3rd party header
  46035. files, you may need to use the juce_WithoutMacros.h file - see the comments in that
  46036. file for more information.
  46037. */
  46038. #if JUCE_WINDOWS && ! JUCE_DONT_DEFINE_MACROS
  46039. #define Rectangle JUCE_NAMESPACE::Rectangle
  46040. #endif
  46041. #endif
  46042. #endif
  46043. /* Easy autolinking to the right JUCE libraries under win32.
  46044. Note that this can be disabled by defining DONT_AUTOLINK_TO_JUCE_LIBRARY before
  46045. including this header file.
  46046. */
  46047. #if JUCE_MSVC
  46048. #ifndef DONT_AUTOLINK_TO_JUCE_LIBRARY
  46049. /** If you want your application to link to Juce as a DLL instead of
  46050. a static library (on win32), just define the JUCE_DLL macro before
  46051. including juce.h
  46052. */
  46053. #ifdef JUCE_DLL
  46054. #if JUCE_DEBUG
  46055. #define AUTOLINKEDLIB "JUCE_debug.lib"
  46056. #else
  46057. #define AUTOLINKEDLIB "JUCE.lib"
  46058. #endif
  46059. #else
  46060. #if JUCE_DEBUG
  46061. #ifdef _WIN64
  46062. #define AUTOLINKEDLIB "jucelib_static_x64_debug.lib"
  46063. #else
  46064. #define AUTOLINKEDLIB "jucelib_static_Win32_debug.lib"
  46065. #endif
  46066. #else
  46067. #ifdef _WIN64
  46068. #define AUTOLINKEDLIB "jucelib_static_x64.lib"
  46069. #else
  46070. #define AUTOLINKEDLIB "jucelib_static_Win32.lib"
  46071. #endif
  46072. #endif
  46073. #endif
  46074. #pragma comment(lib, AUTOLINKEDLIB)
  46075. #if ! DONT_LIST_JUCE_AUTOLINKEDLIBS
  46076. #pragma message("JUCE! Library to link to: " AUTOLINKEDLIB)
  46077. #endif
  46078. // Auto-link the other win32 libs that are needed by library calls..
  46079. #if ! (defined (DONT_AUTOLINK_TO_WIN32_LIBRARIES) || defined (JUCE_DLL))
  46080. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  46081. // Auto-links to various win32 libs that are needed by library calls..
  46082. #pragma comment(lib, "kernel32.lib")
  46083. #pragma comment(lib, "user32.lib")
  46084. #pragma comment(lib, "shell32.lib")
  46085. #pragma comment(lib, "gdi32.lib")
  46086. #pragma comment(lib, "vfw32.lib")
  46087. #pragma comment(lib, "comdlg32.lib")
  46088. #pragma comment(lib, "winmm.lib")
  46089. #pragma comment(lib, "wininet.lib")
  46090. #pragma comment(lib, "ole32.lib")
  46091. #pragma comment(lib, "oleaut32.lib")
  46092. #pragma comment(lib, "advapi32.lib")
  46093. #pragma comment(lib, "ws2_32.lib")
  46094. #pragma comment(lib, "comsupp.lib")
  46095. #pragma comment(lib, "version.lib")
  46096. #if JUCE_OPENGL
  46097. #pragma comment(lib, "OpenGL32.Lib")
  46098. #pragma comment(lib, "GlU32.Lib")
  46099. #endif
  46100. #if JUCE_QUICKTIME
  46101. #pragma comment (lib, "QTMLClient.lib")
  46102. #endif
  46103. #if JUCE_USE_CAMERA
  46104. #pragma comment (lib, "Strmiids.lib")
  46105. #pragma comment (lib, "wmvcore.lib")
  46106. #endif
  46107. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  46108. #endif
  46109. #endif
  46110. #endif
  46111. /*
  46112. To start a JUCE app, use this macro: START_JUCE_APPLICATION (AppSubClass) where
  46113. AppSubClass is the name of a class derived from JUCEApplication.
  46114. See the JUCEApplication class documentation (juce_Application.h) for more details.
  46115. */
  46116. #if defined (JUCE_GCC) || defined (__MWERKS__)
  46117. #define START_JUCE_APPLICATION(AppClass) \
  46118. int main (int argc, char* argv[]) \
  46119. { \
  46120. return JUCE_NAMESPACE::JUCEApplication::main (argc, (const char**) argv, new AppClass()); \
  46121. }
  46122. #elif JUCE_WINDOWS
  46123. #ifdef _CONSOLE
  46124. #define START_JUCE_APPLICATION(AppClass) \
  46125. int main (int, char* argv[]) \
  46126. { \
  46127. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  46128. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  46129. }
  46130. #elif ! defined (_AFXDLL)
  46131. #ifdef _WINDOWS_
  46132. #define START_JUCE_APPLICATION(AppClass) \
  46133. int WINAPI WinMain (HINSTANCE, HINSTANCE, LPSTR, int) \
  46134. { \
  46135. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  46136. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  46137. }
  46138. #else
  46139. #define START_JUCE_APPLICATION(AppClass) \
  46140. int __stdcall WinMain (int, int, const char*, int) \
  46141. { \
  46142. JUCE_NAMESPACE::String commandLineString (JUCE_NAMESPACE::PlatformUtilities::getCurrentCommandLineParams()); \
  46143. return JUCE_NAMESPACE::JUCEApplication::main (commandLineString, new AppClass()); \
  46144. }
  46145. #endif
  46146. #endif
  46147. #endif
  46148. #endif // __JUCE_JUCEHEADER__
  46149. /*** End of inlined file: juce.h ***/
  46150. #endif // __JUCE_AMALGAMATED_TEMPLATE_JUCEHEADER__